Compare commits

..
Author SHA1 Message Date
Koichi ITO
538a364c9b
Merge pull request #563 from koic/validate_icon_src_and_sizes
Some checks failed
Conformance Tests / server-conformance (push) Has been cancelled
Validate the src and sizes of an icon against the specification
2026-09-20 01:04:14 +09:00
Koichi ITO
66b2efa11e
Merge pull request #561 from koic/propagate_network_errors_from_protected_resource_metadata_discovery
Surface unreachable Protected Resource Metadata instead of falling back to legacy discovery
2026-09-20 00:03:41 +09:00
Koichi ITO
8173a38280 Validate the src and sizes of an icon against the specification
## Motivation and Context

`MCP::Icon` validated `theme` but accepted anything for `src` and `sizes`: `src:` defaulted to `nil`,
so `MCP::Icon.new.to_h` was `{}`, an icon with no source, and a `sizes` given as a String reached `to_h` unchanged
and serialized as a JSON string where the specification's `Icon` type requires an array of strings.
Nothing on the server side reported either; the server answered every request with 200 and the failure surfaced
in a client, with no reference to the field responsible. The TypeScript SDK types `sizes` as `string[]`
and `src` as required, and the Python SDK's model refuses such an icon at construction, so this SDK was
the one that let it through.

`src` is now a required keyword and must be a non-empty String, `sizes` must be `nil` or an Array of Strings,
and `mime_type` must be `nil` or a String, each refused with `ArgumentError` at construction the way `theme` already was.
The checks stop at the schema's types, as the reference SDKs do: the scheme of a URL and the `WxH` form of a size stay
the caller's to get right. A message names the class of the rejected value, never the value,
since `src` may carry a `data:` URI of any length. Coercing a String into a one-element Array was considered and rejected:
it would hide the caller's mistake that the class exists to surface. The `theme` check let `false` through its truthiness test
and serialized it; it now refuses everything but `nil`, `"light"`, and `"dark"`.

Fixes #562.

## How Has This Been Tested?

New tests in `test/mcp/icon_test.rb`. Against the previous library, an icon without `src` and an icon whose `sizes` is
a String are both constructed and serialized.

## Breaking Changes

`MCP::Icon.new` now raises `ArgumentError` where earlier releases produced an icon the specification's schema rejects:
`src:` is required and must be a non-empty String, so a call without it, or with `nil`, an empty String, or a non-String,
fails; `sizes:` must be `nil` or an Array of Strings, so a String, or an Array holding `nil` or a non-String, fails;
`mime_type:` must be `nil` or a String; `theme:` must be `nil`, `"light"`, or `"dark"`, so `false` fails where it used
to be serialized. Leaving the optional keywords out, or passing `nil` for them, is unchanged.
2026-09-19 17:32:45 +09:00
Koichi ITO
5f429f3fbf
Merge pull request #560 from koic/let_a_provider_customize_the_oauth_http_client
Let a provider customize the HTTP client the OAuth flow uses
2026-09-19 08:00:02 +09:00
Koichi ITO
e1105c7094
Merge pull request #559 from koic/let_providers_without_a_cimd_url_refresh
Let providers without a CIMD URL reader refresh their tokens
2026-09-19 00:29:07 +09:00
Koichi ITO
5081cc5626 Surface unreachable Protected Resource Metadata instead of falling back to legacy discovery
## Motivation and Context

`Flow#locate_authorization_server` treated every failure to fetch Protected Resource Metadata as "the server publishes none"
and took the legacy 2025-03-26 path, where the MCP server's origin becomes the authorization base URL.
A request that never reached the server, or a `5xx` or `429`, says nothing about what the server publishes,
so a transient failure moved the flow to a different authorization server, discarded client information
and tokens bound to the real one on the way, and surfaced as an unrelated error, such as a failed registration at the origin,
rather than as the fetch failure itself. The comment claimed both reference SDKs behave that way, which is not so:
outside browsers the TypeScript SDK propagates network errors from discovery, and the Python SDK propagates them
and refuses the legacy path after a `5xx` or `429` from any candidate.

Discovery now keeps trying candidate URLs until one serves a JSON object and classifies the outcome once they are exhausted.
Like the Python SDK, it remembers a `5xx` or `429` from any candidate before deciding on the legacy path;
moving on to the next candidate after a network error is what the loop already did. `MetadataNotPublishedError`
(a `4xx` other than `429`, or a body that is not a JSON object) is the only failure that selects the legacy path;
`MetadataUnreachableError` (a network error, or a `5xx` or `429`, from any candidate) is raised instead.
Both subclass `AuthorizationError`, so callers rescuing that class keep working, and `MCP::Client::HTTP` still falls back from
a failed refresh to the full flow, which repeats discovery and raises the same way unless the server has recovered.
A body over the response cap is refused outright with a plain `AuthorizationError`, as it already was on the modern path.
The message lists every candidate's failure, with the URL stripped of userinfo, query and fragment and cut to a fixed length,
but otherwise spelled as requested, and with transport and parser messages bounded, as token endpoint diagnostics already are.
The default legacy endpoints for an origin whose own metadata document is absent are unchanged.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb` and `test/mcp/client/oauth/discovery_test.rb`. Against the library
before this change, discovery in the scenarios these tests set up took the legacy path instead of raising.

## Breaking Changes

When no Protected Resource Metadata candidate serves a JSON object, a request that failed to reach the server,
or returned a `5xx` or `429`, now raises instead of attempting the legacy 2025-03-26 discovery at the MCP server's origin,
and a Protected Resource Metadata body over the response cap is refused instead of triggering that fallback.
2026-09-19 00:18:09 +09:00
Koichi ITO
2c33ad061a
Merge pull request #557 from koic/run_the_extension_grants_without_protected_resource_metadata
Let the client_credentials and jwt-bearer grants run without Protected Resource Metadata
2026-09-19 00:12:33 +09:00
Koichi ITO
9455c41b14
Merge pull request #556 from koic/validate_the_issuer_of_legacy_authorization_server_metadata
Validate the issuer of legacy authorization server metadata
2026-09-19 00:11:34 +09:00
Koichi ITO
c9f381a3ee Let a provider customize the HTTP client the OAuth flow uses
## Motivation and Context

`MCP::Client::OAuth::Flow` takes an `http_client_factory:`, but `MCP::Client::HTTP` builds
the flow itself and passes none, so an application using `oauth:` could not add middleware to
the requests the flow makes: Protected Resource Metadata and authorization server metadata discovery,
dynamic client registration, and every token request.
The block that customizes the transport's Faraday connection does not help,
because that connection is bound to the MCP server URL and carries the `headers:` meant for that server,
and the authorization server is a different origin. The TypeScript SDK hands the transport's `fetch` to `auth()`
and the Python SDK sends the provider's requests through the transport's httpx client, so both let
an application instrument these requests; this SDK did not. (#558)

Providers now take `http_client_customizer:`, a callable invoked with the Faraday connection
the flow builds for its own requests, next to the other callables a provider already holds.
It runs after the SDK's defaults (`Accept: application/json`, no redirect following) and
between two middlewares of the SDK's own: `Flow::RequestedURLStamp`, registered before the customizer is invoked,
records the URL the flow asked for on the request environment, and `Flow::RequestedOriginGuard`, registered last,
sees what the customizer's middleware did to the request after that record. A request that would leave that origin,
by following a redirect or rewriting the URL, or that arrives without the record, is refused with
`Flow::DestinationMismatchError` before it reaches the adapter. The record lives on the environment rather than
in `env.request.context`, which stays the application's to fill or replace. The error is an `ArgumentError`
rather than an `AuthorizationError` so neither discovery nor the transport's refresh fallback can absorb
a configuration mistake. The boundary resembles the one the Python SDK keeps for its own requests,
which follows a redirect only within the origin; this flow follows none itself.
`Flow.build_http_client` assembles that connection and `Flow.new(http_client_factory:)` keeps replacing it whole.
Following done inside an adapter cannot be seen by any guard, so the documentation keeps that, `Accept-Encoding`,
and `raise_error` off the list of things a customizer may add, and notes that a recording middleware sees
client credentials and tokens.

Fixes #558.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb`, `test/mcp/client/oauth/http_oauth_test.rb`,
and the three provider test files. Against the library before this change, every one of them fails,
on the unknown keyword or on the missing reader.

## Breaking Changes

None. The customizer is opt-in, and the guard cannot fire on the SDK's own middleware-free connection.
2026-09-18 13:04:33 +09:00
Koichi ITO
f51ccfbe66 Let providers without a CIMD URL reader refresh their tokens
## Motivation and Context

`Flow#refresh!` reads `client_id_metadata_document_url` from the provider unconditionally, once to decide whether
a provider without stored `client_information` may still refresh and once to build the CIMD `client_id`.
Only `Provider` defines that reader: `CrossAppAccessProvider` and `ClientCredentialsProvider`
raise `NoMethodError` once a stored `refresh_token` is found. `MCP::Client::HTTP` calls `refresh!` on any `401` while
a `refresh_token` is stored, so a `jwt-bearer` client whose authorization server issued one fails with
`NoMethodError` on the first expired token instead of refreshing. The error is not an `AuthorizationError`,
so the transport does not fall back to the grant either. RFC 7521 Section 4.1 makes a refresh token unusual
for an assertion grant, not forbidden, and one in storage must not crash the client.

The flow now reads the URL through a duck-typed helper, like `authorization_flow` and `client_assertion`,
so a provider without the reader has no CIMD URL and refreshes with its stored `client_information`:
the `refresh_token` grant is sent with the stored client authentication, and no new ID-JAG assertion is obtained.
The authorization-code registration path reads the URL through the same helper.
The docs now say that a refresh token issued anyway is used on the next `401`, and that the assertion provider
is not called again on refresh.
A refresh token stored without the `issuer` the SDK records is refused for these two providers before any request:
unlike `Provider`, they have no tokens that predate the record, and a refresh asks no validator, so such a token
would be presented to whatever authorization server discovery names. The refusal is an `AuthorizationError`,
which sends the transport back through the grant, and the grant asks.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb` refresh through a `CrossAppAccessProvider` and
a `ClientCredentialsProvider` holding a `refresh_token`, asserting the `refresh_token` grant, the Basic credentials,
and that the assertion provider is not called. A transport test in `test/mcp/client/oauth/http_oauth_test.rb` sends
a `401` to a `CrossAppAccessProvider` with a stored `refresh_token` and expects the refreshed bearer token on the retry.
All three raise `NoMethodError` against the previous library.
Further tests pin the issuer stamp on the refreshed tokens, the refusal of an authorization server that did not issue them
for a `CrossAppAccessProvider`, a clean `AuthorizationError` for a provider with neither the reader
nor stored `client_information`, and registration through DCR for a provider without the reader.
A refresh token without a recorded issuer is refused for both providers before any request is sent.

## Breaking Changes

None.
2026-09-18 11:17:21 +09:00
Koichi ITO
f22ce86e97
Merge pull request #555 from koic/add_token_request_params
Let a provider add parameters to the token requests it makes
2026-09-18 11:13:58 +09:00
Koichi ITO
29e8d3f2b9 Let the client_credentials and jwt-bearer grants run without Protected Resource Metadata
## Motivation and Context

When a server publishes no Protected Resource Metadata, discovery takes the legacy 2025-03-26 path and `prm` is `nil`.
The authorization-code branch of `run!` allowed for that by passing `prm || {}` to `resolve_scope`,
but `run_client_credentials!` and `run_jwt_bearer!` passed `prm` as is, and `resolve_scope` then
called `prm["scopes_supported"]` on `nil`. Without a non-empty challenge scope, a `ClientCredentialsProvider` or
`CrossAppAccessProvider` pointed at such a server therefore failed with `NoMethodError` after discovery and before
the token request or the ID-JAG callback, instead of running its grant against the legacy authorization base
the way `Provider` does.

`resolve_scope` now treats a missing PRM as advertising no scopes, so the challenge scope or the provider's own scope applies,
and the authorization-code branch passes `prm` unchanged like the other two.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb` run the `client_credentials` grant against a PRM-less server with metadata
at the origin, checking the provider's scope, the `resource`, and the recorded issuer, and run the `jwt-bearer` grant against
a server without any metadata, checking the default token endpoint, the assertion audience, the `resource`, and the recorded
issuer. Both raise `NoMethodError` against the previous library.

## Breaking Changes

None.
2026-09-17 19:05:51 +09:00
Koichi ITO
47eb74aa7a Validate the issuer of legacy authorization server metadata
## Motivation and Context

On the legacy 2025-03-26 path, taken when a server publishes no Protected Resource Metadata,
the authorization server metadata is fetched from the MCP server's origin, which that spec names
as the authorization base URL, but its `issuer` was never compared with that origin.
RFC 8414 Section 3.3 requires the comparison, the 2025-03-26 spec makes RFC 8414 a MUST for clients,
and the TypeScript and Python SDKs both compare on this path, tolerating only a trailing slash.
The flow nevertheless used the unverified `issuer` as the authorization server's identity everywhere:
tokens were stamped with it, stored client information was matched against it, the `private_key_jwt`
and ID-JAG assertions took it as their audience, and `authorization_request_validator` was shown it.

A server on that path could therefore claim any issuer. Claiming the one that minted the stored tokens made
`refresh!` send the refresh token and the stored client secret to the server's own token endpoint, claiming
the one that issued stored client information made the flow reuse those credentials there, and a validator
allow-listing the claimed issuer approved the request.

The legacy path now applies the same check as the modern one: the document's `issuer` must be the origin,
rendered with or without a trailing slash, and any other document is refused before registration, redirect,
or token request. A server without a metadata document still gets the spec's default endpoints.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb` serve legacy metadata at the MCP server origin that claims
`https://auth.example.com` and check that the flow, a refresh of tokens issued by that server,
and a flow holding client information bound to it are all refused before any request, with the validator never asked
and the credentials never presented. Metadata naming the origin, with or without a trailing slash and with
endpoints under a path prefix, completes the flow, including the RFC 9207 `iss` check. The former test
of a path-prefix issuer now expects the refusal. The refusal tests fail against the previous library.

## Breaking Changes

A server without Protected Resource Metadata whose authorization server metadata names an issuer other than
its origin is refused instead of used. The TypeScript and Python SDKs already refuse such a server,
and the 2025-03-26 spec places the metadata at the origin.
2026-09-17 13:37:54 +09:00
Koichi ITO
8ad80dd0b4 Let a provider add parameters to the token requests it makes
## Motivation and Context

`ClientCredentialsProvider` builds a fixed `client_credentials` token request: `grant_type`, `scope`,
`resource`, and the client authentication that `Flow#post_to_token_endpoint` adds. An authorization server
that requires further parameters, such as Auth0's `audience`, cannot be used through `oauth:` at all,
and giving up `oauth:` also gives up the bearer header and the 401-driven retry that the transport provides.

RFC 6749 Section 8.2 allows extension parameters on the token request, and the TypeScript SDK lets
a provider shape its token request through `prepareTokenRequest`. `ClientCredentialsProvider.new` now takes
`token_request_params:`, a Hash of String keys and values added to every token request the provider makes,
and `Flow#post_to_token_endpoint` reads the same name by duck typing, so a `Provider` or `CrossAppAccessProvider`
subclass that defines the method gets the same treatment on its authorization code exchange, refresh,
or `jwt-bearer` request.
`Provider.new` and `CrossAppAccessProvider.new` take the same keyword, held by `StorageBackedProvider` like
`authorization_request_validator`, so every bundled provider refuses a bad value before anything is stored.

The parameters go underneath the flow's own, so the SDK's values always win, and a key the SDK sets itself
(`Flow::RESERVED_TOKEN_REQUEST_PARAMS`) is refused rather than silently overridden: with `ArgumentError`
from the constructor, before any `client_information` is written, and again with `ArgumentError` from the flow,
before the token request is sent. Only Strings are accepted because `URI.encode_www_form` encodes other scalars
and Arrays in ways the caller did not write, and the provider keeps a frozen copy so a later change to
the caller's Hash cannot alter what is sent.
A Hash comparing keys by identity is refused too, since two equal keys are two entries there, sent twice
by a provider method or silently collapsed into one by the copy. The flow raises `ArgumentError` rather than
`AuthorizationError` because `MCP::Client::HTTP` treats a failed refresh as a reason to run the interactive flow,
which would then fail the same way after the user signed in.
Both refusals raise `Flow::InvalidTokenRequestParamsError`, a subclass of `ArgumentError`, so a caller can tell them
from an unknown keyword, and the copy duplicates keys as well as values, since `Hash` copies only keys
whose class is exactly `String`.

Fixes #554.

## How Has This Been Tested?

New tests cover every token request the parameters can ride (the `client_credentials` grant under
all three client authentication methods, the authorization code exchange, refresh, and `jwt-bearer`),
both refusal boundaries (the constructors of all three providers, and the flow for a provider defining the method),
and the transport surfacing a refused hook from a refresh attempt without starting the interactive flow.
All of them fail against the previous library.

## Breaking Changes

None. The keyword is optional and the hook is opt-in; a provider that does not define `token_request_params` sends
the same requests as before.
2026-09-17 13:26:52 +09:00
Koichi ITO
41fbf05d26
Merge pull request #553 from koic/suppress_rubocop_offense
Fix a redundant regexp escape in the tool name validation
2026-09-16 00:44:04 +09:00
Koichi ITO
99ef8732fe Fix a redundant regexp escape in the tool name validation
## Motivation and Context

This PR suppresses the following offense of RuboCop.

```console
$ bundle exec rubocop
Inspecting 163 files
(snip)

Offenses:

lib/mcp/tool.rb:152:48: C: [Correctable] Style/RedundantRegexpEscape: Redundant escape inside regexp literal
        unless tool_name.match?(/\A[A-Za-z\d_\-\.]+\z/)
                                               ^^

163 files inspected, 1 offense detected, 1 offense autocorrectable
```

## How Has This Been Tested?

`bundle exec rake` passes: RuboCop reports no offenses.

## Breaking Changes

None.
2026-09-15 12:36:59 +09:00
Koichi ITO
7d7a5669ef
Merge pull request #549 from junyuanz1/fix/oauth-token-error-diagnostics
fix(client/oauth): preserve token endpoint error diagnostics
2026-09-15 00:38:02 +09:00
Junyuan Zheng
8d1d5be4ba fix(client/oauth): preserve token endpoint error diagnostics 2026-09-14 09:45:38 -04:00
Koichi ITO
a18c628787
Merge pull request #552 from koic/document_listen_delivery_semantics
[Doc] State the Listen Stream Delivery Semantics
2026-09-14 22:29:28 +09:00
Koichi ITO
ef3eb7b0b2 [Doc] State the Listen Stream Delivery Semantics
The Subscriptions page documented the acknowledgement-first contract but not what delivery means:
the stream carries only changes that happen after the acknowledgement, nothing is queued while
no stream is connected, and a dropped stream is gone together with anything it missed.
The Python SDK's subscriptions page states the same contract ("It is not a replay log").
Spelling it out gives client implementers the fetch-after-subscribing guidance and
makes the acknowledgement-window behavior explicit.
2026-09-13 17:10:12 +09:00
Koichi ITO
8e0ae73cc1
Merge pull request #551 from koic/fill_the_client_ping_docs_gaps
[Doc] Document the client's ping answers and the stdio request limit
2026-09-13 00:16:28 +09:00
Koichi ITO
7e507f2963 [Doc] Document the client's ping answers and the stdio request limit
## Motivation and Context

The client answers server pings automatically, but the docs leave out where that applies and what the stdio transport
does with the other server-to-client requests.

The client Transports page now lists the automatic ping answer among the things the stdio transport handles,
and a note states that `ping` is the only server-to-client request answered there: a wire-level `elicitation/create`
or `sampling/createMessage` is ignored over stdio, so a server that sends one waits for an answer that never comes,
while the SEP-2322 `input_required` route works on every transport and keeps `on_elicitation` and `on_sampling` handlers
working over stdio. Without this note, the only trace of the limitation is a hung tool call.

The client Ping page now says that over HTTP a ping reaches the client only on a stream that is already open
and that the client never opens one to receive pings, so a server can only ping a client that has a stream open.
Registering `on_server_request("ping")` moves to the end of the section as the advanced option it is, together with
its side effect of opening the GET listening stream on `connect`.

The client overview mentions the automatic answer next to `MCP::Client#ping`,
and the server Ping page's Client Side section points at it.

## How Has This Been Tested?

Documentation only; the linked headings and pages exist.

## Breaking Changes

None.
2026-09-12 00:02:36 +09:00
Koichi ITO
251a40f780
Merge pull request #550 from koic/drop_the_json_pin_from_the_gemfile
Drop the json pin for Ruby 2.7.0 through 2.7.2 from the Gemfile
2026-09-11 00:04:56 +09:00
Koichi ITO
2f65a6e502 Drop the json pin for Ruby 2.7.0 through 2.7.2 from the Gemfile
## Motivation and Context

json 3.0.2 loads on Ruby 2.7.0 through 2.7.2 again: it no longer forwards arguments after a leading parameter,
the syntax those patch levels could not parse, so the Gemfile no longer has to keep json below 3.0 there,
and the CI job pinned to 2.7.0, the minimum the gemspec supports, resolves json 3.0.2 like every other job.
The maintainers intend to raise json's own Ruby floor to 2.7.3 in the release after 3.0.2, so those patch levels
stay on 3.0.2 by json's gemspec from then on, and no pin of this Gemfile's own is needed for that either.

## How Has This Been Tested?

A fresh `bundle install` on Ruby 2.7.2 resolves json 3.0.2, `require "json"` loads it there,
and `bundle exec rake test` passes. Ruby 3.0 and later were never affected by the pin.

## Breaking Changes

None. The Gemfile is not part of the gem.
2026-09-10 11:55:31 +09:00
Koichi ITO
91ee5a2123
Merge pull request #548 from junyuanz1/fix/token-endpoint-single-auth-method
fix(client/oauth): omit body client_id when using HTTP Basic
2026-09-10 01:31:43 +09:00
Junyuan Zheng
4192ea58ea fix(client/oauth): omit body client_id when using HTTP Basic 2026-09-09 12:14:21 -04:00
Koichi ITO
c6a5512381
Merge pull request #547 from koic/release_1_5_1
Release 1.5.1
2026-09-09 14:43:47 +09:00
Koichi ITO
3b44ec4f48 Release 1.5.1
This release keeps the HTTP client working with json 3.0, which accepts the options of `JSON.parse`
as keywords only. Faraday's JSON response middleware, through 2.14.3, passes them as a positional Hash
that Ruby 3 no longer converts, so every JSON body the client received failed as an internal error.
The client now parses response bodies itself, the way it already handled streamed ones, and no longer
registers the middleware.

The one visible difference: a malformed JSON body delivered whole by an adapter without streaming support
now raises `RequestHandlerError` with `error_type: :parse_error`, as the streamed path already did,
instead of `:internal_error` wrapping a `Faraday::ParsingError`.
2026-09-09 10:43:15 +09:00
Koichi ITO
d0b22ef722
Merge pull request #546 from koic/parse_json_response_bodies_in_the_client
Parse HTTP client response bodies without Faraday's JSON middleware
2026-09-08 18:13:24 +09:00
Koichi ITO
d40d9018d5 Keep json below 3.0 on Ruby 2.7.0 through 2.7.2 in the Gemfile
## Motivation and Context

json 3.0 declares Ruby 2.7 as its floor, but its `load_file` forwards arguments after a leading parameter,
`def load_file(filespec, ...)`, syntax Ruby 2.7.3 was the first to parse. On Ruby 2.7.0 through 2.7.2, requiring
json 3.0.1 is a `SyntaxError`, so `require "mcp"` fails before any test runs, and the CI job pinned to 2.7.0,
the minimum the gemspec supports, fails the whole suite at load time.

The Gemfile keeps json below 3.0 on those three patch levels only. Later 2.7 releases and Ruby 3 parse the syntax
and stay on whatever json the resolver picks.
The line carries a FIXME to drop it once a json release includes ruby/json#1072, whichever version that turns out to be;
excluding only the two broken releases would silently trust a 3.0.2 that may not carry the fix.

## How Has This Been Tested?

`gem "json", "3.0.1"; require "json"` raises the `SyntaxError` on Ruby 2.7.0 and loads on 2.7.3 and 2.7.8.
With the pin, a fresh `bundle install` on Ruby 2.7.2 resolves json 2.x and `bundle exec rake test` passes.

## Breaking Changes

None. The Gemfile is not part of the gem.
2026-09-08 18:09:09 +09:00
Koichi ITO
09c89aef14 Parse HTTP client response bodies without Faraday's JSON middleware
## Motivation and Context

json 3.0, released on 2026-09-07, accepts the options of `JSON.parse` as keywords only, and Faraday's json response middleware,
through 2.14.3, hands them over as a positional Hash, which Ruby 3 no longer converts. With both installed, every JSON body
the client receives fails inside that middleware, and `MCP::Client::HTTP` reports each request as an internal error.
Faraday's main branch passes the options as keywords, but no release carries that yet.

The client already parses streamed bodies and buffered SSE bodies itself; only a JSON body delivered
whole by an adapter without streaming support still went through the middleware. The client now parses that body too
and no longer registers the middleware, so every body takes `parse_json_buffer` and a malformed one answers
`:parse_error` whichever way it arrived. A JSON middleware added through the Faraday customizer block still works,
since a body it has parsed already is used as is.

## How Has This Been Tested?

A new test drives a buffered JSON response through a stand-in `JSON.parse` with the json 3.0 signature, options as keywords only,
so on Ruby 3 it failed with the middleware registered whatever json version is installed and passes now.
The existing buffered-body test keeps covering the plain path. The full suite passes on Ruby 3.0.7 with json 3.0.1 and faraday 2.14.3,
where five client tests failed before.

## Breaking Changes

None. A malformed JSON body delivered by an adapter without streaming support now raises `RequestHandlerError` with `error_type: :parse_error`,
as the streamed path already did, instead of `:internal_error` wrapping a `Faraday::ParsingError`.
2026-09-08 18:09:09 +09:00
Koichi ITO
44af58c7e0
Merge pull request #544 from koic/add_event_stream_parser_to_installation_docs
[Doc] Explain when the HTTP client needs event_stream_parser
2026-09-07 08:57:35 +09:00
Koichi ITO
0da0291887 [Doc] Explain when the HTTP client needs event_stream_parser
## Motivation and Context

The Installation page names faraday as the example of an optional dependency but leaves out event_stream_parser,
which the HTTP client transport needs as soon as a server answers with SSE. The Transports page documents both gems,
so a reader who starts from Installation learns about the second one only when a streaming response fails to parse.

The Transports page also marks event_stream_parser as "optional, required only for SSE responses",
which reads as a corner case. Whether a response is JSON or SSE is the server's choice, made for each response,
a client must accept both, and this SDK's own server picks SSE by default and always on the modern lifecycle,
so a client written for arbitrary servers needs both gems. Both pages now say so, and the Transports page spells out
the one setup that can leave the gem out: a server known to answer with JSON alone, such as this SDK's server
in JSON response mode serving handshake-lifecycle clients, and no listening stream.

The Installation page shows the faraday-only Gemfile first and then the one that adds event_stream_parser,
so both cases are visible at a glance.

## How Has This Been Tested?

Documentation only; the Gemfile snippets on both pages match.

## Breaking Changes

None.
2026-09-06 03:22:32 +09:00
Koichi ITO
8a24e50d1b
Merge pull request #543 from koic/release_1_5_0
Release 1.5.0
2026-09-05 11:58:59 +09:00
Koichi ITO
33525d6494 Release 1.5.0
This release makes the client answer a server's `ping` with the empty result the specification requires:
earlier clients replied with Method not found over Streamable HTTP and stayed silent over stdio,
so a server that checks liveness dropped their long-lived sessions. On the OAuth side,
the embedding application can refuse an authorization request through `authorization_request_validator`,
and stored tokens are refreshed only against the authorization server that issued them.

The validator is what makes this a minor release. The refresh check is the one behavior change:
when the authorization server named for a session differs from the one that issued the stored tokens,
the client reauthorizes instead of refreshing, and tokens stored by earlier releases, which carry no issuer,
keep refreshing.
2026-09-05 02:36:44 +09:00
Koichi ITO
f706cc8a5e
Merge pull request #542 from koic/fix_flaky_listen_keepalive_thread_assertion
Fix the flaky thread count assertion in the listen keepalive test
2026-09-05 02:23:29 +09:00
Koichi ITO
6d272df0e2
Merge pull request #541 from koic/respond_to_server_pings_in_the_client
Answer server-to-client pings in the client
2026-09-05 02:23:10 +09:00
Koichi ITO
eeab784fc8
Merge pull request #539 from koic/add_authorization_request_validator
Let the embedding application refuse an authorization request
2026-09-05 02:22:47 +09:00
Koichi ITO
09c310341b Fix the flaky thread count assertion in the listen keepalive test
## Motivation and Context

"listen keepalive is not started when the interval is nil" fails intermittently on CI. The most recent run failed
on Ruby 3.2 alone while 3.1 and head passed, and a re-run of the same commit went green.

The assertion samples a process-wide count:

```ruby
before = Thread.list.size
open_listen_stream(id: "listen-1", notifications: { toolsListChanged: true })
assert_equal before, Thread.list.size, "a nil interval must not spawn a keepalive thread"
```

`Thread.list` covers the whole process, so the count moves for reasons this test has no interest in.
The observed failure reported 54 against 51: three threads had *gone away* between the samples, not appeared.
This file starts threads in sixteen places, and the SSE stream and reaper threads they leave behind finish whenever
they finish, so whether the count holds still depends on the test order and on the scheduler rather than on
the behavior under test.

The test itself is asking the right question. `setup` builds its transport with `listen_keepalive_interval: nil`
precisely so opening a listen stream spawns no timer, and the point is to hold that guarantee. Only the measurement is wrong,
so this compares the set of threads instead: a thread that disappears no longer registers, and a thread that appears still does.
Minitest runs these tests serially and `open_listen_stream` drives the SSE body inline rather than on a thread,
so a keepalive timer is the only thread that can appear across the two samples.

No library code changes.

## How Has This Been Tested?

The rewritten assertion was checked for sensitivity before being kept: a temporary probe pointed `open_listen_stream` at
a transport built with `listen_keepalive_interval: 15` and asserted the set difference was *not* empty. It passed,
confirming the assertion still catches a spawned keepalive thread rather than merely never failing. The probe was
removed afterwards.

The failure did not reproduce locally beforehand, across six seeds of the file on its own and six full-suite runs,
which matches a timing-sensitive flake that needs a slower machine.

## Breaking Changes

None.
2026-09-04 00:19:38 +09:00
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
Koichi ITO
6b1704f330
Merge pull request #540 from koic/mark_deprecated_features_on_the_server_overview
[Doc] Mark the deprecated features on the server overview
2026-09-02 01:16:15 +09:00
Koichi ITO
6f0b85486b [Doc] Mark the deprecated features on the server overview
The overview's Key Features and Supported Methods listed `roots`, `sampling`, and `logging/setLevel` with no deprecation marking,
while their own pages carry the SEP-2577 warnings, presenting a current-looking feature surface to a reader skimming the overview.
The five entries now carry the pages' "deprecated as of 2026-07-28" wording; `elicitation/create` stays unmarked - it is not deprecated,
and the modern lifecycle keeps carrying it as requests embedded per the multi round-trip requests pattern.
2026-09-01 01:14:59 +09:00
Koichi ITO
09d4bf41aa Let the embedding application refuse an authorization request
## Motivation and Context

An MCP server chooses the authorization server its users sign in to. It names one in `authorization_servers`
in its Protected Resource Metadata, and states the scopes it wants in `scopes_supported`
or in the `WWW-Authenticate` challenge. Nothing binds either choice to the server's own identity.

No origin rule can settle this, because an authorization server is legitimately a different origin
from the resource it protects. Validating that a token was issued for the intended audience is a responsibility
the specification places on MCP servers rather than on clients, and there is no portable way for a client
to perform it either: access tokens are frequently opaque, and an authorization server is not required to honor
the `resource` parameter or to report an audience in the token response.

Two things follow from that, and they are separate.

The first is a judgement, and it belongs to whoever embeds this SDK, because an application often knows
which providers its users deal with. `authorization_request_validator` is handed an `AuthorizationRequest` describing
the authorization server, the scopes, the MCP server, and the RFC 8707 resource, and can refuse.
It is one object rather than keyword arguments so that later revisions of the specification can add to it
without changing the shape implementers wrote. It runs on all three grants, and on the authorization-code grant it
runs before dynamic client registration, which is why scope resolution moved above `ensure_client_registered`:
a refusal must not leave this client registered at an authorization server the host just rejected.

The second is not a judgement and is enforced here rather than asked about. `refresh!` rediscovers
the authorization server on every call, so the server named for a session can differ from the one
the stored tokens came from. SEP-2352 already binds client credentials to their issuer,
but that check passes when the issuer was never recorded and is deliberately skipped for a Client ID Metadata Document URL,
which is portable across authorization servers. The issuer that minted the tokens is now recorded with them,
and `refresh!` refuses to present them to a different one. The transport answers that refusal by running
a full authorization, which brings the new authorization server to the validator above. Tokens stored before
this carry no issuer and keep refreshing.

The hook decides whether to proceed, not what to ask for. The scopes reach the authorization server unchanged either way,
because the specification requires a client to treat the scopes in the challenge as authoritative for the operation,
and narrowing them silently would break that.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb` assert what the validator receives, that a refusal raises
before any registration request is sent and before the redirect handler runs, and that the `client_credentials`
and `jwt-bearer` grants consult it too. Others cover the issuer recorded on authorization, the refusal to refresh against
a different one, and that tokens stored without an issuer still refresh. A test in `test/mcp/client/oauth/http_oauth_test.rb`
drives the two halves together: a stale issuer makes the refresh fail, the transport reauthorizes, and the validator sees
the newly named authorization server while no refresh token is ever posted to it. Each of them fails with its half of
this change removed. `bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

Refreshing now fails when the authorization server named for a session differs from the one that issued the stored tokens,
and the caller reauthorizes instead. Tokens stored before this change carry no recorded issuer and are unaffected
until their next authorization. The validator itself is additive: it defaults to `nil`, and a provider that does not offer
it authorizes as before.
2026-08-31 02:33:10 +09:00
Koichi ITO
0cd1514bde
Merge pull request #538 from koic/namespace_the_conformance_rake_tasks
Group the conformance Rake tasks under a `conformance` namespace
2026-08-31 01:29:29 +09:00
Koichi ITO
920707cd7e Group the conformance Rake tasks under a conformance namespace
## Motivation and Context

The three conformance tasks were named `conformance`, `conformance_list`, and `conformance_server`,
spelling out with underscores the grouping that Rake expresses with namespaces.

They are now `conformance:test`, `conformance:list`, and `conformance:server`.
The bare `conformance` task is kept as an alias for `conformance:test`.

## How Has This Been Tested?

By running `rake -T` to confirm the three tasks are grouped under `conformance:`
with the alias listed beside them, `rake --dry-run default` to confirm that the default task
resolves `conformance:test`, and `rake conformance:list` to exercise a renamed task end to end.

## Breaking Changes

None. These are development-only Rake tasks.
2026-08-30 02:24:52 +09:00
Koichi ITO
11f9aacaa9
Merge pull request #537 from koic/update_examples_for_2026_07_28
Update examples for the 2026-07-28 era
2026-08-29 18:55:38 +09:00
Koichi ITO
bfc6e551a3 Update examples for the 2026-07-28 era
## Motivation and Context

The runnable examples drifted from the SDK they ship with:

- POST requests whose `Accept` header does not cover both `application/json` and `text/event-stream` are answered 406,
  so the cURL walkthroughs  no longer worked as printed.
- `MCP::Client#connect` now defaults to `mode: :auto`, which adopts the sessionless modern lifecycle (2026-07-28)
  against a dual-era server; the Streamable HTTP client example requires a session and broke against its own server.
- POST responses on an established session arrive as an SSE stream, which the hand-rolled HTTP client did not parse.
- `notification_tool` claimed to send SSE notifications but only returned a `Tool::Response`.
- `http_client.rb` read a resource URI the server never registered and skipped `notifications/initialized`.

Handshake examples now offer the latest handshake protocol version (`2025-11-25`) instead of `2024-11-05`,
the Streamable HTTP client pins `mode: :legacy` for its session-based demo, `notification_tool` reports
real `notifications/progress` events requested through `_meta.progressToken`, and the interactive client streams
those events from the POST response so they are visible on screen.

The modern lifecycle itself had no runnable example, so a new server and client pair (`modern_http_server.rb`,
`modern_http_client.rb`) shows the sessionless flow end to end: `server/discover` capability discovery,
the per-request `_meta` envelope with the `Mcp-Method` and `Mcp-Name` headers (stamped by the SDK client automatically),
`resultType` stamping, SEP-2549 cache hints, a SEP-2322 multi round-trip `deploy` tool resumed automatically by
the client's elicitation handler, and the removal of legacy-only methods such as `ping`. The same server keeps serving
the legacy `initialize` flow, routed per request by the `MCP-Protocol-Version` header. `examples/README.md` documents
the pair and adds a cURL walkthrough covering the modern headers, the envelope, and the multi round-trip exchange.

## How Has This Been Tested?

- `ruby examples/stdio_client.rb` against `stdio_server.rb`
- `ruby examples/http_client.rb` against `http_server.rb`
- `ruby examples/streamable_http_client.rb` against `streamable_http_server.rb`, including the progress stream
- `ruby examples/modern_http_client.rb` against `modern_http_server.rb` (discover, modern adoption, cache hints,
  `resultType`, the multi round-trip resume, `ping` rejection)
- The cURL walkthroughs in the banners and `examples/README.md`, including the `requestState` echo and a legacy `initialize`
  against the modern example server

## Breaking Changes

None.
2026-08-28 12:03:52 +09:00
Koichi ITO
da4ce54075
Merge pull request #536 from koic/release_1_4_0 2026-08-28 10:14:09 +09:00
Koichi ITO
50accf644d Release 1.4.0
This release repairs the `subscriptions/listen` stream: a host that buffers its responses,
the documented Rails controller pattern among them, can decline the method with
`serve_subscriptions_listen: false` instead of answering a modern client with a streaming body
it cannot render, and the stream's ordering guarantees are enforced - no notification before
the acknowledgement, none after the graceful closing result.

The new keyword argument is what makes this a minor release; everything else is a bug fix.
The controller-pattern crash is a regression from 1.2.0, where the modern lifecycle began
answering `subscriptions/listen` that earlier versions had refused as an unknown method,
and it fails quietly: only the notification stream breaks, so tool calls keep working.
2026-08-28 03:54:46 +09:00
Koichi ITO
6b6b641655
Merge pull request #535 from koic/serialize_listen_stream_writes_on_teardown
Serialize `subscriptions/listen` writes so the graceful result is the final message
2026-08-27 01:12:33 +09:00
Koichi ITO
7909600d16
Merge pull request #534 from koic/add_a_docs_preview_rake_task
Add a `rake docs:preview` task serving the docs site locally
2026-08-27 01:11:26 +09:00
Koichi ITO
2200cbd2bb Serialize subscriptions/listen writes so the graceful result is the final message
## Motivation and Context

On graceful teardown (`transport.close`), each open `subscriptions/listen` stream receives
its `SubscriptionsListenResult` response before closing, signaling a clean end the client can distinguish
from an abrupt disconnect. But a delivery that snapshotted the stream from the registry
before teardown cleared it performs its write outside the lock, so a change notification could land after the final result.

Each subscription entry now carries a per-stream write mutex. Teardown marks the entry closed and writes
the result under that mutex; a racing delivery either lands before the result or observes `closed` and skips,
keeping the graceful result the stream's final message. The mutex is per stream and held only around the single write call,
so deliveries to different streams stay as parallel as before, and no path nests it inside the transport mutex
(delivery snapshots release `@mutex` first, and the write-error cleanup takes `@mutex` only after the write mutex is released),
ruling out lock-order inversions. Keepalive pings stay outside the mutex: they are SSE comment frames, which clients ignore by
specification, so one landing after the result is harmless.

## How Has This Been Tested?

With a new regression test pinning the race (an entry captured before teardown and re-presented to delivery afterwards writes
nothing after the result), the full suite, RuboCop, and the conformance suite, all green.

## Breaking Changes

None. The write mutex is internal to the listen registry; the wire only gains the ordering guarantee.
2026-08-26 04:44:02 +09:00
Koichi ITO
411f6b9f0f
Merge pull request #532 from koic/activate_listen_streams_after_the_acknowledgement
Deliver `subscriptions/listen` notifications only after the acknowledgement
2026-08-26 04:39:24 +09:00
Koichi ITO
636e494068 Add a rake docs:preview task serving the docs site locally
## Motivation and Context

The documentation site under `docs/` had no development command: previewing a change meant hand-assembling
a Jekyll environment, since the site only builds for real when a release publishes it through
`bin/generate-gh-pages.sh` and the GitHub Pages runtime. `rake docs:preview` now builds and serves
the site at http://localhost:4000 (override with `PORT`), with watch-based rebuilds on edit.

The preview dependencies live in their own `docs/Gemfile` rather than the gem's Gemfile:
`github-pages` mirrors the runtime that builds the released site (jekyll-remote-theme,
jekyll-redirect-from, and the Jekyll version Pages actually runs), which keeps the preview faithful
but is far too heavy to impose on the gem itself. The task subshells into that bundle with
`Bundler.with_unbundled_env`, the same delegation shape the conformance tasks use for npx.
Two support pieces keep the pinned toolchain running on current Ruby. `docs/_preview/taint_shim.rb` restores
the taint API as no-ops: Liquid 4.0.3 calls `obj.tainted?` on every variable render,
ahead of its own lax-mode check (`liquid/variable.rb:124`), so on Ruby 3.2 and later,
where the taint API was removed, the first layout render dies with NoMethodError, while on Ruby 3.1
and earlier the methods still exist as deprecated no-ops and the shim is inert. The shim is loaded only into
the preview process via RUBYOPT. The former default gems the pinned Jekyll expects are listed in the docs Gemfile.
The task also regenerates `docs/_data/versions.yml` from the version tags, mirroring what `bin/generate-gh-pages.sh`
produces at deploy time, so the nav footer shows the released-gem version line exactly as it does on the published site.
Build products and the generated data file are ignored.

## How Has This Been Tested?

By running the task on a spare port and verifying the served pages, the footer's version line,
and that a SIGINT stops it cleanly with exit 0; `git status` stays clean while it runs (all build products ignored).
Verified on both Ruby 3.1.5 (shim inert) and Ruby 4.0.6, where a shimless build reproduces the NoMethodError
and the task runs green with the shim. RuboCop and the full suite are green.

## Breaking Changes

None. The task and its Gemfile are development-only additions; the gem and its dependencies are untouched.
2026-08-25 12:36:54 +09:00
Koichi ITO
3b79c8e58a
Merge pull request #533 from koic/make_subscriptions_listen_refusable
Make `subscriptions/listen` refusable for hosts that cannot stream
2026-08-25 12:26:25 +09:00
Koichi ITO
3da0c10bed Make subscriptions/listen refusable for hosts that cannot stream
## Motivation and Context

The documented Rails controller pattern builds a fresh transport per request and renders `body.first`,
but a modern client's `subscriptions/listen` made `handle_request` return the streaming `Proc` body,
so exactly the documented configuration answered every notification-stream request with a 500 - quietly,
since tool calls and listings kept working. Nothing gated the route: `serves_subscriptions_listen?` was
hardcoded `true` and consulted only by `Server#discover` for capability stripping,
and the modern path deliberately ignores `stateless:`.

`StreamableHTTPTransport.new` now accepts `serve_subscriptions_listen:` (default `true`, behavior unchanged).
When `false`, the transport skips the listen interception so the method falls through the dispatcher as
unimplemented - the spec's 404 with JSON-RPC `-32601`, in an Array body the controller pattern can render - and
`serves_subscriptions_listen?` reflects the setting, so `Server#discover` stops advertising the `listChanged`/`subscribe`
capability flags through its existing wiring and the advertisement agrees with the actual behavior.
The documented controller example passes the flag and explains why; refusing implicitly in `stateless:` mode
was rejected because a stateless transport mounted as a long-lived Rack app serves listen streams correctly
(listen delivery deliberately precedes the stateless notification guard).

On the default streaming side, the listen body is now a small streaming-body object rather than a bare `Proc`:
it still responds to `call` and deliberately not to `each` (Rack would otherwise classify it as enumerable
and break the streaming), while `first` raises an error naming `serve_subscriptions_listen: false`
and pointing at the transports documentation, so a host that buffers the body the documented way fails with
guidance instead of a bare `NoMethodError`.

Fixes #531.

## How Has This Been Tested?

With the issue's reproduction script (default: a streaming body whose `body.first` raises the guidance;
with the flag: 404, `application/json`, and an Array body whose first element is the `-32601` error),
new transport tests covering the refusal shape, the capability stripping on `server/discover`, and the guidance
raise with the body's streaming classification, the full suite, RuboCop, and the conformance suite, all green;
the docs build passes every internal link and anchor check.

## Breaking Changes

None. The keyword defaults to the current behavior; refusal is opt-in.
2026-08-25 02:53:08 +09:00
Koichi ITO
5ce308b082 Deliver subscriptions/listen notifications only after the acknowledgement
## Motivation and Context

Per SEP-2575, the server MUST NOT send any notification on a subscription before `notifications/subscriptions/acknowledged`.
The listen stream was registered in the delivery registry before its acknowledgement was written (the write happens outside
the lock so a stalled reader cannot block the transport), so a change notification published concurrently from another thread
could be written to the stream ahead of the acknowledgement.

The entry is now inserted inactive - still reserving the id and the cap slot atomically - and becomes eligible for delivery only
after the acknowledgement write has completed. A concurrent notification inside the window skips the inactive entry,
which is indistinguishable from the change happening just before the subscription opened.

## How Has This Been Tested?

With a new regression test pinning the window (an entry injected in the registered-but-unacknowledged state receives nothing until activation),
the full suite, RuboCop, and the conformance suite, all green.

## Breaking Changes

None. Activation happens synchronously inside the same response body proc, so an acknowledged stream behaves exactly as before.
2026-08-25 00:29:52 +09:00
Koichi ITO
9cd1041e7c
Merge pull request #528 from koic/replace_the_nav_footer_theme_attribution
[Doc] Replace the theme attribution in the nav footer
2026-08-24 17:38:37 +09:00
Koichi ITO
8866317e62 [Doc] Replace the theme attribution in the nav footer
The bottom of the sidebar (and the mobile page footer) showed the theme's fallback line
"This site uses Just the Docs, a documentation theme for Jekyll", which tells readers nothing about the SDK.
Overriding nav_footer_custom.html replaces it with the release the documentation describes, linking the RubyGems
page of the version deployed via _data/versions.yml by bin/generate-gh-pages.sh, and with the licensing:
the documentation is CC-BY-4.0 per LICENSE, while the code licensing is delegated to LICENSE itself,
whose consent-based MIT to Apache-2.0 transition does not fit a footer phrase.
Without versions data (local previews of the docs/ source) only the license sentences render.
2026-08-24 16:45:55 +09:00
Koichi ITO
2a31e0bd80
Merge pull request #526 from koic/align_roadmap_deprecation_wording
[Doc] Align the ROADMAP deprecation wording with the shipped behavior
2026-08-24 00:46:53 +09:00
Koichi ITO
500d247e68
Merge pull request #525 from koic/align_docs_page_names_with_the_spec
[Doc] Align the Docs Page Names With the MCP Specification
2026-08-24 00:46:24 +09:00
Koichi ITO
c934b04f48 [Doc] Align the ROADMAP deprecation wording with the shipped behavior
## Motivation and Context

The Deprecated Features paragraph still described the pre-#516 design, claiming the SDK
"emits deprecation warnings when they are used with protocol version 2026-07-28 or newer".
Since #516 the only deprecation warning is the client-side one, emitted on a modern connect
that declares the Roots or Sampling capabilities, exactly as the 1.2.0 CHANGELOG entry states.
Logging never warns (`notify_log_message` is the sanctioned SEP-2575 delivery path on that wire),
and the server never warns either: `initialize` counter-offers a legacy version,
a modern `Configuration` pin is rejected at construction, and the modern lifecycle refuses
the deprecated server-to-client request APIs outright rather than serving them with a warning.
The paragraph now describes the shipped behavior and says where each feature lives per lifecycle:
unchanged on legacy, carried on 2026-07-28 by input requests embedded in `InputRequiredResult` responses
(the SEP-2322 multi round-trip requests pattern) and the envelope's `logLevel`. Those carriers are not
the SEP-2577 replacements: the spec's deprecated-features registry points migrating implementations
outside the protocol (tool parameters or configuration, direct LLM provider APIs, stderr or OpenTelemetry),
and the paragraph now says so instead of presenting the modern delivery forms as the replacements.

## How Has This Been Tested?

Documentation-only change; proofread against the `ProtocolDeprecations` module header and
the CHANGELOG entry that shipped this behavior in 1.2.0, which the 1.3.0 release leaves unchanged.
2026-08-23 01:15:20 +09:00
Koichi ITO
c9d36b04bf [Doc] Align the Docs Page Names With the MCP Specification
Three pages carried names the 2026-07-28 specification does not use: "Multi-Round-Trip Results" for
the pattern the specification titles Multi Round-Trip Requests (MRTR) and serves at basic/patterns/mrtr -
the results are the `InputRequiredResult` wire type, not the feature - plus "Completions" for the utility
the specification titles Completion, and "Notification Subscriptions" for the pattern it titles Subscriptions.
Retitle the three pages to the specification's names, move them to /server/mrtr/ and /client/mrtr/,
/server/completion/, and /server/subscriptions/ following the specification's slugs, update every internal reference,
and keep the URLs published with v1.3.0 working via jekyll-redirect-from.
The Discovery page keeps its title but moves from /server/discovery/ to /server/discover/, matching
the specification's slug and the `server/discover` RPC, with its published URL redirected the same way.
2026-08-22 18:07:38 +09:00
Koichi ITO
fcb1ac935d
Merge pull request #524 from koic/release_1_3_0
Release 1.3.0
2026-08-22 04:48:27 +09:00
Koichi ITO
79d89e0ac6
Merge pull request #523 from koic/restructure_readme_into_docs_site
Move the Documentation From README.md to the Documentation Site
2026-08-22 04:46:21 +09:00
Koichi ITO
833e21a959 Release 1.3.0
This release adds a `resources_list_handler` so `resources/list` can be served per-connection,
passes handler-returned `_meta` through subscription results, and moves the user-facing documentation
from README.md to the documentation site at https://ruby.sdk.modelcontextprotocol.io.

Two entries under "Changed" are incompatible with 1.2.0 and ship in a minor release under
the exceptions in VERSIONING.md: OAuth endpoint responses larger than 4 MiB are refused,
and a request whose id is already in flight on the same session is answered with Invalid Request.

IMPORTANT: The documentation moves with #523, and the site deploys only through the release workflow,
so #523 needs to be merged immediately before this release.
2026-08-22 01:20:22 +09:00
Koichi ITO
88831b46f6 Move the Documentation From README.md to the Documentation Site
Move the documentation that had grown to 3000+ lines in README.md onto https://ruby.sdk.modelcontextprotocol.io
and slim the README down to a quick start and feature overview, following the Python SDK layout:

- Add 21 server pages as the docs/_server/ collection (overview plus transports, discovery, tools, prompts, resources,
  roots, sampling, elicitation, multi round-trip results, notifications, notification subscriptions, cancellation, progress,
  ping, completions, logging, pagination, server context, configuration, and custom methods), 8 client pages as
  the docs/_client/ collection (overview, transports, lifecycle, multi round-trip results, cancellation, ping, pagination,
  and authorization), and 3 extension pages as the docs/_extensions/ collection (overview, capability extensions, and MCP Apps,
  following the Extensions Overview recommendation that SDK documentation list the supported extensions) -
  one page per topic, ordered to match the sidebar of the 2026-07-28 specification, with the client-side APIs
  (pinging, cancelling, and paginating from MCP::Client) documented under Building Clients
- Add top-level Examples and Protocol Versions pages after Installation, linking the runnable examples in examples/
  and summarizing the supported protocol versions, the era model, and client negotiation
- Render the three sections as just-the-docs collections, which list every page beneath a plain category heading in
  the sidebar with no folding, and serve every page at an extensionless URL under /server/, /client/, and /extensions/,
  matching the sibling SDK documentation sites
- Replace docs/building-servers.md and docs/building-clients.md with redirects to the new section overview pages via
  jekyll-redirect-from, redirect the previously published /installation.html to its extensionless URL, fold their content
  that was missing from README.md into the new pages, and update the Tool argument keys reference comment in lib/mcp/server.rb to
  the relocated Tools page
- Reduce README.md to the badges, a compact feature overview in the Python SDK style, installation instructions, a stdio
  server and client quick start, and a License section, using absolute URLs for the remaining repository links
  so they resolve on rubygems.org
- Adapt formatting where GitHub rendering habits break on the site: convert the numbered "three ways to define" lists into headings,
  since kramdown restarts numbering at 1 when code blocks split list items, convert GitHub-style alerts into just-the-docs callouts
  with the SEP-2260 server-to-client association note raised to a red warning, merge the duplicated Exception Reporting
  and Configuration Block Data sections into the Configuration page, and relocate the Streamable HTTP settings that were nested under
  the Logging section into the Transports page
- Refresh the migrated content against the current implementation: correct stale claims and broken samples the README carried,
  note on each session-era feature how it relates to the modern lifecycle of MCP 2026-07-28, and point spec links at the latest revision,
  keeping deliberate 2025-11-25 pins for pages the modern revision removed
- Style the site after the Rails API documentation palette (red links and accents on neutral surfaces) with matching
  light and dark color schemes, center the sidebar and content as one block, add a Previous/Next footer pager following
  the sidebar order, open external links in a new tab, and serve the MCP logo as the favicon

Every code block and heading from the previous README was verified to have a home in the new docs pages or the slimmed README before
the reduction; a few samples were corrected rather than copied, as noted above.
2026-08-21 13:24:04 +09:00
Koichi ITO
5124cb452d
Merge pull request #522 from koic/update_mrtr_resumption_doc
[Doc] Describe the client's automatic MRTR resumption
2026-08-21 00:11:26 +09:00
Koichi ITO
0ff1406efe
Merge pull request #510 from koic/pass_meta_through_subscription_results
Pass a handler-returned `_meta` through the subscribe result
2026-08-20 16:06:22 +09:00
Koichi ITO
77f571bc5d [Doc] Describe the client's automatic MRTR resumption
The Multi-Round-Trip Results section still said "automatic resumption is not implemented yet",
but the client driver shipped in #500: with a handler registered through `on_elicitation`,
`on_sampling`, or `on_roots`, the `call_tool`, `get_prompt`, and `read_resource` methods fulfill
embedded `inputRequests` and re-issue the original request automatically,
raising `MCP::Client::InputRequiredError` only when no matching handler exists.
Rewrite the paragraph to describe the implemented behavior, including the `input_required_max_rounds` cap
and the keywords for manual driving.
2026-08-20 14:59:40 +09:00
Koichi ITO
34473282b7
Merge pull request #509 from koic/add_resources_list_handler
Add a `resources_list_handler` for context-dependent resource lists
2026-08-20 01:15:27 +09:00
Koichi ITO
4eb66155e2
Merge pull request #521 from koic/reject_duplicate_in_flight_request_ids
Reject duplicate in-flight JSON-RPC request IDs
2026-08-19 01:03:06 +09:00
Koichi ITO
87ad91d170
Merge pull request #520 from koic/bound_oauth_response_bodies
Bound OAuth response bodies in the client
2026-08-18 03:23:11 +09:00
Koichi ITO
a53e8d9ed4 Reject duplicate in-flight JSON-RPC request IDs
## Motivation and Context

A request id is the only key that routes request-scoped messages back to the request that caused them:
progress and log notifications, server-to-client requests such as sampling and elicitation,
and `notifications/cancelled` all resolve through it. Nothing checked that the id was free,
so a second request arriving under an id already in flight took the routing entry over.
From that point the first request's notifications were written to the second request's SSE stream,
and whichever finished first removed the shared entry, leaving the survivor's messages nowhere to go.

The spec puts the uniqueness obligation on the sender, and 2026-07-28 draws it at exactly
the window this change enforces: "The request ID MUST NOT match the ID of any other request the sender
has issued and not yet received a response for". Earlier revisions worded it as never reusing an id within
the session. Neither says what a receiver does with a duplicate, but the Streamable HTTP rules require
that messages the server sends before the response "SHOULD relate to the originating client request",
and two live requests sharing one id make that impossible to honor for either of them.
Answering the second one is the only option that stays correct, so it is refused the same way
a duplicate `initialize` is, and for the same reason: a repeated id must not silently displace state
the first one established.

The reference SDKs currently accept the duplicate and let the newer request take the entry.
That is not a settled design: the Python SDK carries a TODO naming rejection with `INVALID_REQUEST`
as the revisit, so this moves toward where they expect to end up rather than away from them.

`ServerSession#register_in_flight` now claims the id atomically and reports a collision instead of overwriting,
which `Server` turns into an Invalid Request for every transport. `StreamableHTTPTransport` refuses
the colliding POST with 409 before it registers a stream, since the stream is registered ahead of dispatch
and would otherwise take over the routing entry for as long as the rejection takes.

Removal is now guarded by identity everywhere the registry is keyed by request id, so a request that loses
a race cannot retire a registration it does not own. `initialize` never registers, so its `ensure` no longer unregisters:
a refused duplicate `initialize` reusing an in-flight id used to evict that registration on the way out,
silently disabling cancellation for the request that owned it (Streamable HTTP refuses such a POST before dispatch;
stdio reached this path). `drop_broken_stream` had a sharper form of the same bug: it removed whichever stream held
the id while closing the one passed in, which are not necessarily the same stream.

Only ids that are in flight are refused, which is the scope the current spec draws.
Enforcing the older "never within the session" wording would instead mean remembering every id a session ever used,
and the in-flight window is the part routing depends on either way. Sequential reuse keeps working,
and neither this SDK's client (`SecureRandom.uuid`) nor a client built on the TypeScript SDK (a per-connection counter)
can produce a collision.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` reproduce the collision:
a tool parked mid-request, a second POST reusing its id, and assertions that the second POST is refused
and that the first request still receives the progress frame it emits afterwards. Others cover
the identity-guarded removal and confirm that an id can be reused once the earlier request has finished.
New tests in `test/mcp/server_cancellation_test.rb` cover the registry directly, including
the transport-independent Invalid Request and the survival of an in-flight registration across
a refused duplicate `initialize` under the same id. All of them except the sequential-reuse guard fail
without this change. `bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

A request whose id is already in flight on the same session is now answered with Invalid Request
(HTTP 409 on Streamable HTTP) instead of being processed. A client that reuses ids concurrently was
already violating the specification and was already having its notifications misrouted.
2026-08-17 03:47:35 +09:00
Koichi ITO
02db089038 Bound OAuth response bodies in the client
## Motivation and Context

`MCP::Client::HTTP` caps a single message from the server at 4 MiB, but the OAuth flow talks to
authorization endpoints over its own Faraday connection, and that one had no cap. Discovery,
dynamic client registration, and token responses were buffered in full and handed to `JSON.parse`,
so a server that answered an OAuth request with an endless body grew the client's memory for as
long as it kept sending.

`Flow` and `IDJAGTokenExchange` each build their own connection, so both needed the bound.
The new `BoundedBody` counts bytes in a Faraday `on_data` callback and refuses the response once
it passes `MAX_RESPONSE_BYTES`, which matches the 4 MiB of `MCP::Client::HTTP::MAX_MESSAGE_BYTES`
and `MCP::Client::Stdio::MAX_LINE_BYTES`. It hands back the status paired with the bounded body
rather than the Faraday response, so no later caller can reach the unbounded `response.body`.

Those bytes are counted after decompression. The default Net::HTTP adapter negotiates `Accept-Encoding`
itself  and reads the body through `Net::HTTPResponse#inflater`, so a small compressed body that expands past
the cap is refused partway through the expansion. That holds only while the connection leaves
`Accept-Encoding` alone, which is now recorded in a comment on both `default_http_client` definitions.

An over-cap response is refused rather than truncated: a partial discovery or token document cannot be validated.
Protected resource metadata is the one place where refusing is not fatal, since any PRM discovery failure
already selects the legacy authorization path by design.

## How Has This Been Tested?

New unit tests in `test/mcp/client/oauth/bounded_body_test.rb` cover the streaming path,
the at-limit boundary, and the fallback for adapters that ignore `on_data`. One of them serves
a gzip body over a real socket rather than through WebMock, which returns a stubbed body verbatim
and never runs the inflater; it fails if the cap ever starts measuring compressed bytes. New tests in
`test/mcp/client/oauth/flow_test.rb` and `test/mcp/client/oauth/id_jag_token_exchange_test.rb` drive each of
the four request wrappers end to end with an over-cap body; all five fail without the cap in place.

## Breaking Changes

An OAuth endpoint response larger than 4 MiB is now rejected instead of parsed.
2026-08-16 03:29:15 +09:00
Koichi ITO
ad73154697
Merge pull request #519 from koic/update_roadmap_for_2026_07_28
Refresh ROADMAP.md for the shipped 2026-07-28 support
2026-08-15 12:16:22 +09:00
Koichi ITO
8a886639fd Refresh ROADMAP.md for the shipped 2026-07-28 support
## Motivation and Context

The roadmap predates the 2026-07-28 implementation work and has drifted from the released SDK.
The 2026-08-15 SEP-1730 tier audit flagged the drift while evaluating the roadmap requirement:

- "Current Status" claims only 2025-06-18 and 2025-11-25 support, but the SDK now completes
  the 2026-07-28 revision and passes all scored server and client conformance scenarios for each
  revision's requirement set.
- The SEP-2575 stateless lifecycle rewrite was described as reserved for 2.0,
  but it shipped during 1.x with both lifecycle eras served side by side;
  the few incompatible adjustments shipped in a minor release under the spec-conformance
  and security exceptions described in VERSIONING.md, as recorded in the 1.2.0 CHANGELOG entry.
- Deprecation warnings for Roots/Sampling/Logging (SEP-2577) were described as future work
  but have shipped (#406, #516).
- The documentation section undersold the coverage: all implemented non-experimental features are
  documented with examples (#472, #515).

The refreshed text records the implemented spec revisions and how the 2026-07-28 revision actually shipped,
and keeps the tasks extension (SEP-2663, #391) and the removal of legacy-era support as the remaining tracked items.
Gem versions are deliberately not named: the roadmap describes the current state of the SDK,
and the version-to-revision mapping already lives in CHANGELOG.md.

## How Has This Been Tested?

Documentation-only change; no code paths are affected. Statements were cross-checked against the v1.2.0 CHANGELOG entry
and the 2026-08-15 tier audit results (server 67/67 and client 50/50 scored conformance across the 2025-11-25
and 2026-07-28 requirement sets).

## Breaking Changes

None. This only updates ROADMAP.md.
2026-08-15 12:13:25 +09:00
Koichi ITO
8cac72771c
Merge pull request #518 from koic/release_1_2_0
Release 1.2.0
2026-08-15 11:52:38 +09:00
Koichi ITO
af02717e28 Release 1.2.0
This release completes the SEP-2575 stateless lifecycle of the 2026-07-28 specification,
together with the SEP-2322, SEP-2549, and SEP-2243 features that revision builds on.

Several entries under "Changed" are incompatible with 1.1.0 and ship in a minor release
under the spec-conformance and security exceptions in VERSIONING.md.
Servers no longer echo 2026-07-28 from `initialize` and counter-offer 2025-11-25 instead,
`Configuration` accepts only handshake versions for its `protocol_version` pin,
server-to-client requests are bounded by a timeout and refused outright on the modern lifecycle,
the client bounds automatic pagination and its total SSE reconnection wait,
and `prompts/get` answers Invalid Params where it used to answer Internal Error.

Closes #512.
2026-08-15 11:49:42 +09:00
Koichi ITO
a62e56ef48
Merge pull request #516 from koic/counter_offer_legacy_version_on_initialize
Stop negotiating modern protocol versions through the `initialize` handshake
2026-08-15 11:32:15 +09:00
Koichi ITO
84eac104f0
Merge commit from fork
Restrict OAuth Discovery URL Destinations
2026-08-15 11:26:11 +09:00
Koichi ITO
c4921ed09f
Merge pull request #517 from latent-9/prompts-get-invalid-params
Return Invalid Params for unknown prompts and missing prompt arguments
2026-08-15 11:24:58 +09:00
Koichi ITO
ddec72f861
Merge pull request #514 from koic/http_standard_headers_driver
Drive the `http-standard-headers` scenario in the conformance client
2026-08-15 11:18:42 +09:00
latent-9
feba4d4893
Return Invalid Params for unknown prompts and missing prompt arguments
An unknown prompt name and a missing required prompt argument are client input errors, but prompts/get raised them with the default Internal Error (-32603). The tools/call, resources/read, and completion/complete siblings already return Invalid Params (-32602) for the same not-found and missing-input conditions (resources/read via ResourceNotFoundError, per SEP-2164).

Add an explicit error_code so both map to -32602 while keeping the descriptive message and the existing instrumentation labels.
2026-08-15 07:55:27 +12:00
Koichi ITO
ab17d50288
Merge pull request #515 from koic/add_list_changed_notification_examples
[Doc] Add prompts/resources list-changed notification examples to README.md
2026-08-15 00:11:19 +09:00
Koichi ITO
48b7aaacd9 Stop negotiating modern protocol versions through the initialize handshake
## Motivation and Context

Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/issues/512#issuecomment-5285679761

A comment on #512 reported that results stay unstamped when a client negotiates `2026-07-28` through
the legacy `initialize` handshake: the SEP-2322 `resultType` stamp and the SEP-2549 cache hints are
both gated on the per-request `_meta` envelope, which such a connection never carries,
so strictly validating clients reject every result as missing the REQUIRED `resultType`.

The root cause sits upstream of the stamp. Per the SEP-2575 era model, an era is a property of
the protocol version itself: legacy versions establish a session via `initialize`
(`2025-11-25` and earlier), and modern versions carry their version on every request in `_meta` with
no handshake at all - the 2026-07-28 schema defines no `initialize`, and a request without the envelope
is malformed. The negotiation list of this server still contained `2026-07-28`, producing a hybrid state
the spec does not define and the reference SDKs refuse to construct: the TypeScript server negotiates
from `SUPPORTED_PROTOCOL_VERSIONS`, which stops at `2025-11-25`, and counter-offers its first entry;
the Python server negotiates from `HANDSHAKE_PROTOCOL_VERSIONS`, which stops there too,
and counter-offers `LATEST_HANDSHAKE_VERSION`.

`initialize` now negotiates from a new `SUPPORTED_HANDSHAKE_PROTOCOL_VERSIONS` list
(`2025-11-25` and earlier): a request for `2026-07-28`, or for a version this server does not know,
is counter-offered `2025-11-25`, exactly as both reference SDKs answer. A counter-offered client proceeds on
`2025-11-25`, where `resultType` does not exist and its absence is the correct shape,
resolving the reported rejection. `2026-07-28` stays reachable through `server/discover` and
the per-request envelope, where the stamps already apply. The `envelope &&` stamp gates are
intentionally unchanged: with the handshake capped, an envelope-less `2026-07-28` connection is
no longer constructible, so the gates are correct by construction.

The client side is symmetrized the same way, matching both reference SDKs:
the legacy handshake offers `LATEST_HANDSHAKE_PROTOCOL_VERSION` by default,
passing an explicitly modern `protocol_version` to the legacy connect raises `ArgumentError`
(validated before the stdio transport spawns its child process), and a server answering `initialize` with
a modern version is rejected like an unknown one. `:auto` forwards an explicitly modern version to
the discovery probe and never downgrades it into the legacy fallback: the probe's failure is
the real answer and propagates, instead of the fallback dying on the handshake guard.
The handshake rule itself lives in one place (`Configuration.reject_modern_handshake_version!`),
and the handshake list is derived from the stable and modern lists so the era partition cannot drift
when the next revision lands.

Two consequences are worth naming. The roots/sampling deprecation warnings move to the modern connect
on the client, the revision where SEP-2577 actually deprecates them, since the handshake can no longer land
on a deprecating version and the call site the warnings used to sit on had become unreachable.
On the server the answer is removal: `Configuration#protocol_version` scopes the handshake,
so it now accepts handshake versions only and rejects a modern pin with `ArgumentError` at construction.
Accepting one would configure nothing (a modern version has no handshake to pin),
and neither reference SDK carries a config value that is accepted but inert:
Python's negotiation has no knob at all, and every entry of the TypeScript server's `supportedProtocolVersions`
is consumed by its own era's mechanism. With no path left onto a deprecating revision,
the server-side deprecation warning plumbing became unreachable and is removed along with it.
Keying those warnings on a modern-era session instead was tried and rejected,
because `notify_log_message` is the SEP-2575 sanctioned delivery path on that wire and every log line
would then carry a deprecation warning for doing exactly what the revision prescribes
(a single test file produced over a thousand of them).

A session-bound request may still stamp `MCP-Protocol-Version: 2026-07-28` after being counter-offered,
and such a request continues to be served at the negotiated revision rather than rejected.
Sending the negotiated version is a SHOULD on the client, and the spec's `400 Bad Request` rule
covers a version the server does not support, which is not the case here: this server does serve `2026-07-28`,
through the other lifecycle. The session it is bound to decides, and a test now pins that reading along with
its consequence, which is that no `resultType` appears on those results.

Two details follow from the pin being handshake-scoped. Reading it back when nothing is set
now answers `LATEST_HANDSHAKE_PROTOCOL_VERSION` rather than the newest version of any era,
so the getter no longer hands out a value its own writer rejects and round-tripping
the setting keeps working; only `Server#validate!` reads that default,
through three comparisons that answer the same for either value, so nothing else moves.
And the rejection names its reason instead of listing the accepted versions,
because this is the error an upgrade from a release that accepted the value lands on,
which makes it the migration note a bare list would not be.

`MCP::ProtocolDeprecations` says in its own documentation that only the client emits these warnings now,
and that `LOGGING_MESSAGE` has no caller left. It stays public and callable: removing it would be
a breaking change for no gain.

The handshake examples in `docs/building-clients.md` and the shared `initialize_params` test helper
now use the handshake version as well, and the README section on `protocol_version` describes the pin as
handshake-scoped: handshake versions only, `ArgumentError` for a modern one, the handshake version as the default,
and `2026-07-28` reached through `server/discover` with no configuration needed.

## How Has This Been Tested?

New regression tests pin the reported scenario end to end: an `initialize` requesting `2026-07-28` is
counter-offered `2025-11-25`, locks the legacy era, and subsequent results carry no `resultType`
(the correct shape at that revision). Client-side tests cover the default `2025-11-25` offer,
the `ArgumentError` for an explicitly modern version on the legacy connect
(asserting no child process is spawned on the stdio transport), the rejection of a modern `InitializeResult`
on both transports, the `:auto` probe failure propagating for an explicitly modern version instead of
falling back, and the deprecation warning firing on modern connects declaring roots/sampling capabilities.

Counter-offer adoption gets its own test on both transports, since the server-side fix only resolves anything for
clients that honor a counter-offer, and this client is one of them: the offer is the latest handshake version,
the answer is an older one, and the connection speaks the answer afterwards
(over HTTP the next request's `MCP-Protocol-Version` header carries it). The existing tests could not tell adoption
from an echo, because every one of them had the server answer with the version the client had just offered.
Both new tests were confirmed to fail when the client is made to report its own offer instead.

Tests that pinned the previous dual-lifecycle negotiation were inverted or reworked:
the server tests asserting `2026-07-28` echoes and fallbacks now assert the counter-offer,
and the deprecation warning tests keyed on a legacy-negotiated `2026-07-28` now assert no warning fires.
The server-side deprecation tests that reached their state by calling `mark_initialized!` with a modern version,
or by pinning one in `Configuration`, were replaced by tests asserting no warning fires on those paths,
since no code path can produce the warning state any more; `Configuration` rejecting a modern pin has its own tests
on the constructor and the setter, asserting the reason in the message rather than the list of accepted values.

The default-pin test now also round-trips what it reads back into a fresh `Configuration`,
which is what the old default could not do. The default move was checked for neutrality outside
the suite as well, by building a server that uses every feature `Server#validate!` gates on that value
(`description`, `title`, `website_url`, `instructions`, a `$ref` input schema, and tool annotations)
and confirming all of them are still accepted.

## Breaking Changes

Servers no longer echo `2026-07-28` from `initialize`: clients that negotiated it through
the handshake are counter-offered `2025-11-25` and are served at that revision, matching
the TypeScript and Python servers. `Configuration.new(protocol_version: "2026-07-28")` now
raises `ArgumentError` (the pin scopes the handshake, which cannot land there);
the value was only accepted since v1.1.0, whose handshake behavior this change replaces anyway.
Reading `Configuration#protocol_version` with no pin set answers `2025-11-25` instead of `2026-07-28`;
nothing in this SDK behaves differently for either value, but code comparing that reader against
a literal will see the change. The client no longer offers modern versions on the legacy handshake
and rejects a modern `InitializeResult`. Server-side deprecation warnings for SEP-2577 features
no longer fire at all, because no negotiation or configuration path can put a connection on a deprecating revision;
the client-side warning on a modern connect replaces them.
2026-08-14 16:08:07 +09:00
Koichi ITO
67779a2e88
Merge pull request #505 from koic/bound_client_automatic_pagination
Bound automatic pagination in the MCP client
2026-08-14 05:38:04 +09:00
Koichi ITO
a4a885683c Bound automatic pagination in the MCP client
## Motivation and Context

`MCP::Client#tools`, `#resources`, `#resource_templates`, and `#prompts` follow `nextCursor`
until the server stops offering one. The `seen` set in `fetch_all_pages` catches a server that
repeats or cycles cursors, but a fresh cursor on every response walks past that guard, and
the client keeps requesting and retaining pages for as long as the server keeps producing them.
The transports' per-message limits do not help here, since each individual page can be small.

`MCP::Client.new` now takes `max_pages:`, defaulting to `MAX_PAGES` (1000). Reaching it raises
`PaginationLimitError` rather than truncating the collection silently, since a short array would
be indistinguishable from a server that genuinely ran out of items. The single-page `list_*` methods
are unchanged, so callers who need their own policy still have one.

## How Has This Been Tested?

New tests in `test/mcp/client_test.rb` cover a server that returns a distinct cursor per page,
the boundary where a server stops exactly at `max_pages`, and the argument validation.
The existing repeat-cursor and cycling-cursor tests are unaffected.
`bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

An all-pages call against a server offering more than 1000 pages now raises
`MCP::Client::PaginationLimitError` instead of continuing. Pass a larger `max_pages:` to
`MCP::Client.new` if that is expected.
2026-08-14 04:45:32 +09:00
Koichi ITO
34d7fca0ac
Merge pull request #504 from koic/bound_sse_reconnection_delay
Bound the total wait across SSE reconnection attempts
2026-08-14 04:41:47 +09:00
Koichi ITO
6a19688cf3 [Doc] Add prompts/resources list-changed notification examples to README.md
## Motivation and Context

The SDK tiering system (SEP-1730) requires Tier 1 SDKs to document all non-experimental features with examples.
The 2026-08-14 documentation coverage audit found the last two example gaps: the Notifications section documents
`notify_prompts_list_changed` and `notify_resources_list_changed` in prose, but only `notify_tools_list_changed`
appeared in a code example, leaving the prompts and resources variants PARTIAL.

The Usage Example in the notifications chapter now defines a prompt and a resource and broadcasts
the matching list-changed notification for each, alongside the existing tools example. The block signatures mirror
the canonical `define_prompt` / `define_resource` examples earlier in the README.md.

## How Has This Been Tested?

Documentation-only change. The snippet was verified end to end against the current public API: both definitions
serve `prompts/get` / `resources/read` responses and all three notify calls run without error.

## Breaking Changes

None. This only extends a code example in README.md.
2026-08-14 04:24:30 +09:00
Koichi ITO
c8116fbcf0 Drive the http-standard-headers scenario in the conformance client
## Motivation and Context

The 2026-07-28 requirement set scores `http-standard-headers` (SEP-2243) on the client leg,
but `conformance/client.rb` had no case for it: the scenario hit the unknown-scenario abort,
the client exited 1, and every `Mcp-Method` / `Mcp-Name` check reported SKIPPED
("Client did not send a ... request"), failing the scenario in tier-check.
The 2026-08-14 tier audit flagged this as the only scored conformance failure (client leg 49/50).

The transport already sends the standard headers on the modern path; what was missing is
a driver that exercises each request kind the harness observes. The new case issues `tools/list`,
`tools/call` (the `test_headers` fixture tool), `resources/list`, `resources/read`
(the first listed resource URI), `prompts/list`, and `prompts/get` (the first listed prompt),
letting the harness see the `Mcp-Method` header on every POST and the `Mcp-Name` header on
the three name-carrying requests. The `initialize` / `notifications/initialized` rows stay SKIPPED
by design: the 2026-07-28 wire is stateless, so those requests are never sent.

## How Has This Been Tested?

`conformance client --scenario http-standard-headers --spec-version 2026-07-28` passes 9/9 checks,
and the full `--requirements 2026-07-28` client leg exits 0 with every scored scenario passing
(435 checks; the only failures are the baselined not-scored DPoP/WIF extensions). RuboCop is clean.

## Breaking Changes

None. The change only adds a scenario driver to the conformance client fixture; library code is untouched.
2026-08-14 04:22:23 +09:00
Koichi ITO
0695c43ebe
Merge pull request #501 from koic/mrtr_legacy_shim
Fulfill `input_required` results on the legacy wire per SEP-2322
2026-08-14 02:50:46 +09:00
Koichi ITO
b159314baa Fulfill input_required results on the legacy wire per SEP-2322
## Motivation and Context

SEP-2322 handlers return `InputRequiredResult` instead of issuing in-flight server-to-client requests,
but that result type exists only on the 2026-07-28 wire: pre-2026 clients treat an unknown `resultType`
as a final result, so the server rejected `input_required` on legacy requests with an internal error.
That forced authors to keep two handler styles, one per era.

This adds the dual-era authoring shim both reference implementations converged on:
the TypeScript SDK's default-on legacy fulfilment shim (typescript-sdk#2381)
and the Python SDK's version-negotiating resolver (python-sdk#2986).
When a `tools/call`, `prompts/get`, or `resources/read` handler returns an `InputRequiredResult` on
the legacy wire, the server fulfills it in place of the client's driver:

- Every `inputRequests` entry is sent verbatim as the equivalent real server-to-client request through
  a new `ServerSession#fulfill_input_request` (per the spec, clients treat each embedded entry exactly like
  the standalone request), stamped with the originating request id so the association requirement of
  SEP-2260 holds and Streamable HTTP delivery rides the originating POST stream. One exception to
  the verbatim forwarding: a URL-mode elicitation leg gains a synthesized `elicitationId` when
  the handler supplied none, since the 2025-11-25 wire requires the field and the 2026-07-28 in-band
  shape dropped it (correlation rides `requestState` there) - matching the TypeScript shim.
- The answers are collected under the same keys and the handler re-runs with `inputResponses`
  and the raw `requestState` merged into the original params - the same deterministic replay contract
  the modern client driver follows, read through the existing `server_context.input_responses`/`request_state` accessors.
  Only the current round's responses are sent, matching the client driver; handlers carry earlier answers through `requestState`.
- `requestState` round-trips in-process as the value the handler wrote. `RequestStateSecurity` sealing is
  wire hardening against a tampering client and does not apply to the in-process replay.
- The embedded-capability gate still runs each round against the session's declared client capabilities;
  a violation fails before any client contact. The `-32021` code is 2026-only, so the legacy wire gets
  an internal error naming the missing capabilities.
- Rounds are capped at 8 (`LEGACY_INPUT_REQUIRED_MAX_ROUNDS`), matching the TypeScript shim's `maxRounds` default;
  exhaustion fails with an explanatory internal error, which also bounds the `requestState`-only load-shedding form
  that cannot make progress in-process.

The shim is on by default, matching the TypeScript SDK; `Server.new(input_required_legacy_shim: false)` restores
the strict rejection. Requests without a session (no notification path back to a client) and all modern requests
are untouched: the modern wire keeps returning the `input_required` result for the client driver.

Resolves #382.

## How Has This Been Tested?

`bundle exec rake` passes: 1691 test runs / 4381 assertions with zero failures and RuboCop clean.
The conformance baseline check passes on both legs (the frozen 2025-11-25 wire is where the shim lives),
and the modern `input-required-result-*` scenarios stay green, confirming the modern path is untouched.

New `test/mcp/server_input_required_legacy_shim_test.rb` covering: completion through
a real elicitation with the SEP-2260 association asserted on the transport, replay exposing
the collected responses and the raw `requestState`, sealing bypass under `RequestStateSecurity`,
`prompts/get` and `resources/read` shimming, multi-round collection, the round cap, the capability gate failing
before client contact, the URL-mode leg gaining a synthesized `elicitationId` (and a handler-supplied
one riding unchanged), a client answering a fulfilment leg with an error failing the original request,
the opt-out, session-less rejection, and modern requests staying untouched.

The pre-existing legacy rejection test (session-less) and all modern MRTR serialization tests pass unchanged.

## Breaking Changes

Only for handlers that returned `InputRequiredResult` to legacy clients THROUGH A SESSION and relied
on the internal-error rejection: those now drive a real fulfilment round trip by default.
No such handler could have worked end to end before (the request always failed), so this is the intended upgrade;
`input_required_legacy_shim: false` restores the previous behavior. Everything else is unchanged.
2026-08-14 02:46:38 +09:00
Koichi ITO
33ed4a80aa
Merge pull request #500 from koic/client_input_required_driver
Drive multi round-trip `input_required` results on the client per SEP-2322
2026-08-14 02:25:29 +09:00
Koichi ITO
2fb9ab8e6a Drive multi round-trip input_required results on the client per SEP-2322
## Motivation and Context

Final step of SEP-2322 (modelcontextprotocol/modelcontextprotocol#2322) for the 2026-07-28 MCP spec release.
The client so far only recognized `input_required` results by raising `InputRequiredError`; this adds the resume loop,
mirroring the Python SDK's high-level `Client` driver and the TypeScript SDK's `runInputRequiredDriver`.

- The driver answers embedded requests with the handlers already registered through `on_elicitation`,
  `on_sampling`, and the new `on_roots`. There is no second registration path: a server can ask for input two
  ways, as a real request mid-call and as an entry in an `input_required` result, and one registration covers
  both. This follows the TypeScript driver, which dispatches "to the client's already-registered handlers
  (elicitation, sampling, roots - one generic engine, no per-feature API)".
- `on_elicitation` and `on_sampling` no longer refuse a transport without `on_server_request`. They record
  the handler either way and wire it to the transport only when it can carry server-to-client requests. Refusing
  would have locked stdio clients, and every 2026-07-28 connection, out of the only route the spec leaves:
  the modern lifecycle forbids server-to-client requests, so an embedded request is how it asks.
- `MCP::Client.new` gains `input_required_max_rounds:` (default 10, the TypeScript and Python default).
- Once a handler is registered, `call_tool`, `get_prompt`, and `read_resource` resume automatically:
  each `inputRequests` entry is fulfilled by the matching handler and the ORIGINAL request is re-issued with
  `inputResponses` under the same keys plus the byte-exact echoed `requestState`, on a fresh JSON-RPC id per leg
  (modern envelope stamping happens in the transports per send, so every leg carries the SEP-2575 triple).
  A `requestState`-only result (load shedding) retries after an exponential backoff from 50ms to a 250ms cap,
  matching the Python SDK; every leg counts against the round cap, whose exhaustion raises `InputRequiredError`
  carrying the last result.
- A requested kind without a matching handler falls back to the manual path by raising `InputRequiredError`,
  and clients with no handlers keep the exact pre-existing behavior. For manual driving,
  `call_tool` / `get_prompt` / `read_resource` gain `input_responses:` and `request_state:` keyword arguments
  that ride at the params top level. Non-MRTR methods such as `tools/list` keep raising unconditionally.

The conformance client rides the same change: it derives its lifecycle from the wire version the harness names per run
(`MCP_CONFORMANCE_PROTOCOL_VERSION`), connecting with `mode: :modern` for the 2026 draft and keeping the pinned legacy
handshake through 2025-11-25, retrying a modern connect once when the server rejects the first request with `-32022`
naming its supported versions. New scenario branches drive `sep-2322-client-request-state` through this driver
(an accepting `on_elicitation` handler plus the four `test_mrtr_*` tools), `request-metadata`, both SEP-2243 header
scenarios, and `json-schema-ref-no-deref`. The expected-failures baseline drops the six scenarios this stack resolves,
leaving only the not-scored extensions and the post-anchor `json-schema-2020-12-preservation`.

Verified end-to-end over stdio: a modern connection (`connect(mode: :modern)` with declared form-elicitation capability)
against a server whose tool returns `InputRequiredResult` under `RequestStateSecurity` sealing completes in two legs with
the handler supplying the answer, and a handler-less client receives `InputRequiredError` with the sealed opaque state.

Part of #382.

## How Has This Been Tested?

New tests in `test/mcp/client_test.rb` (Mocha sequenced transports) cover: the two-leg happy path asserting preserved original params,
key-matched `inputResponses`, byte-exact `requestState` echo, and a fresh id per leg; the exponential backoff sequence for
`requestState`-only legs (stubbed `sleep`); round-cap exhaustion raising `InputRequiredError` with the last state; the unhandled-kind
fallback; the manual `input_responses:`/`request_state:` keyword arguments; and the `prompts/get` driver path. The existing SEP-2322
recognition tests pin the no-handler behavior unchanged.

Three tests cover the shared-registration design specifically: the driver resolving an embedded request on a transport that
has no `on_server_request` at all, an `on_roots` handler answering an embedded `roots/list`, and `on_elicitation` and
`on_sampling` accepting a registration on such a transport rather than raising, which replaces the two tests that pinned
the old refusal.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes, plus the stdio end-to-end script described above.

With the separate SEP-2243 mirroring change applied alongside, every scored scenario of the frozen 2026-07-28 client leg passes
(`sep-2322-client-request-state` 5/5, `request-metadata` 5/5 with no version-retry warning, `http-custom-headers` 18/18,
`http-invalid-tool-headers` 11/11), and the `--requirements` client legs at both revisions report failures only
in not-scored scenarios. The full conformance task passes its baseline check on both legs.

## Breaking Changes

`on_elicitation` and `on_sampling` no longer raise `ArgumentError` on a transport without `on_server_request`; they
register the handler for the `input_required` route instead. Code that relied on the refusal to detect an unsuitable
transport needs another check. Everything else is additive: the new keyword arguments default to `nil`, and with no
handler registered every code path is identical to before.
2026-08-14 02:04:21 +09:00
Koichi ITO
c3ca40f770
Merge pull request #513 from koic/fix_non_cacheable_cache_hints_test
Stop using `ping` as the non-cacheable result example
2026-08-14 01:03:47 +09:00
Koichi ITO
ed802f7494 Stop using ping as the non-cacheable result example
## Motivation and Context

`main` is red on every Ruby version: "modern non-cacheable results carry no cache hints" errors with
`undefined method 'key?' for nil`. The test reaches for `response[:result]` on a request that no longer
produces a result.

Two changes met on `main` without conflicting textually. #499 added the test and picked `ping` as its example of
a result that is not cacheable. #511 then made a modern-enveloped request naming a method SEP-2575 removed answer
with `-32601` even before the connection era locks, and `ping` is one of those methods, so the response now carries
an error rather than a result. Each branch was green against the `main` it was written on; the pairing only failed
once both had landed.

`ping` was the wrong example regardless. It is absent from the 2026-07-28 schema, so no modern request can name it
and receive a result of any shape. `tools/call` is the accurate stand-in: the spec types `CallToolResult` as
a plain `Result`, while the ones it types as `CacheableResult` are the discover, list, and read families.
The test now calls the tool it already registers, and a comment records why `ping` cannot come back here -
the same note #511 left where it replaced `ping` with `prompts/list` in the neighboring `resultType` test.

Only the test changes. The behavior both #499 and #511 implement is correct; the example the test chose was not.

## How Has This Been Tested?

The test errors on `main` and passes with this change. `bundle exec rake` (tests, RuboCop, and conformance baseline) passes.
The rest of the suite was searched for the same pattern, a modern-enveloped request naming a method the modern lifecycle removed:
the only other occurrence is the assertion #511 added deliberately, which checks that such a request does not lock the era,
and which reads no result.

## Breaking Changes

None. No library code changes.
2026-08-14 01:00:14 +09:00
Koichi ITO
451c2b3c89
Merge pull request #511 from koic/reject_modern_removed_methods_before_era_lock
Reject modern-removed methods before the connection era locks
2026-08-14 00:45:15 +09:00
Koichi ITO
cfd9a7b0ba
Merge pull request #503 from koic/reject_modern_lifecycle_server_requests
Refuse server-to-client requests in the modern lifecycle per SEP-2575
2026-08-13 23:27:36 +09:00
Koichi ITO
bea636c007 Refuse server-to-client requests in the modern lifecycle per SEP-2575
## Motivation and Context

The modern lifecycle removes server-initiated JSON-RPC requests: a stateless server has no connection to send them on,
and SEP-2322 multi round-trip `input_required` results replace what sampling and elicitation covered before.
`StdioTransport#send_request` already says so, refusing outright when its session is modern.
`StreamableHTTPTransport#send_request` says nothing, so a modern handler that reaches for elicitation
or sampling falls through to the session lookup and is told `Session not found: <uuid>` against a session id it never chose.
Failing is right, the explanation is not: `handle_modern` mints a session per request without ever registering it in `@sessions`,
so that lookup cannot succeed for a modern request no matter what the handler does.

`send_request` now refuses a modern-era session up front with the message `StdioTransport` uses, which turns
an incidental registration detail into a stated rule and leaves the rest of the method a legacy-only path by construction.
Callers see the same `RuntimeError` class as before, only with a message naming the actual constraint.

## How Has This Been Tested?

A new test in `test/mcp/server/transports/streamable_http_transport_test.rb` sends `elicitation/create` from
a session constructed with `era: :modern` and asserts the SEP-2575 message. It sits with the existing guard tests for stateless mode,
a missing `session_id`, and an unknown session, which still pass unchanged.
`bundle exec rake` is green, and both conformance legs pass their baseline check.

## Breaking Changes

None. The call already failed; only the message changes.
2026-08-13 23:25:04 +09:00
Koichi ITO
0575dc0de8
Merge pull request #502 from koic/add_server_request_timeout
Bound server-to-client requests with a timeout
2026-08-13 23:23:12 +09:00
Koichi ITO
416b7e8a6e Bound server-to-client requests with a timeout
## Motivation and Context

The specification asks implementations to establish timeouts for all sent requests,
"to prevent hung connections and resource exhaustion", to cancel the request once the deadline passes,
and to let SDK users configure the deadline per request. This SDK did none of the three: `send_request` blocked
on `Queue#pop` with no deadline, so a client that opens a session, triggers a handler that elicits input,
and then simply never answers holds that worker thread for good. A handful of such requests exhausts
a Rack server's thread pool. The existing escape hatches are weak: the idle reaper waits 1800 seconds
by default and refreshes on any traffic for the session, so a client that keeps sending other requests never trips it,
and only the GET stream has a keepalive to notice a vanished peer.

`StreamableHTTPTransport` now waits `server_to_client_request_timeout:` seconds
(`DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT`, 600) for a response, and `timeout:` overrides it per request through
`ServerContext` and `ServerSession` down to the transport. The option spells out its direction because
the same constructor already takes `max_request_bytes:` for the requests arriving the other way.
Ten minutes matches the TypeScript SDK, which raises its uniform 60-second request default to 600 seconds for
the legs of its legacy `input_required` shim because they are "human-paced, so the 60s protocol default is wrong".
Every request this transport can send is that kind of leg: someone answering an elicitation prompt, or the client's
own model producing a sample. The Python SDK leaves the deadline unset and bounds nothing by default.

On expiry the transport sends `notifications/cancelled` for the request it stopped waiting on, so a late answer
does not act on something the server abandoned, and raises the new `MCP::Server::RequestTimeoutError`.
Both reference SDKs send the same courtesy cancel on timeout, and it is what the revision governing this path asks
for: 2025-11-25 lets either side cancel and tells the sender to "issue a cancellation notification for that request
and stop waiting". Only that revision and earlier reach the wait, since the modern lifecycle forbids these requests
and its sessionless requests never register the session `send_request` looks up.

Uncaught in a handler, the error answers the client's originating request with `-32001` rather than a generic
internal error. The code is not spec-allocated, but it sits in the implementation-defined server range and is what
the Python SDK reports for this condition, so a peer that recognizes it there reads the same meaning here.

The wait itself moves from `Queue` to a small `MCP::Server::PendingResponse`: `Queue#pop` only accepts a `timeout:`
on Ruby 3.2 and later and this gem supports 2.7, so the wait is a `ConditionVariable` with a monotonic deadline.
It keeps the `push`/`pop` names, leaving the three resolving call sites (a client response, a cancellation, session teardown)
unchanged, and keeps first-writer-wins so a cancellation racing a real response still cannot overwrite it.
The expiry block runs after the lock is released, since it cancels the request and would otherwise re-enter
the same non-reentrant mutex.

stdio is untouched and ignores `timeout:`, which the README now states. Its `send_request` waits inside
a `$stdin.gets` loop rather than on a queue, and the process model differs enough (the server owns the client
process, whose exit surfaces as EOF) that it deserves its own change; `forward_to_transport` already filters
`timeout:` out for transports that do not declare it, so custom transports and stdio keep their existing signatures.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` cover a request timing out with
the transport default, `timeout:` overriding it per request, the error code it reports, expiry reaching the peer
as `notifications/cancelled`, a response arriving before the deadline still returning normally, and
the constructor rejecting a non-positive `server_to_client_request_timeout`.
`test/mcp/server_session_request_timeout_test.rb` covers the deadline reaching the transport from all five
`ServerSession` entry points, and being dropped for transports that never declared it.
`test/mcp/server_context_test.rb` covers the same through `ServerContext`, including an omitted `timeout:`
not being forwarded at all. The pre-existing `send_request` tests (the response path, cross-session rejection,
cancellation, the cancel/response race, client errors, and session teardown) pass unchanged against the new
wait primitive.

`bundle exec rake` is green, and both conformance legs pass their baseline check. `PendingResponse` was exercised
directly on Ruby 2.7.0, the minimum this gem supports and the reason the wait avoids `Queue#pop(timeout:)`:
the deadline fires on time, a pushed value is delivered, the first writer wins, and the expiry block can resolve
the same object without deadlocking.

## Breaking Changes

Server-to-client requests that previously waited forever now fail after ten minutes by default. This is
the incompatible-but-required kind of change VERSIONING.md admits into a minor release: the unbounded wait deviates from
the specification and is the resource-exhaustion path it exists to prevent. Handlers that legitimately wait longer pass
a larger `timeout:`; the release notes and CHANGELOG entry need to call this out and point at that knob.
2026-08-13 23:16:59 +09:00
Koichi ITO
b09708365b
Merge pull request #499 from koic/stamp_cache_hints_on_modern_results
Stamp the required cache hints on modern cacheable results per SEP-2549
2026-08-13 23:14:17 +09:00
Koichi ITO
ebed930927
Merge pull request #495 from koic/subscriptions_listen
Serve the `subscriptions/listen` notification stream per SEP-2575
2026-08-13 23:05:35 +09:00
Koichi ITO
aaf0c71995 Restrict OAuth Discovery URL Destinations
## Motivation and Context

The OAuth client checked the scheme of every discovery URL but never checked where it pointed.
`Discovery.secure_url?` returns true for any `https` URL regardless of host, and the `resource_metadata` URL from
a `WWW-Authenticate` challenge is placed first in the candidate list, so a server answering
`401 Bearer resource_metadata="https://169.254.169.254/..."` had the client issue that request during discovery,
before the user approves anything. The same gap applied one hop deeper: a server that serves its own
Protected Resource Metadata can name any host in `authorization_servers`, and the endpoints in the document fetched
from there receive the dynamic client registration and the token request that carries the client credentials.

Two rules now apply to those URLs. Both run before the request is sent, and neither is configurable.

The `resource_metadata` URL must be on the MCP server's own origin. Protected Resource Metadata describes that server,
so a real deployment publishes it there, and requiring it means a challenge cannot aim the first request of the flow at
an unrelated host. RFC 9728 does not itself require this, so the SDK is deliberately stricter than the specification:
the range check below cannot recognize an internal host that is named rather than addressed, and this is the one URL
a server supplies directly.

The PRM `authorization_servers` entry and the `authorization_endpoint`, `token_endpoint`, and `registration_endpoint`
from Authorization Server metadata must not be IP literals in a private, loopback, link-local, or unique-local range,
which is the precaution RFC 9728 Section 7.7 asks clients to take. That check is skipped when the configured MCP server URL
is itself on such an address. Pointing a client at a private network is a deliberate act and its authorization server
usually lives on the same network, so `http://localhost` development and deployments that never leave a corporate network
keep working. Only a server reachable on the public internet is barred from steering the client inward.

A range check is only as good as its reading of the address, so the second rule also refuses hosts written in
the numeric IPv4 grammar `inet_aton` accepts and `IPAddr` rejects: one to four dot-separated parts, each hexadecimal,
octal, or decimal, with the last part filling the remaining bytes. `2130706433`, `127.1`, and `0x7f000001` all reach
127.0.0.1, and `0xa9fea9fe` reaches the cloud metadata address, so reading only the dotted-decimal spelling would refuse
`169.254.169.254` while admitting every alias of it. Those hosts are refused outright rather than decoded and
range-checked, because their value is resolver-dependent: a leading zero reads as octal on one platform and decimal on
another, which is the difference between 8.0.0.1 and 10.0.0.1 for `010.0.0.1`. Choosing a reading here would leave
whichever one was not taken as a way through, and nothing is legitimately addressed in this notation.

Hostnames are not resolved. A lookup here would be a second network request driven by the same untrusted input,
and the address it returned need not be the one the HTTP client connects to a moment later, so the check would read as
a guarantee it cannot make. `MCP::Client::OAuth::Flow` also documents why its Faraday connection has no redirect-following
middleware: every check runs against the URL as written, so a connection that follows a `3xx` on its own would reach hosts
these rules just refused.

## How Has This Been Tested?

- New unit tests in `test/mcp/client/oauth/discovery_test.rb` cover `same_origin?` (case-insensitive scheme and host,
  explicit default ports, differing port/host/scheme, subdomains, malformed and hostless input) and `private_network_host?`
  (every blocked range, IPv4-mapped IPv6 spellings, bracketed IPv6, `localhost` matched exactly, and public addresses and names).
  One test documents that a named internal host reads as public, which is the deliberate limit of the predicate.
- Further unit tests cover the numeric spellings: packed integers, hexadecimal, and short forms that reach a blocked range,
  and the ambiguous leading-zero forms whose value depends on the resolver. Removing the rule leaves them addressable,
  which is what those tests fail on.
- New tests in `test/mcp/client/oauth/flow_test.rb` and `test/mcp/client/oauth/http_oauth_test.rb` drive both rules through `run!`,
  `refresh!`, and the transport. They assert with `assert_not_requested` that no request was issued rather than only that an error
  was raised, since nothing downstream can un-send one. One of them names the authorization server `https://0xa9fea9fe`, which
  without the rule above is fetched. A further test runs a complete flow with the MCP server and the authorization server on
  two loopback ports, which is what the carve-out exists for.
- `rake conformance` passes with all 22 auth scenarios green. Its harness runs the MCP server and the authorization server on
  separate loopback ports and publishes PRM on the server's own origin, so it exercises exactly the shapes these rules must not break.

## Breaking Changes

A client whose MCP server is reachable on the public internet no longer follows a `resource_metadata` URL on a different origin,
and no longer contacts an authorization server or OAuth endpoint at a private IP literal or at a host written in the numeric
IPv4 notation above. All were previously allowed. Local development, private-network deployments, and the conformance suite
are unaffected.
2026-08-13 14:54:27 +09:00
Koichi ITO
bd702d3e51 Reject modern-removed methods before the connection era locks
## Motivation and Context

SEP-2575 removes `initialize`, `ping`, `logging/setLevel`, `resources/subscribe`,
and `resources/unsubscribe` from the modern lifecycle, and the server answers them with `-32601` there.
The check consulted `ServerSession#era` alone, but `StdioTransport` locks the era in `lock_modern_era_on_success`,
which runs after a response is produced. The first frame of a stdio connection therefore reached
the server with `era == nil`, and a request carrying the modern `_meta` envelope was served instead of refused.
All five methods leaked, one request per connection:

```
initialize             a full InitializeResult
ping                   {resultType: "complete"}
logging/setLevel       {resultType: "complete"}
resources/subscribe    {resultType: "complete"}
resources/unsubscribe  {resultType: "complete"}
```

`initialize` is the worst of the five because it also mutates the session: serving it negotiated
the legacy lifecycle for a request that had declared the modern one, pinning the connection to
`:legacy` and marking it initialized. The Streamable HTTP transport was never affected,
since it routes sessionless modern traffic to `handle_modern` and rejects a modern envelope on every other path.

The era is the wrong thing to consult on its own: a request declares which lifecycle it belongs to
through its own envelope, independently of connection state that settles later. The Python SDK gates
on exactly that, testing each request's `_meta` before dispatch rather than a negotiated connection
mode. `modern_request?` now does the same here, treating a locked `:modern` era as authoritative and
falling back to the request's envelope while the era is still undetermined. A legacy-locked session is left alone:
`lift_request_envelope` already answers a modern envelope there with the lifecycle violation,
which names the cause better than Method not found.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb` cover all five removed methods being refused with `-32601` when
they carry the envelope on an era-less session, an enveloped `initialize` no longer locking the era
or marking the session initialized, a method the modern lifecycle keeps still being served under the same
conditions, and a legacy `initialize` negotiating 2026-07-28 still succeeding and locking `:legacy` - negotiating
a dual-era version through the handshake is not the same as carrying the envelope. A test in
`test/mcp/server/transports/stdio_transport_test.rb` drives the case end to end,
sending an enveloped `resources/subscribe` as a connection's first frame.

One existing assertion changed. "modern results carry resultType complete" used `ping` as one of its
stamped examples, which only passed because of this defect; `ping` is absent from the 2026-07-28 schema,
so a modern request naming it is refused rather than stamped. It now uses `prompts/list`, with a note
on why `ping` cannot appear there. The existing legacy counterpart, which pings without an envelope,
is unchanged and still expects no stamp.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes. The conformance suite exercises
the HTTP transport, which this does not change, so its baseline is unaffected.

## Breaking Changes

None for a conforming client. A request that both carries the 2026-07-28 envelope and names a method
that revision removed now receives `-32601` instead of a result, which is the answer the spec already
required once the era was known.
2026-08-13 01:47:59 +09:00
Koichi ITO
8c2e89afd5 Pass a handler-returned _meta through the subscribe result
## Motivation and Context

`resources/subscribe` and `resources/unsubscribe` answered with a hardcoded `{}`, discarding whatever
the registered handler returned. A server had no way to attach anything to the response - not even `_meta`,
which the specification allows on every result. The handler docstring justified the discard as "always
an empty result `{}` per the MCP specification", but the spec does not require an empty object here:
the subscribe result is an `EmptyResult`, and every result may carry `_meta`.

The one field that is interoperable is `_meta`. The TypeScript SDK validates the subscribe result against
`EmptyResultSchema.strict()`, which rejects any member other than `_meta`, so a top-level field like
a bespoke `subscriptionId` would be refused by a TypeScript client. The Python SDK passes the handler's `EmptyResult`
return through, `_meta` included. Passing `_meta` matches both while staying within what the spec defines.

The subscribe and unsubscribe handlers now pass a returned `_meta` hash through to the result and drop anything else.
`subscription_result` reads `_meta` under a symbol or string key and includes it only when it is itself
a hash; every other return shape - a non-hash, or a hash without a usable `_meta` - keeps the empty `{}` result it
produced before. Advisory data such as a subscription identifier goes under `_meta`, namespaced, rather than
at the top level. This affects only 2025-11-25 and earlier connections, since `resources/subscribe`
and `resources/unsubscribe` are removed from the modern lifecycle.

Fixes #508.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb` cover a `_meta` hash passing through on both `resources/subscribe`
and `resources/unsubscribe`, a non-`_meta` field being dropped, a string `_meta` key working, a non-hash `_meta`
being ignored, and a non-hash return keeping the empty result. The existing subscribe and unsubscribe tests,
which return `{}` and assert an empty result, are unchanged.

## Breaking Changes

None. A handler that does not return a hash carrying a `_meta` hash - which is every handler written against
the previous "return value is ignored" contract - still produces the empty `{}` result.
2026-08-13 01:36:15 +09:00
Koichi ITO
27044b0047 Add a resources_list_handler for context-dependent resource lists
## Motivation and Context

`resources/read` can be taken over with `resources_read_handler`, but `resources/list` had no equivalent:
it was bound to the internal `list_resources`, which paginates the constructor-provided `resources` array,
and `define_custom_method` refuses to rebind a method the server already handles.
An application whose visible resources depend on the request - authenticated versus anonymous sessions,
or an OAuth-scoped connector that must see a scope-filtered set - had to build a fresh `Server` per request
or override a private method.

Both reference SDKs let the list vary per request. The TypeScript SDK exposes `resources/list` through
`setRequestHandler` and gives resource templates a per-context `listCallback(ctx)`; the Python SDK takes
an `on_list_resources` handler. This adds the Ruby equivalent.

`resources_list_handler(&block)` registers a block that returns the resource collection to serve.
It feeds `list_resources` rather than replacing it, so the framework still paginates the returned array
and stamps the SEP-2549 cache hints; the block returns only the array, matching how `resources_read_handler` returns
only the contents and the framework wraps them. A block that declares a `server_context:` keyword receives
an `MCP::ServerContext`, reusing the same opt-in rule the read handler uses, so the list can be filtered by
the authenticated principal or granted scope. The block is invoked once per page and must return
a stable ordering across the pages of one query, since the cursor is a positional offset. When no handler is set,
the constructor-provided resources are served unchanged.

The `resources` capability is advertised whether or not the constructor array is populated, so a server that
provides only a `resources_list_handler` still answers `resources/list`.

Fixes #507.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb` cover a handler replacing the served collection, a handler receiving `server_context:`
and returning different sets for authenticated and anonymous requests, pagination and cache hints still applying to
the handler-provided array, and a server with no constructor-provided resources served entirely by the handler.
The existing `resources/list` test, which exercises the no-handler default path, is unchanged.

## Breaking Changes

None. When no `resources_list_handler` is set, `resources/list` serves the constructor-provided resources exactly as before.
2026-08-13 00:21:41 +09:00
Koichi ITO
b195a21410
Merge pull request #506 from koic/cover_json_schema_2020_12_preservation_scenario
[Conformance] Cover the JSON Schema 2020-12 preservation scenario
2026-08-13 00:02:38 +09:00
Koichi ITO
927ccdd161 [Conformance] Cover the JSON Schema 2020-12 preservation scenario
## Motivation and Context

The `json-schema-2020-12-preservation` client scenario (SEP-1613, SEP-2106; not scored for
2026-07-28, as it was added after the requirements anchor) failed only because the conformance client
had no branch for it: an unknown scenario aborts after connecting, so the harness never observed
a `tools/list` nor the schema echo it diffs.

The client itself already preserves the vocabulary the scenario checks (`$schema`, `$defs` with
`$anchor`, `$ref`, `allOf`/`anyOf`, `if`/`then`/`else`, `additionalProperties`):
`Client::Tool#input_schema` is the parsed `tools/list` response untouched, with no dereferencing,
validation-time rewriting, or keyword stripping, the same fixture-echo approach
the TypeScript and Python conformance clients take. The new branch lists the tools and echoes
the focal tool's observed `inputSchema` verbatim through `json_schema_echo`,
and the expected-failures entry is removed.

## How Has This Been Tested?

The scenario passes 9/9 at its default 2025-11-25 wire. On top of the modern-lifecycle client selection
(the SEP-2322 driver branch) it also passes 9/9 at `--spec-version 2026-07-28`, where the SEP-2106 keyword checks
are failure-gated instead of skipped. `bundle exec rake` is green, with the conformance task passing its baseline check
on both legs, and RuboCop reports no offenses.

## Breaking Changes

None. The change is confined to the conformance client and its baseline; the shipped gem is untouched.
2026-08-12 02:26:41 +09:00
Koichi ITO
248b5f8403 Bound the total wait across SSE reconnection attempts
## Motivation and Context

The SSE `retry:` field is chosen by the server, and `MCP::Client::HTTP` passed it to `sleep` unchanged in
both reconnection paths. `await_response_after_disconnect` runs on the calling thread, so a server that primes
a stream with an event id, closes it gracefully, and asks for a large `retry:` interval keeps that thread waiting
for as long as it likes. `MAX_RECONNECTION_ATTEMPTS` caps how many times the client reconnects, not how long
it waits before each attempt, and no I/O timeout covers a sleep.

The obvious fix, clamping `retry:` to a ceiling, is not available: the spec says a client
"MUST respect the `retry` field, waiting the given number of milliseconds before attempting to reconnect",
and reconnecting sooner than a server asked for is also the wrong direction to err in, since `retry:` is how
an overloaded server asks for room. Both reference SDKs pass the value through untouched.

What the spec does allow is waiting longer. The `retry` field it points at is the one WHATWG HTML defines,
whose reconnection algorithm reads "Wait a delay equal to the reconnection time of the event source. Optionally,
wait some more." It also leaves reconnecting at all a SHOULD, which this client already declines once
`MAX_RECONNECTION_ATTEMPTS` is reached. Both fixes below sit inside that room; neither shortens a wait.

`await_response_after_disconnect` now carries a deadline, `max_reconnection_wait:` seconds
(`MAX_RECONNECTION_WAIT`, 300, the same budget as `SSE_LISTENER_READ_TIMEOUT`). Before each attempt it compares
the delay the server asked for against the remaining budget, and stops reconnecting when honoring it in full
would run past the deadline. The server's interval is therefore either waited out exactly or not acted on at all,
and the calling thread is released as soon as the answer is known. On the reported case, a day-long `retry:`,
the thread now returns without sleeping at all.

Whatever is left of the budget also becomes the resumed stream's read timeout, so the bound covers a server
that accepts the GET and then sends nothing. That GET previously relied on whatever the Faraday adapter
defaults to, which is 60 seconds for Net::HTTP but need not exist at all for a caller-supplied adapter.
`listen_for_server_requests` already guarded its own GET this way with `SSE_LISTENER_READ_TIMEOUT`.

The other path has the opposite problem. `listen_for_server_requests` treats a graceful close as success and
resets `consecutive_failures`, so `retry: 0` never reaches the attempt cap and the listening stream reconnects
in a tight loop. A `MIN_RECONNECTION_DELAY_MS` floor of 100ms stops that, and is the "optionally, wait some more"
case exactly. That path gets no deadline: it runs on a thread this client owns and is meant to poll indefinitely
(the spec asks clients to "poll" a closed stream by reconnecting), so a long `retry:` there idles the SDK's own
listener rather than the embedding application.

`DEFAULT_RECONNECTION_DELAY_MS` and `MAX_RECONNECTION_ATTEMPTS` are unchanged and still match the Python SDK.

## How Has This Been Tested?

New tests in `test/mcp/client/http_test.rb` cover a day-long `retry:` releasing the calling thread without
sleeping, a delay that fits the budget still being waited out in full and resuming normally, a caller-supplied
`max_reconnection_wait:` stopping the resume with a message naming the budget, and the argument validation.
Both reconnection paths are covered for the unusable values a server can send: `retry: 0` is raised to the floor
on the resumption path and on the listening stream, and negative or non-numeric values (`-5000`, `abc`, `1e6`, `500ms`)
fall back to the default delay, since the SSE parser accepts only a run of digits. The existing reconnection tests,
whose `retry:` values fit the default budget, are unaffected.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes. The conformance `sse-retry` scenario scores
`client-sse-retry-timing`, which checks the reconnect happens neither early nor very late against a 500ms `retry:`;
since no wait is ever shortened, that check is unaffected by the size of the value it uses.

## Breaking Changes

A request whose resumption cannot complete within `max_reconnection_wait:` (300 seconds by default) now fails instead of
waiting however long the server asked for. Servers asking for intervals that fit the budget are unaffected.
Pass a larger `max_reconnection_wait:` if you expect longer.
2026-08-11 05:29:48 +09:00
Koichi ITO
c40aa9cc59 Serve the subscriptions/listen notification stream per SEP-2575
## Motivation and Context

Companion to the stateless lifecycle work (SEP-2575, modelcontextprotocol/modelcontextprotocol#2575) for
the 2026-07-28 MCP spec release. The modern lifecycle removed the HTTP GET listening stream;
`subscriptions/listen` replaces it as a long-lived POST that opts in to server change notifications.
The Python SDK ships the server side of this as its SEP-2575 event-bus work (python-sdk PR /modelcontextprotocol/python-sdk#3035);
the TypeScript SDK landed it in PR modelcontextprotocol/typescript-sdk#2321.

Wire behavior, per the draft schema:

- The request carries a REQUIRED `notifications` filter (`SubscriptionFilter`): `toolsListChanged`,
  `promptsListChanged`, `resourcesListChanged`, and `resourceSubscriptions` (URI list, replacing
  the legacy `resources/subscribe` RPC). Every type is opt-in; the server MUST NOT send types
  the client did not request.
- The first stream message is `notifications/subscriptions/acknowledged`, reporting the subset of
  requested types the server agreed to honor. Honoring reads the capability FLAGS that promise delivery
  (`listChanged`, `subscribe`), the same derivation `server/discover` uses for its era-aware capability stripping;
  the mere presence of a primitive's capability is not enough.
- Every notification delivered on the stream carries the correlating `io.modelcontextprotocol/subscriptionId`
  (the listen request id) in `_meta`.
- A graceful teardown (transport `close`) sends a `SubscriptionsListenResult` response before closing the stream,
  stamped with the REQUIRED 2026-07-28 `resultType` at its construction site (it never passes through the dispatch path);
  an abrupt disconnect sends nothing.

Implementation:

- `StreamableHTTPTransport` intercepts `subscriptions/listen` on the modern path (after header and envelope validation)
  and serves it as a long-lived SSE stream, using the same register-and-return body proc pattern as the legacy GET stream.
  Subscriptions live in an in-process registry keyed by the listen request id; fan-out hooks into `send_notification` ahead of
  the legacy delivery, so a resource updated by one session's tool call also reaches modern subscribers.
  The matching snapshot is taken under the transport mutex, but stream writes happen outside it,
  matching the legacy delivery paths: a slow or stalled subscriber must not block the transport.
  Duplicate subscription ids close the new stream instead of double-registering.
- Concurrent listen streams are capped (`max_listen_subscriptions:`, default 1000, `nil` to opt out);
  a listen request past the cap is rejected with HTTP 503, like the `max_sessions` guard against session floods.
  Each stream holds an open connection for its lifetime, so without a bound an unauthenticated client can retain
  unbounded connections.
- Each stream is kept alive by an SSE comment frame written every `listen_keepalive_interval:` seconds
  (default 15, matching the TypeScript SDK; `nil` to opt out when an upstream proxy pings the stream).
  A silently dropped connection would otherwise hold its capped slot until the next fan-out write failed,
  so on a quiet server the cap would ratchet down permanently; the periodic write detects the dead peer
  and frees the slot. A comment frame cannot corrupt an interleaved notification's JSON, and the write
  happens outside the transport mutex, reusing the legacy GET stream's keepalive mechanism.
- Every SSE response now carries `x-accel-buffering: no`, which the spec asks of SSE streams and both
  reference SDKs send: a buffering reverse proxy would hold events back instead of delivering them as
  they are written, and on a listen stream it would also swallow the keepalive frames a dropped peer
  is detected by. The header rides the shared `SSE_HEADERS`, so the legacy streams gain it too.
- stdio does not serve the stream, matching the Python SDK's stream-pair behavior: no server handler is registered,
  so the method answers `-32601`.
- `Server#discover` becomes era-aware about notification delivery: `listChanged`/`subscribe` capability flags
  promise delivery over `subscriptions/listen` streams in the modern lifecycle, so they are stripped when
  the transport does not serve that RPC (the new `Transport#serves_subscriptions_listen?` seam, true for `StreamableHTTPTransport`).
- The conformance fixture defines the diagnostic triggers the `server-stateless` scenario calls
  (`test_trigger_tool_change` / `test_trigger_prompt_change`): each broadcasts its list-changed notification
  to the listen streams and returns, mirroring the suite's TypeScript reference fixture, which mutates nothing either.

Out of scope, noted for follow-ups: an external event bus for multi-worker deployments, and the client-side listen driver
(the Python reference is python-sdk PR modelcontextprotocol/python-sdk#3047).

Refs #389.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` cover:
the SSE response with the acknowledgement as the first event (including the honored-subset reduction for unsupported types and
for capability entries lacking the delivery flag), the `notifications` filter and envelope requirements (400 responses),
opt-in-only delivery with the correlating `subscriptionId`, URI-scoped `resources/updated` delivery, per-subscription ids across
concurrent streams, the graceful close result carrying `resultType: "complete"`, duplicate-id rejection, the 503 past
the concurrent stream cap, the keepalive (writing the comment frame outside the mutex, freeing a dead peer's slot,
no thread when the interval is `nil`, and the positive-or-nil interval validation), and `x-accel-buffering: no`
on both the listen stream and the legacy GET stream.
`test/mcp/server/transports/stdio_transport_test.rb` asserts `-32601` over stdio,
and `test/mcp/server_test.rb` covers the era-aware capability stripping in `server/discover` for both transport kinds.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

Against the conformance fixture server at `--spec-version 2026-07-28`, the `server-stateless` subscription checks
all report SUCCESS: the acknowledgement, `subscriptionId` tagging, and filter-containment MUSTs, plus both
list-changed SHOULD checks driven by the new trigger tools. The `--requirements 2025-11-25` server leg
passes 78/78, unchanged.

## Breaking Changes

None. The method was previously unhandled (`-32601` everywhere); the only observable change to existing responses is that
`server/discover` no longer advertises `listChanged`/`subscribe` flags on transports that cannot deliver those notifications in
the modern lifecycle, which `server/discover` has not shipped in a gem release with anyway.
2026-08-11 00:05:39 +09:00
Koichi ITO
f0c9665383
Merge pull request #498 from koic/mirror_x_mcp_header_params_into_headers
Mirror `x-mcp-header` tool parameters into `Mcp-Param-*` headers per SEP-2243
2026-08-10 12:20:19 +09:00
Koichi ITO
6dfef81a75
Merge pull request #496 from koic/request_state_security
Add opt-in `requestState` sealing via `RequestStateSecurity`
2026-08-10 12:19:56 +09:00
Koichi ITO
b98b783a5f
Merge pull request #489 from koic/enforce_modern_request_admission
Enforce the modern lifecycle admission rules per SEP-2575
2026-08-09 03:34:29 +09:00
Koichi ITO
5864b8431c Stamp the required cache hints on modern cacheable results per SEP-2549
## Motivation and Context

The 2026-07-28 spec revision makes the SEP-2549 `ttlMs` / `cacheScope` cache hints REQUIRED members of
the cacheable results (`tools/list`, `prompts/list`, `resources/list`, `resources/templates/list`,
and `resources/read`). The SDK's existing emission is opt-in (`Server.new(ttl_ms:, cache_scope:)`),
so servers that never opted in violate the 2026-07-28 wire schema, and the conformance suite fails
those scenarios on wire-schema validation (`ListToolsResult: must have required property 'cacheScope' / 'ttlMs'`)
plus all eight checks of the `caching` scenario.

The dispatch path now fills the hints centrally for results of requests carrying the SEP-2575 `_meta` envelope,
next to the SEP-2322 `resultType` stamp: a cacheable result that does not already carry both fields gets
the configured `ttl_ms` / `cache_scope` values, with `ttlMs: 0` (do not cache) and `cacheScope: "private"`
filling anything unset. Values already in the result win, preserving per-result overrides.
Only complete results are stamped: an SEP-2322 `input_required` round trip of `resources/read` is not
a cacheable final result and stays hint-free.

The unset-scope fill is `"private"` because the spec names no default scope and `"private"` is the side
that cannot leak a user-dependent `resources/read` result through a shared cache; it is also
the unconfigured default of the TypeScript SDK (`cacheScope: 'private'`), the Python SDK (`CacheHint.scope`),
and this SDK's own `server/discover`. The opt-in emission of `apply_cache_metadata` used to fill a missing
scope as `"public"` when only `ttl_ms` was configured and now fills `"private"` for the same reason,
so both paths agree. Stable protocol versions otherwise keep the opt-in emission unchanged.

## How Has This Been Tested?

`bundle exec rake test` passes with zero failures. New tests in `test/mcp/server_test.rb`: modern `tools/list`
and `resources/read` results carry the default hints, configured values win over the defaults,
non-cacheable modern results (`ping`) stay untouched, and legacy cacheable results keep the opt-in emission.
The opt-in emission tests assert the `"private"` fill for a configured `ttl_ms` without a scope.
The previously failing conformance scenarios (`tools-list`, `resources-read-text`, and `caching`) pass at
`--spec-version 2026-07-28` against the conformance fixture server, and the 2025-11-25 leg is unchanged.

## Breaking Changes

The modern-path emission is additive: it applies only to results of requests carrying the SEP-2575
modern `_meta` envelope. One deliberate change reaches stable versions: a server configured with
`ttl_ms:` but no `cache_scope:` now emits `cacheScope: "private"` instead of `"public"` on its opt-in results;
declaring `cache_scope: "public"` explicitly restores the shared-cacheable scope.
2026-08-09 01:25:08 +09:00
Koichi ITO
fee2710955
Merge pull request #493 from seunghan91/expose-server-context-in-instrumentation
Expose the user-defined server_context in instrumentation data
2026-08-09 01:10:36 +09:00
Koichi ITO
3511375204 Mirror x-mcp-header tool parameters into Mcp-Param-* headers per SEP-2243
## Motivation and Context

SEP-2243's custom-header half (MCP 2026-07-28) lets a tool annotate `inputSchema` properties with
`x-mcp-header` so intermediaries can route on argument values without parsing bodies: the client MUST
mirror each annotated argument of a `tools/call` into an `Mcp-Param-{Name}` header, encode values that
cannot ride as plain ASCII field values with the `=?base64?...?=` sentinel, and omit the header for
`null` or absent arguments. `MCP::Client::HTTP` sent only the standard `Mcp-Method`/`Mcp-Name` mirror
headers, so every `http-custom-headers` check of the 2026-07-28 conformance requirements fails.

The new `MCP::Client::McpParamHeaders` module ports the TypeScript SDK's `mcpParamHeaders` codec:

- `scan` walks a tool's `inputSchema` for declarations and validates every constraint the spec places
  on them: RFC 9110 token names, case-insensitive uniqueness, primitive-typed declaring properties
  (`number` is accepted alongside the spec's `string`/`integer`/`boolean` because the published
  referee annotates `type: "number"` parameters, the same accommodation the TypeScript SDK makes),
  and static reachability through a chain of `properties` keys only: an annotation under `items`,
  the combinators, or `$defs` invalidates the whole tool definition.
- `build` resolves each declaration's path in the call's `arguments`, omits `null`/absent and
  non-representable values (unsafe integers, non-finite floats, non-primitives), converts primitives
  per the spec's rules, and encodes with the sentinel exactly where a plain ASCII field value
  cannot carry the value (empty, edge whitespace, bytes outside visible ASCII, sentinel-shaped input).

`MCP::Client::HTTP` learns declarations from the `tools/list` responses passing through it (the same
source of truth the TypeScript SDK's response cache uses) and mirrors on each `tools/call` alongside
the existing `Mcp-Method`/`Mcp-Name` construction. Learning and mirroring exist on the modern
lifecycle only, matching both reference SDKs. An invalid tool definition mirrors nothing, per
the spec's guidance to send without custom headers when no reliable declarations are available;
a complete (uncursored, `nextCursor`-less) listing rebuilds the registry so declarations of
unlisted tools stop mirroring (the Python SDK's pruning), and the registry is capped
(`MAX_MCP_PARAM_TOOLS`, 1000) so a server rotating tool names cannot grow it without bound.

On the modern lifecycle, `MCP::Client#list_tools` and `#tools` also enforce the spec's MUST:
a tool definition whose `x-mcp-header` annotations violate the constraints is excluded from
the listing, with a warning naming the tool and the reason (the spec's SHOULD), so one malformed
definition does not block the valid tools - the same filtering the Python SDK's
`_absorb_tool_listing` and the TypeScript SDK's cached-listing finalize apply. A value that cannot
be represented as UTF-8 omits its header like the other non-representable values.
The README documents the mirroring and the exclusion under the lifecycle negotiation section.
The server-side validation half of the codec is a follow-up.

## How Has This Been Tested?

New `test/mcp/client/mcp_param_headers_test.rb` covers the scan constraint matrix (root and
non-reachable placements, empty/non-token/duplicate names, non-primitive types), the primitive
conversions (including `42.0` serializing as `42` and unsafe integers refusing), the encoding matrix
(plain pass-through, empty, non-ASCII, edge whitespace, CR/LF, sentinel-shaped input), and header
construction with nested paths and omitted values (including a value that cannot be represented
as UTF-8). `test/mcp/client/http_test.rb` drives the transport end to end over a modern connection:
a `tools/list` teaching the declarations, the following `tools/call` carrying the mirrored headers,
an invalid declaration mirroring nothing, a legacy connection learning nothing, and a complete
listing pruning the declarations of unlisted tools. `test/mcp/client_test.rb` covers the MUST-level
exclusion: the invalid definition dropped from `#tools` with the warning on a modern connection,
and listed unchanged on a legacy one. `bundle exec rake` is green.

## Breaking Changes

None. Requests to servers whose tools carry no `x-mcp-header` annotations are byte-for-byte unchanged,
and the new headers only appear for tools that declare them.
2026-08-08 20:58:35 +09:00
Koichi ITO
e6b5a9b5e3 Add opt-in requestState sealing via RequestStateSecurity
## Motivation and Context

The SEP-2322 `requestState` continuation string leaves the server, sits in the client's hands,
and comes back as client-controlled input. Without protection a client can read the server's continuation state,
tamper with it (for example forging an already-answered elicitation), or replay a state issued for one call against
another tool, other arguments, or another server. The multi-round-trip documentation of the Python SDK is explicit
that the echo must be treated as untrusted input; its high-level server seals the state by default via `RequestStateBoundary`.

New `MCP::Server::RequestStateSecurity` (OpenSSL standard library only) brings that protection to this SDK as an opt-in:

- `seal` encrypts the plaintext state with AES-256-GCM (clients cannot read it, not merely verify it) inside a claims
  envelope binding an expiry window (`ttl:`, default 300 seconds, re-sealed each round), the originating method and target
  (tool/prompt name or resource URI), a digest of the originating arguments (stringified and sorted recursively,
  so symbol/string parses of identical JSON digest identically), and an optional `audience:`. The token format is
  `v1.<base64url(iv || ciphertext || tag)>` with the version prefix bound as GCM associated data,
  following the Python SDK's `AESGCMRequestStateCodec`.
- `unseal` verifies every claim fail-closed and raises `InvalidStateError` on tampering, expiry, or any mismatch.

Passing an instance via `Server.new(request_state_security:)` makes the seal/unseal transparent: issuance seals
the `requestState` of an outgoing `input_required` result, and dispatch unseals the echoed token for `tools/call`,
`prompts/get`, and `resources/read` before any handler runs, so `server_context.request_state` always reads
the plaintext the handler wrote. A tampered, expired, or cross-call echo is rejected as `-32602`
with "Invalid or expired requestState", matching the Python SDK's frozen error.

Without the option the state crosses the wire exactly as the handler wrote it (the Python low-level Server behavior);
the README documents that this is then the handler author's responsibility, and that multi-process deployments
must share the key across workers.

The conformance fixture opts in with a random per-boot key, both to dogfood the feature and because
the tampered-state scenario of the 2026-07-28 conformance requirements retries an MRTR request with
a corrupted `requestState` and requires a JSON-RPC error; without integrity-checked state the fixture
cannot detect the corruption. Every MRTR round trip completes within one server process,
so no key persistence is needed. Sealing is transparent to the fixture tools, whose `requestState` plaintext
round-trips unchanged, and the new `test_input_required_result_tampered_state` tool is therefore
a plain MRTR elicitation flow; the tampered echo is rejected with `-32602` by the server-level unsealing
before dispatch ever reaches it.

Refs #382.

## How Has This Been Tested?

New `test/mcp/server/request_state_security_test.rb` covers constructor validation,
the seal/unseal round trip (opaque `v1.` token, plaintext not visible), expiry via time travel,
fail-closed rejection of method/target/digest/audience mismatches, tampered and malformed tokens,
and tokens sealed under a different key.

New tests in `test/mcp/server_test.rb` drive `Server#handle` with the modern envelope:
transparent sealing on issuance and plaintext restoration on the retry leg, `-32602` for
tampered echoes and for echoes replayed against different arguments, and the pass-through
default when `request_state_security:` is not set.

Against the fixture server at `--spec-version 2026-07-28` (run with `@modelcontextprotocol/conformance@alpha`;
the 2026-07-28 scenarios are not yet in a stable conformance release), `sep-2322-reject-tampered-state` reports SUCCESS,
and the other 13 `input-required-result-*` scenarios stay green with sealing active,
confirming that sealed states round-trip through the suite's retries without false rejections
(the seal binds `method`, target, and an arguments digest, and the suite echoes all three unchanged).
The `--requirements 2025-11-25` server leg still passes.

## Breaking Changes

None. The feature is opt-in via a new keyword argument that defaults to `nil`, in which case behavior is byte-identical to before.
2026-08-08 18:54:14 +09:00
Koichi ITO
633a5fa5ef Enforce the modern lifecycle admission rules per SEP-2575
## Motivation and Context

The 2026-07-28 conformance requirements reject two admission gaps in the modern (stateless) lifecycle
that the current implementation answers with the wrong signal:

- The RPCs the modern lifecycle removes (`initialize`, `ping`, `logging/setLevel`, `resources/subscribe`, `resources/unsubscribe`)
  were still dispatched, or answered incidental errors (`initialize` answered `-32022`, `resources/subscribe` a capability error);
  the requirement is `-32601` Method not found with HTTP 404.
- `server/discover` was fully envelope-exempt, while the requirements validate its envelope
  like every other modern request.

The per-request `_meta` validation itself (`-32602` naming the offending keys, optional `clientInfo`,
era classification on the reserved `protocolVersion` key alone) landed separately in #491;
this change builds on that shape and completes the admission rules:

- `Server#handle_request` rejects `Methods::MODERN_REMOVED_METHODS` on a modern-era session
  with `-32601` before the capability check, since the method does not exist in that era at all.
  The Streamable HTTP modern path maps `-32601` to 404 and `-32602` to 400 through its existing status ladder.
- The dual-era sniff treats an `initialize` carrying the modern envelope as modern traffic (a modern client naming a removed method)
  instead of the legacy-distinctive handshake, and `server/discover` keeps its envelope exemption outside the modern era only.
  The envelope-less rejection on a modern-locked session adopts #491's wire shape, `-32602` with the detailed message.

One deliberate divergence from the Python SDK: its dual-era stream loop answers an `initialize` on
a modern-locked connection with `-32022` carrying the supported-version list, while its HTTP path serves
the 404/-32601 shape. The conformance requirement phrases removed methods transport-independently,
so this SDK answers `-32601` on every transport, stdio included, for uniform era semantics.

The stdio era-lock tests used a modern `ping` as the era-distinctive request; they now use `tools/list`,
since `ping` no longer exists in the modern lifecycle.

## How Has This Been Tested?

`bundle exec rake test` passes with zero failures and RuboCop reports no offenses.
New and updated tests cover each admission rule on `Server#handle`, the Streamable HTTP modern path, and the stdio era lock
(all five removed methods per transport, the envelope requirement on `server/discover`, and the envelope-carrying `initialize` routing).

Against the conformance fixture server, every admission check of the `server-stateless` scenario passes at
`--spec-version 2026-07-28`: the per-request `_meta` validation, removed-method 404, discovery, capability,
and version-negotiation checks are all green, and the only remaining failures are the `subscriptions/listen`
checks that belong to separate work. The `--requirements 2025-11-25` server leg passes 78/78, unchanged.

## Breaking Changes

None for stable protocol versions: legacy requests are byte-for-byte unchanged, and a bare legacy `_meta`
(`progressToken`, trace context) keeps its legacy classification. Within the modern lifecycle,
previously incidental error shapes are replaced by the ones the 2026-07-28 conformance requirements mandate.
2026-08-08 18:51:53 +09:00
Koichi ITO
4fac357343
Merge pull request #497 from koic/pin_conformance_cli_to_the_alpha_dist_tag
Pin the conformance CLI to the `alpha` dist-tag
2026-08-08 18:51:25 +09:00
Koichi ITO
5932521552 Pin the conformance CLI to the alpha dist-tag
## Motivation and Context

The npm `latest` dist-tag of `@modelcontextprotocol/conformance` points at 0.1.16, the old 0.1 line,
while the 2026-07-28 requirement revisions and the frozen-requirements framework live in the 0.2.0 alpha line
(`alpha` currently resolves 0.2.0-alpha.11). The runners invoked the bare package name, so `rake conformance`
and the conformance CI job resolve whatever `latest` points at: a fresh machine silently downgrades to
the old suite while a warm npx cache may keep serving a newer one, and the suite actually in use depends
on the environment. Pinning the `alpha` dist-tag puts every run on the line the frozen conformance requirements
are anchored to (0.2.0-alpha.10, published 2026-07-27).

Running the real alpha suite surfaced the actual client-leg state, so the expected-failures baseline is
updated to match: `initialize` now passes (the harness accepts 2026-07-28, fulfilling the TODO on the old entry),
and the scenarios pending client-side work are recorded with their reasons: the 2026-07-28 stateless lifecycle
and the SEP-2322 MRTR driver, SEP-2243 custom-header mirroring, client-side JSON Schema preservation,
the DPoP and WIF authorization extensions, and one `auth/authorization-server-migration` check added to
the suite after the alpha.10 anchor.

The manual `npx` examples in `conformance/README.md` carry the same pin so local reproduction runs
the same suite as the rake task.

## How Has This Been Tested?

`npx --yes @modelcontextprotocol/conformance@alpha --version` resolves 0.2.0-alpha.11,
and `bundle exec rake conformance` passes the baseline check on both legs: the server leg reports 73 passed with 0 failed
and no expected failures, and the client leg fails exactly the scenarios the baseline records.

## Breaking Changes

None. The change is confined to the conformance tooling; the shipped gem is untouched.
2026-08-08 18:47:24 +09:00
Koichi ITO
05c3585bba
Merge pull request #491 from koic/align_modern_envelope_validation_with_final_spec
Align modern envelope validation with the finalized spec
2026-08-08 16:04:45 +09:00
Koichi ITO
f39b1bf4aa Align modern envelope validation with the finalized spec
## Motivation and Context

Two deviations from the finalized 2026-07-28 specification in the SEP-2575 envelope validation,
both introduced against the frozen SEP text and overtaken by post-final spec changes:

1. `clientInfo` was treated as required. Spec PR modelcontextprotocol/modelcontextprotocol#3002 made it
optional (clients SHOULD include it unless configured not to), and the TypeScript and Python SDKs validate only
the `protocolVersion` + `clientCapabilities` pair.
A conformant client configured not to identify itself was rejected.

2. A missing or mistyped envelope answered `-32600` Invalid Request.
The spec maps missing required envelope fields to `-32602` Invalid params, and both reference SDKs answer
with `-32602` naming the offending keys.

Fixing these also corrects the era classification to match the reference SDKs: a request claims
the modern lifecycle when `_meta` carries `io.modelcontextprotocol/protocolVersion`
(the TypeScript envelope claim and the Python `_has_modern_envelope` are both single-key checks),
and a claimed-but-incomplete envelope is now validated and rejected with `-32602` naming
the missing keys instead of silently flowing through the legacy path. Legacy `_meta` usage without
the claim key (`progressToken`, trace context) is classified exactly as before.

Unchanged on purpose: the era-lock violations keep their codes (`-32600` for a modern envelope on
a legacy-locked session, `-32022` for `initialize` on a modern-locked one), matching the Python SDK.

## How Has This Been Tested?

`test/mcp/request_envelope_test.rb` now covers: classification by the claim key alone,
a claimed-but-incomplete envelope staying modern, parsing without the optional `clientInfo`
(reader returns `nil`), `-32602` with the offending key names for a missing `clientCapabilities`
and for mistyped required and optional fields.

`test/mcp/server_test.rb` covers the dispatch-level behavior: a claimed
but incomplete envelope answers `-32602` naming the missing key, an envelope without `clientInfo` is
served with `server_context.client_info` reading `nil`, and a claim-less request on
a modern-locked session answers `-32602` naming the required keys.
The stdio and Streamable HTTP transport tests assert the new code on their envelope-requirement paths.

## Breaking Changes

None for conforming clients. Requests that were already rejected change error code
(`-32600` to `-32602`, HTTP status 400 unchanged), and requests carrying the `protocolVersion` claim key
with an incomplete envelope are now rejected as the spec mandates instead of being served as legacy requests.
Envelopes without `clientInfo`, previously rejected, now succeed.
2026-08-08 16:00:29 +09:00
Koichi ITO
b2f8070488
Merge pull request #494 from koic/derive_mcp_name_in_modern_test_requests
Derive `Mcp-Name` from the body in the modern transport test helper
2026-08-08 15:48:39 +09:00
Koichi ITO
90b8fd49c8 Derive Mcp-Name from the body in the modern transport test helper
## Motivation and Context

#490 and #492 merged independently green but broke each other on main: #492 made the modern path reject
a name-bearing POST whose body carries a target name without `Mcp-Name` (-32020, HTTP 400)
and taught the `modern_rack_request` helper to derive `Mcp-Method` from the body, while #490,
merged in between, added five modern `tools/call` tests that build their requests through that helper
and therefore send no `Mcp-Name`. Since the #492 merge every CI run on main fails those five tests
with 400 where 200 is expected; the library behavior itself is correct.

The helper now derives `Mcp-Name` the same way it derives `Mcp-Method`: from `params.name` or
`params.uri` when the body's method is one of the name-bearing three. That is what a conforming client sends per
the 2026-07-28 specification, and what the TypeScript SDK's client, the bundled `MCP::Client::HTTP`,
and the conformance harness's standard headers all do, so tests built through
the helper model a compliant client by default. `name_header: nil` omits the header for tests of
the requirement itself, symmetric with `method_header: nil`, and an explicit `headers:` entry still overrides
the derived value, which keeps the base64 mismatch tests exercising their divergent names.

## How Has This Been Tested?

The five failing tests pass again without being touched, and the #492 requirement tests
(missing `Mcp-Method`, missing `Mcp-Name`, header mismatches, base64 decoding) still pass:
the transport test file reports 217 runs with zero failures. `bundle exec rake` is green,
including RuboCop and the `--requirements 2025-11-25` conformance baseline.

## Breaking Changes

None. The change is confined to a test helper; the shipped gem is untouched.
2026-08-08 15:44:53 +09:00
Koichi ITO
b03da23dd3
Merge pull request #482 from koic/elicitation_enum_schema
Add `MCP::Elicitation::EnumSchema` builders for SEP-1330
2026-08-08 15:29:55 +09:00
Koichi ITO
2c3c3075b8
Merge pull request #492 from koic/require_mcp_method_header_on_the_modern_path
Require the `Mcp-Method` header on the modern path
2026-08-08 15:29:32 +09:00
Koichi ITO
02aed75882
Merge pull request #490 from koic/stream_modern_request_notifications
Stream modern request notifications and honor the envelope `logLevel` per SEP-2575
2026-08-08 15:25:04 +09:00
Koichi ITO
da2a7f80d7 Stream modern request notifications and honor the envelope logLevel per SEP-2575
## Motivation and Context

The modern (stateless) lifecycle of MCP 2026-07-28 serves each request as a self-contained exchange,
and two delivery requirements of that model were unimplemented:

- Notifications a handler emits while serving a modern request (progress, log messages)
  had nowhere to go: the modern path answered with a single JSON object,
  and the ephemeral per-request session degraded every notification to non-delivery.
  The conformance requirement expects them as frames on the request's own response stream
  (`tools-call-with-progress` fails with "No progress notifications received" at 2026-07-28).
- The envelope's `logLevel` member, which replaces the removed `logging/setLevel` RPC,
  was parsed but never applied: log delivery fell back to the server-wide level, violating the requirement
  that no `notifications/message` is sent for requests that did not set `_meta` `logLevel`.

The changes wire both up:

- `StreamableHTTPTransport#handle_modern` registers a per-request notification sink for its ephemeral session;
  `send_notification` routes into the sink ahead of the stateless guard.
  A request whose handler emitted notifications answers as an SSE stream carrying them ahead of the final response;
  a request that emitted none keeps the single JSON exchange and its HTTP status ladder.
- `Server#handle_request` applies the lifted envelope's `logLevel` to the session via the existing `configure_logging`,
  and on modern-era sessions `ServerSession#notify_log_message` no longer falls back to the server-wide level:
  without a per-request `logLevel` it stays silent, on every transport. An unrecognized level reads as absent,
  the safe direction, matching the Python SDK's `allowed_log_levels`.

The `server-stateless` scenario of the 2026-07-28 conformance requirements probes two stream-discipline
rules through diagnostic fixture tools the Ruby fixture did not define, so both checks failed as
not testable: `sep-2575-http-server-no-independent-requests-on-stream` calls `test_streaming_elicitation`
and requires that every frame on the request's response stream is a notification or the final response,
and `sep-2575-server-no-log-without-loglevel` calls `test_logging_tool` without an envelope `logLevel`
and requires that no `notifications/message` reaches the stream.

The fixture now defines both tools. `test_streaming_elicitation` reports progress and completes;
`test_logging_tool` calls `notify_log_message` unconditionally and relies on the SDK's per-request gate,
which drops the notification for modern requests that did not authorize logging through
`io.modelcontextprotocol/logLevel`. Both lean on the notification streaming this change adds:
with a `progressToken` or an authorizing `logLevel`, the notification is delivered as an SSE frame
ahead of the final response rather than being dropped.

One known limitation relative to the TypeScript and Python SDKs, which stream notifications live while the handler runs:
delivery here is buffered, flushing the frames after the handler returns. Ordering is preserved
and the conformance checks are satisfied, but long-running handlers get no real-time interleaving.
The sink is bounded (`MAX_MODERN_REQUEST_NOTIFICATIONS`, 1000): a handler emitting notifications
in proportion to client-supplied input cannot grow one request's memory without bound,
and past the cap the notify helpers report `false`, the same non-delivery degradation
they have on every other undeliverable path. Live streaming can follow without changing the wire shape.

## How Has This Been Tested?

`bundle exec rake test` passes with zero failures and RuboCop reports no offenses. New tests cover:
a modern `tools/call` streaming `notifications/progress` frames ahead of the result, the single JSON exchange staying
in place without notifications, log suppression without the envelope `logLevel`, log delivery with it,
the modern-era session ignoring the server-wide level while honoring a per-request one,
and the notification cap bounding one request's buffered frames while the notify helpers report `false` past it.

Against the conformance fixture server, the `tools-call-with-progress` progress check passes
at `--spec-version 2026-07-28` (its remaining wire-schema check belongs to the separate `resultType` change),
the stream-discipline checks `sep-2575-http-server-no-independent-requests-on-stream` and
`sep-2575-server-no-log-without-loglevel` report SUCCESS, and manual probes confirm the positive
directions the suite leaves untested: with `io.modelcontextprotocol/logLevel` in `_meta`,
`test_logging_tool` streams its `notifications/message` frame ahead of the result, and
with a `progressToken`, `test_streaming_elicitation` streams its `notifications/progress` frame.
The `--requirements 2025-11-25` server leg passes 78/78, unchanged.

## Breaking Changes

None for stable protocol versions: legacy requests and their notification delivery are unchanged.
Within the modern lifecycle, notifications become deliverable where they were previously dropped,
and log messages without a per-request `logLevel` stop leaking through the server-wide level,
as the specification requires.
2026-08-08 15:22:58 +09:00
Koichi ITO
8e30f325ce
Merge pull request #488 from koic/raise_resource_not_found_in_conformance_fixture
[Conformance] Raise `ResourceNotFoundError` for unknown resource URIs
2026-08-08 15:15:16 +09:00
Koichi ITO
29647deb0e
Merge pull request #487 from koic/stamp_result_type_on_modern_results
Stamp the required `resultType` on modern results per SEP-2322
2026-08-08 15:14:43 +09:00
Koichi ITO
14bf3a7091 Stamp the required resultType on modern results per SEP-2322
## Motivation and Context

SEP-2322 (merged for the 2026-07-28 spec release) makes `resultType` a REQUIRED member of every result
a 2026-07-28 server returns: "Servers implementing this protocol version MUST include this field",
with absence tolerated only when the result comes FROM an earlier protocol version.
The client-side vocabulary landed earlier (`MCP::ResultType`, treating an absent value as `"complete"`),
but every ordinary modern result the server returns is unstamped, which violates the MUST for `tools/list`,
`tools/call`, `ping`, and every other standard result on the modern wire.
The conformance suite's 2026-07-28 requirements fail each of those scenarios on wire-schema validation
(`CallToolResult: must have required property 'resultType'`).

The dispatch path now stamps `resultType: "complete"` centrally: any Hash result of a request carrying
the SEP-2575 `_meta` envelope that does not already carry a `resultType` gets the standard value merged in.
Results that already carry a discriminator keep it, notifications and cancellation-suppressed responses
are untouched, and legacy results stay unstamped because pre-2026 clients do not know the field.
`server/discover`, which is exempt from the `_meta` envelope (pre-version discovery),
stamps its `DiscoverResult` at its construction site instead.

## How Has This Been Tested?

`bundle exec rake test` passes with zero failures. New tests in `test/mcp/server_test.rb`: `tools/list`,
`ping`, and `tools/call` results carry `resultType: "complete"` on modern requests and no `resultType`
on legacy requests; `server/discover` carries the stamp. The conformance scenarios previously failing
on the missing property (`tools-call-simple-text`, `prompts-get-simple`, `completion-complete`, and
the other tools/prompts scenarios) pass at `--spec-version 2026-07-28` against the conformance fixture server.

## Breaking Changes

None. The stamp applies only to results of requests carrying the SEP-2575 modern `_meta` envelope;
results on stable protocol versions through 2025-11-25 are byte-for-byte unchanged.
2026-08-08 15:12:18 +09:00
Koichi ITO
e5ab590c05
Merge pull request #481 from koic/input_required_results
Let Handlers Return Multi Round-Trip `input_required` Results per SEP-2322
2026-08-08 15:09:55 +09:00
Koichi ITO
6e2b7a1971 Let Handlers Return Multi Round-Trip input_required Results per SEP-2322
## Motivation and Context

SEP-2322 (modelcontextprotocol/modelcontextprotocol#2322, merged for the 2026-07-28 MCP spec release)
replaces server-initiated JSON-RPC requests, which the stateless modern lifecycle (SEP-2575) forbids,
with multi round-trip results: a `tools/call`, `prompts/get`, or `resources/read` handler returns
`resultType: "input_required"` with `inputRequests` (server-assigned keys mapping to `elicitation/create`,
`sampling/createMessage`, or `roots/list` request shapes) and/or an opaque `requestState`,
and the client retries the ORIGINAL request with `inputResponses` under the same keys plus the echoed state.
The client-side recognition landed earlier (`MCP::ResultType`, `Client::InputRequiredError`);
this adds the server side, mirroring the Python SDK's low-level Server (python-sdk#2967/#2986)
and the TypeScript SDK's umbrella 2026-07-28 work.

- New `MCP::Server::InputRequiredResult` value object: construction validation
  (at least one of the two fields, embedded methods restricted to the three shapes), `to_h` wire serialization,
  and the capability mapping shared with the TypeScript SDK's `requiredClientCapabilitiesForInputRequest`
  (url-mode elicitation requires `elicitation.url`, form otherwise; sampling with `tools`/`toolChoice` requires
  `sampling.tools`; `roots/list` requires `roots`), including the 2025 back-compat rule that a bare `elicitation: {}`
  declaration implies form support.
- Handlers return the object through the existing paths: both branches of `call_tool_with_args` and
  `call_prompt_template_with_args` pass it through instead of calling `.to_h`, `call_tool` skips
  output schema validation and the structured-content fallback for it (output schema validation would otherwise
  run against a `nil` `structuredContent`), and the `resources/read` dispatch skips the `contents` wrapping and
  SEP-2549 cache-hint stamping.
- One central hook in the dispatch lambda gates and serializes the result, after the cancellation check
  so cancelled requests stay suppressed: a legacy request (no SEP-2575 envelope) gets an internal error,
  because pre-2026 clients treat an unknown `resultType` as a final result; embedded requests exceeding
  the request's declared client capabilities get `-32021` with the full merged `requiredCapabilities` set.
- `MCP::ServerContext` gains `input_responses`, `request_state`, and the key-tolerant `input_response(key)` reader.
  The retry fields are params-top-level siblings of `name`/`arguments`/`uri` (not `_meta`),
  so only handlers that opt in to `server_context:` can participate, matching the envelope readers' access model.
  The server holds no memory between rounds: handlers re-run from the start on every retry
  (deterministic replay, as in the Python SDK).

The 2026-07-28 conformance requirements score 14 `input-required-result-*` scenarios and the capability
checks of `server-stateless`, and each drives a diagnostic fixture tool the server under test must define.
The fixture defines the tools those scenarios call, mirroring the suite's TypeScript reference fixture
(`examples/servers/typescript/everything-server.ts`) in tool names and `inputRequests` keys:

- `test_input_required_result_elicitation` / `_sampling` / `_list_roots`: one embedded request each,
  answered on the retry round (also exercised by the missing-response, result-type, ignore-extra-params,
  and validate-input scenarios)
- `test_input_required_result_request_state`: stamps an opaque `requestState` and completes only after
  it round-trips
- `test_input_required_result_multiple_inputs`: all three embeddable methods in one result
- `test_input_required_result_multi_round`: two elicitation rounds with per-round `requestState`
- `test_input_required_result_capabilities`: builds `inputRequests` from the declared client capabilities,
  so a sampling-only client is never asked to elicit
- prompt `test_input_required_result_prompt`: the non-tool MRTR flow over `prompts/get`
- `test_missing_capability`: guards on `require_client_capability!(:sampling)`, giving
  the `server-stateless` capability checks a target that answers -32021 with HTTP 400

`test_input_required_result_tampered_state` is deliberately absent: rejecting a tampered `requestState` needs
the sealing machinery of the request-state security change, and its fixture tool lands there.
Sealing of the echoed `requestState` (it arrives as client-controlled input) and the client-side auto-fulfillment loop
follow in the next changes.

Refs #382.

## How Has This Been Tested?

New `test/mcp/server/input_required_result_test.rb` covers construction validation, key normalization and freezing,
the wire shape of `to_h`, the full capability mapping, missing-capability subtraction with symbol/string declarations,
and the implied-form back-compat rule.

New tests in `test/mcp/server_test.rb` drive `Server#handle` with the modern envelope: issuance wire shape for all three methods,
the retry leg exposing `input_responses`/`request_state`/ `input_response(key)` to the handler, the legacy-request internal error,
`-32021` with the merged `requiredCapabilities` data, output-schema validation bypass under `validate_tool_call_results: true`,
and `resources/read` results staying unwrapped without `ttlMs`/`cacheScope` stamping even when the server configures cache hints.

Against the fixture server at `--spec-version 2026-07-28`, all SEP-2322 checks of the 13 covered scenarios pass,
and `server-stateless` reports `sep-2575-server-rejects-undeclared-capability` and
`sep-2575-missing-capability-http-400` as SUCCESS. The `wire-schema-valid` failures on rounds that reach
a complete result come from the missing `resultType` stamp, which is the separate stamping change's job.
The `--requirements 2025-11-25` server leg still passes 78/78, and `bundle exec rake` is green.

## Breaking Changes

None. The serialization seams only branch on a return type that previously could not occur, all new keyword arguments default to `nil`,
and requests that carry no `inputResponses`/`requestState` behave exactly as before.
2026-08-08 15:07:16 +09:00
Koichi ITO
4ed461c72f
Merge pull request #480 from koic/discover_finalize_and_client
Finalize `server/discover` and Add Client Modern Lifecycle Support per SEP-2575
2026-08-08 15:04:54 +09:00
seunghan Kim
14e02da475 Expose the user-defined server_context in instrumentation data
APM integrations need to tag a span with the subject of the request, but the
user-defined `server_context` hash passed to `Server.new` never reaches
`around_request` or `instrumentation_callback`. The exception reporter's
`server_context` argument is a different value — it describes where a failure
occurred (`{ request: ... }`, `{ notification: ... }`), not who made the call —
so there is currently no way to read the request subject from a hook.

Add `Configuration#instrument_server_context`, off by default. When enabled,
`instrument_call` puts the host's `server_context` into the instrumentation data
before invoking `around_request`, so it is readable both before and after
`request_handler.call`.

The flag is opt-in rather than unconditional because the hash is
application-supplied and may hold values a tracing backend should not receive.
Hosts that do not expose a `server_context` reader are unaffected.

`instrument_call` reads it through `self.server_context`: the existing
`server_context:` keyword shadows the reader, and the value wanted here is the
user-defined hash, not the reporter context.

Follows the same shape as the earlier additions of `tool_arguments` (#218) and
`client` (#221) to this hash.
2026-08-08 08:33:07 +09:00
Koichi ITO
9a62b9ae4f
Suppress RuboCop extension suggestions (#484)
This PR suppresses the following information:

```console
$ bundle exec rubocop
(snip)

Tip: Based on detected gems, the following RuboCop extension libraries might be helpful:
  * rubocop-i18n (https://rubygems.org/gems/rubocop-i18n)

You can opt out of this message by adding the following to your config
(see https://docs.rubocop.org/rubocop/plugins.html#plugin-suggestions for more options):
  AllCops:
    SuggestExtensions: false
```

There's no need to introduce a third-party RuboCop extension unless there's a specific need.
2026-08-07 18:46:46 -04:00
Koichi ITO
5f3a131e1a Require the Mcp-Method header on the modern path
## Motivation and Context

The modern Streamable HTTP path validated the SEP-2243 mirror headers only when present:
an absent `Mcp-Method` or `Mcp-Name` was silently tolerated. The 2026-07-28 specification
requires `Mcp-Method` on every request and `Mcp-Name` on `tools/call`, `resources/read`,
and `prompts/get`, and lists a missing required standard header among the validation failures
a server MUST reject; the TypeScript SDK enforces presence with `-32020` the same way.
Tolerating absence also defeats the headers' purpose silently: they exist so intermediaries
can route and inspect requests without parsing bodies.

A modern POST without `Mcp-Method`, or a name-bearing modern POST whose body carries
a target name without `Mcp-Name`, now answers HTTP 400 with `-32020` naming the missing header,
exactly like a mismatch. `Mcp-Name` stays unrequired when the body carries no target name,
matching the TypeScript SDK. The bundled `MCP::Client::HTTP` already sends both headers on
every modern request, so SDK-to-SDK traffic is unaffected.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` cover
the missing `Mcp-Method` and missing `Mcp-Name` rejections, asserting the `-32020` code
and the header name in the message. The `modern_rack_request` helper now mirrors
a conforming client by deriving `Mcp-Method` from the body (with `method_header: nil` to omit it),
so the existing modern-path tests exercise the requirement on every request.

## Breaking Changes

None for conforming clients, which must already send these headers.
Hand-rolled modern clients that omitted them are now rejected with `-32020` instead of being served;
add the headers, or use the legacy lifecycle, to proceed.
2026-08-08 03:56:06 +09:00
Koichi ITO
d0d7308a89 Finalize server/discover and Add Client Modern Lifecycle Support per SEP-2575
## Motivation and Context

Final step of the stateless lifecycle (SEP-2575, modelcontextprotocol/modelcontextprotocol#2575) for
the 2026-07-28 MCP spec release, now that the server core and both server transports can serve modern traffic.

Server side, `Server#discover` reaches its spec-final shape:

- `supportedVersions` advertises modern versions only, matching the TypeScript and Python SDKs:
  legacy versions are negotiated via `initialize`, not selected from discovery. This also closes
  an interop hazard of the interim response: auto-negotiating TS and Python clients treat
  any `DiscoverResult` as proof of a modern server and do not fall back to `initialize`,
  so advertising only legacy versions made them fail outright.
- The `ttlMs`/`cacheScope` cache hints are REQUIRED on `DiscoverResult` (unlike the opt-in SEP-2549 hints
  on list and read results), so the spec defaults (`0`, `"private"`) fill in when the server was not configured with
  `ttl_ms`/`cache_scope`, and the configured SEP-2549 values are reused otherwise.
- The server identity rides in the result `_meta` as the optional `io.modelcontextprotocol/serverInfo` stamp
  instead of a top-level `serverInfo` field, following spec PR modelcontextprotocol/modelcontextprotocol#3002
  (the TypeScript SDK stamps `_meta` the same way and the Python `DiscoverResult` carries no top-level
  `serverInfo`, so the top-level placement was invisible to both). `Client#discover` and
  the `server_implementation` reader read the `_meta` stamp with a top-level fallback for servers built
  against the frozen SEP text, and the key is exposed as `RequestEnvelope::SERVER_INFO_META_KEY`.

Client side, both bundled transports learn the modern lifecycle, and `MCP::Client` negotiates it automatically by default:

- `MCP::Client#discover` sends `server/discover` and returns a `DiscoverResult` struct
  (`supported_versions`, `capabilities`, `server_info`, `instructions`, `ttl_ms`, `cache_scope`).
  It works before `connect`; the stdio transport's connect guard exempts `server/discover`
  and spawns the subprocess on demand.
- `connect` gains `mode:` and defaults to automatic negotiation, joining the Python, Go, and C# SDKs
  (the TypeScript SDK keeps a legacy default): transports whose `connect` declares `mode:`
  (the bundled HTTP and stdio transports) receive `:auto`, which probes `server/discover`
  and falls back to the legacy handshake on any discovery failure, including a successful discovery
  without a mutually supported modern version (rollout tolerance for servers that answer discovery
  while only serving legacy versions). Custom transports whose `connect` does not declare `mode:`
  keep receiving the historical legacy call shape, detected by keyword introspection;
  a bare `**kwargs` deliberately does not count, so wrappers and test doubles that absorb arbitrary keywords
  stay on the legacy shape. An explicit `:modern`/`:auto` against such a transport raises `ArgumentError`
  instead of silently downgrading.
- The mode vocabulary is `:legacy`/`:auto` (shared with the Python and TypeScript SDKs) plus an explicit `:modern`,
  instead of folding a version-string pin into `mode` as Python and TypeScript do: this client has carried
  the scalar `protocol_version:` keyword since the handshake landed, so a second version-bearing input would make
  the API ambiguous about which one wins. `mode:` stays the strategy and `protocol_version:` stays the version,
  the same orthogonal split as the Go and C# scalar version pins; Python's `mode="2026-07-28"` is expressed here
  as `mode: :modern` with `protocol_version: "2026-07-28"`.
- An explicit legacy-generation `protocol_version` (e.g. `"2025-11-25"`) pins the legacy handshake without a probe,
  so an explicitly requested version is never overridden by the default negotiation adopting the modern lifecycle.
  `mode: :legacy` forces the classic handshake unconditionally; prefer it for spawn-per-invocation CLI tools
  and when using server-initiated requests, which exist only on the legacy lifecycle.
- Because the raw `connect` return value and `server_info` mirror the wire result, their shape depends
  on the negotiated era (`InitializeResult` vs `DiscoverResult`). New era-independent readers absorb that difference:
  `MCP::Client#protocol_version` (negotiated or adopted version; backed by a new stdio transport reader and the existing HTTP one),
  `#server_capabilities`, `#instructions`, and `#server_implementation`, which reads the spec-final `_meta`
  `io.modelcontextprotocol/serverInfo` stamp with a top-level fallback and returns `nil` when a modern server
  does not identify itself. `server_info` remains the permanent raw window to everything the readers do not cover.
- The stdio `server/discover` probe is bounded by a new `DEFAULT_DISCOVER_PROBE_TIMEOUT` (5 seconds, matching the C# SDK)
  when no `read_timeout` was configured: a compliant legacy server answers the probe with `-32601` immediately,
  but a non-compliant one that silently drops unknown methods must read as legacy evidence for the auto fallback
  instead of blocking `connect` forever. Regular requests keep the unbounded default.
- In modern mode, the new shared `MCP::Client::ModernEnvelope` stamps the SEP-2575 `_meta` triple onto
  every request (never onto notifications, whose `_meta` carries no envelope), reusing the reserved key names
  from `MCP::RequestEnvelope`. The HTTP transport sends the matching `MCP-Protocol-Version` header and
  keeps the existing `Mcp-Method`/`Mcp-Name` mirror headers; no `Mcp-Session-Id` is ever attached because `initialize`
  is never sent.
- The conformance client pins `mode: :legacy`: the referee validates the legacy `initialize` handshake
  and its scenario servers do not expect a preceding probe.

Resolves #389.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb` pin the required cache hints (spec defaults and configured SEP-2549 values);
the existing discover assertions across `server_test.rb` and both transport test files were updated to
the modern-only `supportedVersions`.

New tests in `test/mcp/client_test.rb` cover the `DiscoverResult` struct mapping, `ValidationError`/`ServerError`
on malformed and error responses, and the mode resolution contract: the `:auto` default on transports declaring `mode:`,
the unchanged legacy call shape for transports without it, the legacy pin for an explicit stable `protocol_version`,
`ArgumentError` for explicit non-legacy modes on transports without `mode:`, unknown-mode rejection,
and the era-independent readers against legacy results, modern results, the `_meta` `serverInfo` stamp, and absence.

New tests in `test/mcp/client/http_test.rb` cover modern adoption via discovery, envelope stamping with
the matching header on subsequent requests, the no-mutual-version failure, both auto-mode fallbacks,
and argument validation. New tests in `test/mcp/client/stdio_test.rb` cover pre-connect `server/discover`,
modern adoption with envelope stamping and no `initialize` frame, the auto-mode fallback, the probe timeout
default applying only while probing, and the fallback when a server never answers the probe.

## Breaking Changes

`server/discover` responses change shape (modern-only `supportedVersions` plus the required `ttlMs`/`cacheScope`);
this method has not shipped in a gem release yet, so no released behavior changes.

On the bundled HTTP and stdio transports, `MCP::Client#connect` without `mode:` now probes `server/discover` before
the legacy handshake: against legacy servers this adds one round trip and an unknown-method entry in their logs with
an unchanged final result, and once a server serves the modern lifecycle the connection adopts it, changing
the raw result shape from `InitializeResult` to `DiscoverResult`. Pass `mode: :legacy` or an explicit legacy-generation
`protocol_version` to keep the previous behavior unconditionally, or use the era-independent readers, which are stable
across both lifecycles. Custom transports without `mode:` and direct `transport.connect` calls are unaffected.
2026-08-08 03:45:00 +09:00
Koichi ITO
ff48f5c6dd [Conformance] Raise ResourceNotFoundError for unknown resource URIs
## Motivation and Context

Per SEP-2164, a `resources/read` request for a nonexistent resource answers with JSON-RPC error -32602 carrying
the requested URI in `error.data`, and MUST NOT return an empty `contents` array. The SDK supports this via
`MCP::Server::ResourceNotFoundError` (#402), but the conformance fixture's `resources_read_handler` returned
an empty array for unknown URIs, so the `sep-2164-resource-not-found` scenario of the 2026-07-28 conformance
requirements fails on the fixture ("Server returned a result with an empty contents array").

The gap never surfaced before because the scenario is part of the 2026-07-28 requirement set only;
the 2025-11-25 suite the fixture has been passing does not run it. The fixture now raises `ResourceNotFoundError`,
which is also the documented pattern for `resources_read_handler` users.

## How Has This Been Tested?

- `sep-2164-resource-not-found` passes 4/4 checks at `--spec-version 2026-07-28` against the fixture server.
- The `--requirements 2025-11-25` server leg passes 78/78, and each resources scenario reports no change,
  so known URIs are unaffected.
- RuboCop reports no offenses on the changed file.

## Breaking Changes

None. The change is confined to the conformance fixture; the shipped gem is untouched.
2026-08-08 01:45:01 +09:00
Koichi ITO
2d8210f411
Merge pull request #486 from jj-ivx/sanitize-tool-error-messages
fix: stop leaking exception messages to clients via JSON-RPC error data
2026-08-07 12:04:02 +09:00
Joshua J
f379e13b47
fix: stop leaking exception messages to clients via JSON-RPC error data
Tool handler exceptions and anything reaching JsonRpcHandler's blind
rescue had their #message echoed into the error data member, exposing
internals to untrusted clients (CWE-209). Capability errors keep their
client-facing message by re-raising through RequestHandlerError, the
one channel whose message is deliberately surfaced.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-06 18:28:17 +02:00
Koichi ITO
b54eebac75 Add MCP::Elicitation::EnumSchema builders for SEP-1330
## Motivation and Context

MCP 2025-11-25 (SEP-1330) replaces the ad-hoc `enumNames` convention with four standards-based enum schema variants
for elicitation requests: titled/untitled single-select and titled/untitled multi-select. The TypeScript SDK ships
typed Zod definitions for each shape (`packages/core/src/types/schemas.ts`), and the Python SDK relies on hand-built
schemas with the same shapes in its conformance fixtures.

Adds builder class methods on `MCP::Elicitation::EnumSchema` that produce the canonical JSON-Schema shapes for each variant,
plus a `legacy_titled` builder retained for backward compatibility with clients that have not yet migrated.
Each constructor returns an `EnumSchema` instance whose `to_h` produces the property-value Hash to pass through
`requested_schema:` on `ServerSession#create_form_elicitation`.

Each builder maps one-to-one to the spec's schema type names in `schema/2025-11-25/schema.ts`,
which the TypeScript and Python SDKs also carry verbatim in their type layers:

| Spec type (schema.ts)                             | Builder                                         |
|---------------------------------------------------|-------------------------------------------------|
| `UntitledSingleSelectEnumSchema`                  | `untitled_single_select`                        |
| `TitledSingleSelectEnumSchema`                    | `titled_single_select`                          |
| `UntitledMultiSelectEnumSchema`                   | `untitled_multi_select`                         |
| `TitledMultiSelectEnumSchema`                     | `titled_multi_select`                           |
| `LegacyTitledEnumSchema` (deprecated in the spec) | `legacy_titled`                                 |
| `EnumSchema` (the union of all five)              | the `MCP::Elicitation::EnumSchema` class itself |

These shapes stay relevant on the stateless 2026-07-28 lifecycle: elicitation is not deprecated by SEP-2577
and reaches modern clients as `elicitation/create` requests embedded in SEP-2322 `input_required` results,
whose `requestedSchema` uses the same variants. The README documents that pairing; the example references
`MCP::Server::InputRequiredResult`, so this change should merge after the SEP-2322 server-side PR.

The conformance server now builds the enum schemas of its `test_elicitation_sep1330_enums` tool
(and the `status` enum of the SEP-1034 defaults tool) through these builders instead of hand-written hashes,
so the conformance run exercises the exact schemas the SDK produces for users.

## How Has This Been Tested?

`test/mcp/elicitation/enum_schema_test.rb` covers each of the five shapes with happy-path emission,
`default` propagation, `title` / `description` propagation, and the four ArgumentError cases
(empty values, missing `:value`, missing `:title`, mismatched `value_titles` length). Two additional regression tests
assert that empty-but-non-nil defaults survive `to_h`:

- `EnumSchema.untitled_single_select(default: "")` keeps the empty string in the emitted Hash
- `EnumSchema.untitled_multi_select(default: [])` keeps the empty array in the emitted Hash

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes; the `elicitation-sep1330-enums`
and `elicitation-sep1034-defaults` conformance scenarios pass with the builder-produced schemas,
confirming they emit the same wire shapes as the previous hand-written hashes.

## Breaking Changes

None. The change is purely additive: new module `MCP::Elicitation::EnumSchema` with new class methods.
Existing callers of `ServerSession#create_form_elicitation` that pass raw hashes continue to work unchanged.
2026-08-05 12:26:13 +09:00
Koichi ITO
d51d4a0f91
Merge pull request #479 from koic/http_modern_path
Serve the Sessionless Modern Path over Streamable HTTP per SEP-2575
2026-08-04 00:26:12 +09:00
Koichi ITO
58f6a1bda0
Merge pull request #478 from koic/stdio_era_lock
Serve both lifecycle eras over stdio with an era lock per SEP-2575
2026-08-04 00:25:52 +09:00
Koichi ITO
80efdc7d02
Merge pull request #406 from atesgoral/issue-390-deprecations
Deprecate roots, sampling, and logging per SEP-2577
2026-08-04 00:25:33 +09:00
Ates Goral
6a43d3d6fb feat: deprecate roots sampling and logging
Warn when Roots, Sampling, or Logging APIs are used with MCP protocol version 2026-07-28 or newer.

Add a shared protocol deprecation helper, YARD deprecation notes, and regression tests covering warnings at and after the deprecation threshold and no warnings for older or never-established protocol versions.

Closes https://github.com/modelcontextprotocol/ruby-sdk/issues/390

Co-authored-by: Qlaw <noreply@qlaw.quick.shopify.io>
2026-08-02 13:13:10 -04:00
Koichi ITO
e591cbb804 Serve the Sessionless Modern Path over Streamable HTTP per SEP-2575
## Motivation and Context

Fourth step of the stateless lifecycle (SEP-2575, modelcontextprotocol/modelcontextprotocol#2575)
for the 2026-07-28 MCP spec release. `StreamableHTTPTransport` now routes header-first,
like the Python SDK's streamable HTTP manager: an `MCP-Protocol-Version` header naming a version outside
every supported list enters a new sessionless modern path, while requests without the header (or with
a stable-only version) take the existing paths untouched. Routing unknown versions to the modern path
means an unknown future version receives the spec-mandated `-32022` with `data: { supported:, requested: }`
instead of a generic invalid-request error.

Since 2026-07-28 became the latest stable protocol version, it serves both lifecycles of the dual-era model,
and the header value alone can no longer decide the era. For a dual-era header the routing disambiguates
by request shape: an `Mcp-Session-Id` binds the request to an established legacy session
(POST requests, the GET SSE stream, and DELETE termination keep working), and a sessionless POST
whose body is `initialize` is the legacy-distinctive handshake, so a client negotiating 2026-07-28 over
the classic handshake connects unchanged. Everything else under a dual-era header is sessionless modern traffic
(`server/discover`, envelope-carrying requests, and envelope-missing requests that get the modern path's error shape).
The era sniff reads the body once, bounded by `max_request_bytes`, and hands the string to whichever path serves the request,
since Rack 3 inputs need not be rewindable.

The modern path (`handle_modern`) is a single POST/JSON exchange:

- GET (the removed listening stream, replaced by `subscriptions/listen`) and DELETE (no sessions to terminate) return 405.
- It never consults `@stateless`, `@sessions`, or `@enable_json_response`, never issues an `Mcp-Session-Id`,
  and rejects requests carrying one with HTTP 400.
- Its body read is bounded by `max_request_bytes` (HTTP 413), like the legacy POST path.
- Header/body match rules surface as `-32020 HEADER_MISMATCH` (HTTP 400): the header version against
  the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers against the body when sent.
  `Mcp-Name` decoding mirrors the client transport's `=?base64?...?=` sentinel for values that are not header-safe ASCII.
- HTTP statuses follow the Python SDK's ladder: `-32020`/`-32021`/ `-32022` and the generic parse/invalid codes map to 400,
  `-32601` maps to 404 (disambiguating an unknown method from a legacy HTTP+SSE 404), and everything else
  including internal errors stays 200.
- Dispatch runs against an ephemeral per-request `ServerSession` locked to `era: :modern`,
  whose fresh unregistered `session_id` makes notification delivery degrade gracefully instead of
  broadcasting to unrelated legacy sessions through the broadcast branch of `send_notification`.

The legacy POST path gains one load-bearing guard for bodies carrying the modern `_meta` triple,
which would previously fall through the legacy path via the header default. Session-bound under
a dual-era header, such a request is a lifecycle violation, rejected as `-32600` because
the session already negotiated the legacy lifecycle (mirroring the stdio era lock).
With the header missing or naming a stable-only version, it violates the header/body match
requirement and is rejected as a header mismatch (`-32020`).

Intentional behavior changes for previously-erroneous requests, all following from header-primary routing:
an unknown header version now yields `-32022` with data instead of the legacy `-32600` message
(`initialize` included, which legacy-wise ignored the header), and GET/DELETE with an unknown header version,
or with a dual-era header and no session, yield 405 instead of 400. An empty header value stays malformed
on the legacy path. Existing tests were updated to codify these.

Refs #389.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` cover:
the sessionless 200 exchange without `Mcp-Session-Id`, `-32022` with the supported list
for unknown header versions, `-32020` for header/body version, `Mcp-Method`,
and base64-encoded `Mcp-Name` mismatches, the `Mcp-Session-Id` rejection,
405 for modern GET/DELETE, 404/`-32601` for unknown methods, the envelope requirement (`-32600`),
`-32021` with `requiredCapabilities` from a handler capability guard, `server/discover` without
an envelope, and the legacy-path sniff for modern-envelope bodies without the modern header.

Dual-era routing tests: a sessionless `initialize` with the 2026-07-28 header stays legacy
and negotiates 2026-07-28, session-bound POST and DELETE with that header stay on the legacy path,
a session-bound POST carrying the modern envelope is rejected as `-32600`,
and an oversized modern POST returns 413.

## Breaking Changes

None for conforming clients: requests without the header or with a stable-only version
are byte-identical to before, and legacy clients negotiating 2026-07-28 over
the classic handshake connect unchanged. Requests that were already rejected change error shape
(see intentional behavior changes above) to the forms the 2026-07-28 spec mandates.
2026-08-03 01:57:10 +09:00
Koichi ITO
09545f1272 Serve both lifecycle eras over stdio with an era lock per SEP-2575
## Motivation and Context

Third step of the stateless lifecycle (SEP-2575, modelcontextprotocol/modelcontextprotocol#2575) for
the 2026-07-28 MCP spec release. `StdioTransport` now serves the legacy handshake lifecycle
and the modern per-request-envelope lifecycle on one connection, with the same era-lock semantics as
the TypeScript and Python SDKs: the first era-distinctive message to SUCCEED locks the connection era
for its lifetime.

- Each stdin frame is parsed once (`symbolize_names: true`) so era classification can inspect its method
  and `_meta`. Frames that are not JSON objects fall back to `ServerSession#handle_json`,
  keeping protocol-level error responses byte-identical.
- A successful `initialize` locks `:legacy` (already a side effect of `ServerSession#mark_initialized!`).
  A successful `server/discover` or a successful request carrying the full modern `_meta` triple locks `:modern`.
  Failed era-distinctive messages (for example an unsupported envelope version) leave the connection unlocked,
  so a client probe can still fall back to the other era.
- Era violations are rejected in-band by `Server#lift_request_envelope`, which now also covers the legacy side:
  a modern envelope arriving on a legacy-locked session is an invalid request (`-32600`), mirroring
  the existing modern-side rules (`initialize` after a modern lock is `-32022`; a missing envelope after
  a modern lock is `-32600`).
- `StdioTransport#send_request` raises on a modern-locked session: the modern lifecycle forbids
  server-initiated JSON-RPC requests, which multi round-trip `input_required` results (SEP-2322) replace.
  The inline read loop inside `send_request` dispatches through the same era-aware path as the main loop.

Refs #389.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/stdio_transport_test.rb` drive full stdin/stdout round trips:
legacy lock via `initialize` then rejection of a modern envelope, modern lock via `server/discover`
then `-32022` (with `data.supported`) for a late `initialize`, modern lock via an envelope-carrying request,
no lock when the probe fails with an unsupported version (a legacy `initialize` still succeeds afterwards),
the envelope requirement after a modern lock, and the `send_request` prohibition on modern sessions.

`bundle exec rake` (tests, RuboCop, and conformance baseline, including the stdio conformance scenarios) passes.

## Breaking Changes

None. Legacy clients send `initialize` first and take the same code path as before;
the era lock only constrains message sequences that mix lifecycles on one connection,
which no legacy client produces.
2026-08-03 01:54:06 +09:00
Koichi ITO
f4d939d349
Merge pull request #475 from koic/server_modern_core
Handle the SEP-2575 Modern Request Envelope in the Server Core
2026-08-03 00:29:31 +09:00
Koichi ITO
72a929bbc0
Merge pull request #477 from koic/release_1_1_0
Release 1.1.0
2026-08-02 00:36:07 +09:00
Koichi ITO
1fa8673a58 Release 1.1.0
This release primarily addresses https://github.com/modelcontextprotocol/ruby-sdk/issues/474.
Work on full support for the 2026-07-28 specification, including stateless mode, is ongoing
and will continue in future releases.
2026-08-01 11:29:49 +09:00
Koichi ITO
d20eac0a4b
Merge pull request #476 from koic/support_2026_07_28_as_latest_protocol_version
Support 2026-07-28 as the Latest Protocol Version
2026-08-01 11:06:39 +09:00
Koichi ITO
ba88d9fbfd
Merge pull request #473 from koic/fix_docs_theme_stylesheet_fouc
Fix flash of unstyled content when loading the docs site
2026-08-01 11:05:54 +09:00
Koichi ITO
dc25610162 Support 2026-07-28 as the Latest Protocol Version
## Motivation and Context

Clients that require MCP 2026-07-28, such as ChatGPT, reject connections because the SDK
does not advertise that version: `Server#init` answers a 2026-07-28 request with 2025-11-25,
the Streamable HTTP transport 400s an `MCP-Protocol-Version: 2026-07-28` header,
and `server/discover` omits the version from `supportedVersions`.

Making 2026-07-28 the latest entry in `SUPPORTED_STABLE_PROTOCOL_VERSIONS` fixes all three at once,
since they all read that list. The version now serves both lifecycles of the SEP-2575 dual-era model:
negotiable through the legacy `initialize` handshake, and simultaneously the version of
the per-request modern lifecycle.

Parts of the 2026-07-28 feature set remain unimplemented, such as the stateless modern lifecycle
over the transports, and are being built separately. This change deliberately limits itself to
the version bump, focusing first on eliminating the connection errors that 2026-07-28 clients hit.

Known follow-up: the in-progress modern HTTP path routes requests to the sessionless modern lifecycle
when the header version is absent from `SUPPORTED_STABLE_PROTOCOL_VERSIONS`, so that routing predicate
needs rework on top of this change.

Closes #474

## How Has This Been Tested?

New regression tests: `initialize` with `protocolVersion: "2026-07-28"` echoes it back (`server_test.rb`),
a follow-up POST with `MCP-Protocol-Version: 2026-07-28` passes header validation
(`streamable_http_transport_test.rb`), and `Configuration.new(protocol_version: "2026-07-28")` is accepted
(`configuration_test.rb`).

`bundle exec rake test` passes (1454 runs, 0 failures). The conformance server suite passes 30/30.
The client `initialize` scenario is added to the expected-failures baseline: the conformance framework pins
the client's requested version to 2025-11-25 and does not accept 2026-07-28 yet; the entry carries a TODO
to remove it when the framework catches up.

## Breaking Changes

Servers that do not pin `configuration.protocol_version` now answer version negotiation fallbacks
and default client requests with 2026-07-28 instead of 2025-11-25. 2025-11-25 remains fully supported
and negotiable; clients that request it are unaffected.
2026-07-31 12:55:21 +09:00
Koichi ITO
5b4729294c Handle the SEP-2575 Modern Request Envelope in the Server Core
## Motivation and Context

Second step of the stateless lifecycle (SEP-2575, modelcontextprotocol/modelcontextprotocol#2575)
for the 2026-07-28 MCP spec release, building on the `MCP::RequestEnvelope` foundations.

`Server#handle_request` now lifts the per-request `_meta` envelope before dispatch: a request
whose `_meta` carries the full required triple is validated (raising `-32022` with
`data: { supported:, requested: }` for unsupported versions) and its envelope is threaded into
`tools/call`, `prompts/get`, `completion/complete`, `resources/read`, subscribe/unsubscribe,
and custom method handlers via `MCP::ServerContext`. A partial triple keeps flowing through
the legacy path untouched, so existing `_meta` usage (`progressToken`, trace context) is unaffected.

`MCP::ServerContext` gains per-request readers and a capability guard:

- `modern?`, `protocol_version`, `client_info`, and `client_capabilities` read from the envelope first
  and fall back to session state stored by `initialize` on legacy requests. The envelope always wins
  because servers MUST NOT infer client state from prior requests; nothing is written to the session
  on the modern path.
- `require_client_capability!(*path)` raises `Server::MissingRequiredClientCapabilityError`
  (`-32021` with `data: { requiredCapabilities: }`) when the request did not declare the capability.
- `notify_log_message` honors the per-request `io.modelcontextprotocol/logLevel`: on modern requests without it,
  the server MUST NOT send `notifications/message`, and an insufficient level drops the message the same way.

`MCP::ServerSession` gains the connection-era lock of the dual-era serving model: `era` is `nil`
until the first era-distinctive message succeeds, a successful `initialize` locks `:legacy` as
a side effect of `mark_initialized!`, `lock_era!` refuses to flip an established era, and transports can construct
per-request sessions with `era: :modern`. On a modern-locked session, `initialize` is rejected with `-32022`
(the modern lifecycle has no handshake) and the envelope triple becomes required for every other request
except `server/discover`.

The existing plain `RuntimeError` raises in `ServerSession#list_roots` and friends are intentionally unchanged:
converting them to `RequestHandlerError` subclasses would break callers rescuing `RuntimeError`.
Typed `-32021` errors are scoped to the new envelope-based guard.

Refs #389.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb` cover the wire behavior through `Server#handle`: envelope data exposure
without session mutation, `-32022` for unsupported envelope versions, partial triples staying legacy,
the envelope requirement and `initialize` rejection on modern-locked sessions, the `server/discover` exemption,
`require_client_capability!` returning `-32021` with the `requiredCapabilities` data shape,
and the `ServerSession` era-lock transitions (including preset `era: :modern` and invalid values).

New tests in `test/mcp/server_context_test.rb` cover the per-request logLevel gate (absent, insufficient,
and sufficient levels), the envelope-first/session-fallback readers, and string-keyed capability matching
in `require_client_capability!`.

## Breaking Changes

None. All new keyword arguments default to `nil`, legacy requests take exactly the same code path as before,
and the era lock only constrains sequences that were previously impossible (modern-era traffic).

Fix a Ruby 2.7 ArgumentError When Raising UnsupportedProtocolVersionError

## Motivation and Context

On Ruby 2.7, a method that declares a keyword parameter splits a trailing
symbol-keyed Hash positional argument into keywords. `UnsupportedProtocolVersionError#initialize`
declared `supported:`, so passing the request Hash as the second positional argument raised
`ArgumentError: unknown keywords: :name, :arguments, :_meta` inside the error constructor,
and the intended `-32022` response surfaced as a `-32603` internal error on the Ruby 2.7 CI job.

No caller overrides `supported:`; drop the keyword parameter and read
`Configuration::SUPPORTED_MODERN_PROTOCOL_VERSIONS` directly, matching the keyword-free
shape of `ResourceNotFoundError` and `MissingRequiredClientCapabilityError`.

## How Has This Been Tested?

- Reproduced the `-32603` responses on Ruby 2.7.8 and confirmed both now return `-32022`
- Added a regression test constructing the error with a symbol-keyed request Hash
- `bundle exec rake test` on Ruby 2.7.8: 1467 runs, 0 failures

## Breaking Changes

None. The `supported:` keyword argument was never passed by any caller.
2026-07-31 10:16:41 +09:00
Koichi ITO
75fffab8c8
Merge pull request #471 from koic/stateless_foundations
Add Stateless Lifecycle Foundations per SEP-2575
2026-07-31 00:09:44 +09:00
Koichi ITO
c2879fb640 Fix flash of unstyled content when loading the docs site
## Motivation and Context

Opening https://ruby.sdk.modelcontextprotocol.io/ briefly showed a black half-circle
at the bottom of the screen. The theme preference script in `head_custom.html` called
`window.jtd.setTheme` on every page load. That helper rewrites the `href` of
the render-blocking color stylesheet link, which detaches the loaded stylesheet
and refetches it, so the page paints unstyled until the replacement arrives.
During that window the search magnifier SVG, sized only by CSS, rendered at its fallback size
and appeared as a large black half-circle near the bottom of the viewport.

The site sets no `color_scheme`, so the default stylesheet is identical to the light one
and most visitors paid the flash for a no-op swap.

This change replaces the `jtd.setTheme` call with a local swapper that:

- Leaves the stylesheet untouched when the resolved theme already matches
  (treating `default` as `light`).
- Swaps non-destructively otherwise: the new link is inserted next to the current one
  and the old link is removed only after the new stylesheet has loaded. On error the new link
  is dropped and the page keeps its current styles.
- Sets `blocking="render"` on the new link so supporting browsers hold first paint until
  the dark stylesheet arrives.

It also pre-applies the dark background and text colors in `custom.scss`, keyed on
the `data-theme` attribute that is set synchronously in the head, to soften the light-colored
first paint for dark-preference visitors in browsers without `blocking="render"` support.

## How Has This Been Tested?

Mirrored the live site locally, patched the inline script with the new code,
and drove it in Chrome:

- Unpatched baseline reproduced the old behavior: the link `href` was rewritten
  and `just-the-docs-light.css` was fetched in addition to `just-the-docs-default.css`.
- Patched light and system-light loads keep the original link untouched with no extra stylesheet request.
- Patched dark loads settle on a single `just-the-docs-dark.css` link, with `jtd.getTheme()`
  still reporting the right theme.
- Rapid toggling keeps at most two color stylesheet links and settles on exactly one matching
  the final preference.
- With `just-the-docs-dark.css` returning 404, the failed link is dropped and the page stays styled.

## Breaking Changes

None.
2026-07-30 12:44:28 +09:00
Koichi ITO
1ce7c978b5
Merge pull request #472 from koic/fill_documentation_gaps
Document non-text content types, binary resources, and elicitation schema options
2026-07-29 11:48:04 +09:00
Koichi ITO
5a879b3678
Merge pull request #445 from rickreyhsig-wealthbox/client-tool-annotations
Expose server tool annotations on MCP::Client::Tool
2026-07-28 01:21:53 +09:00
rickreyhsig-wealthbox
3591acdfaa Expose server tool annotations on MCP::Client::Tool
Client#tools/#list_tools built Tool objects without an annotations
field even though the server includes annotations in every
tools/list response. Add the reader and pass the raw hash through,
mirroring how output_schema is already handled.
2026-07-27 09:54:54 -04:00
Koichi ITO
a1fd3d4283 Document non-text content types, binary resources, and elicitation schema options
## Motivation and Context

The SDK tiering system (SEP-1730) requires Tier 1 SDKs to document all non-experimental features
with examples. A documentation coverage audit against the canonical feature list found that the README.md
only showed `type: "text"` content everywhere, leaving several implemented features invisible to users:

- Tool responses with image, audio, and embedded resource content (`MCP::Content::Image` / `Audio` / `EmbeddedResource`)
- Prompt messages carrying image or embedded resource content
- Reading binary resources via `MCP::Resource::BlobContents`
- Reading resources through a registered resource template URI
- Elicitation `requested_schema` flat-object restrictions and client-side validation behavior
- Elicitation default values (SEP-1034) and enum values with `enumNames` (SEP-1330)

All of these are existing SDK capabilities; the conformance suite already exercises them.
This change documents each with prose and a runnable-style example, closing every documentation gap
that does not require new code. Legacy SSE transport remains undocumented because the SDK intentionally
does not implement it.

## How Has This Been Tested?

Documentation-only change. Every code example was written against the current public API in lib/
(`MCP::Content`, `MCP::Resource::TextContents` / `BlobContents`, `MCP::Prompt::Message`, `create_form_elicitation`)
and cross-checked with the working implementations in conformance/server.rb, which pass the conformance suite.

## Breaking Changes

None. This only adds sections to README.md.
2026-07-27 16:41:01 +09:00
Koichi ITO
d3aec1c3e6 Add Stateless Lifecycle Foundations per SEP-2575
## Motivation and Context

SEP-2575 (modelcontextprotocol/modelcontextprotocol#2575, merged for the 2026-07-28 spec release) replaces
the `initialize` handshake with a stateless "modern" lifecycle: every request carries its protocol version,
client info, and client capabilities in reserved `_meta` keys, and the server validates each request independently.
This change lays the shared vocabulary for that lifecycle without changing any behavior:

- `MCP::Configuration` gains `LATEST_MODERN_PROTOCOL_VERSION` ("2026-07-28"), `SUPPORTED_MODERN_PROTOCOL_VERSIONS`,
  and `Configuration.modern_protocol_version?`. Modern versions are deliberately kept out of `SUPPORTED_STABLE_PROTOCOL_VERSIONS`
  so `initialize` can never negotiate them and `protocol_version=` keeps rejecting them.
- `MCP::ErrorCodes` gains `HEADER_MISMATCH` (-32020), completing the spec's stateless lifecycle error code block alongside
   the existing -32021/-32022 constants.
- New `MCP::RequestEnvelope` parses and validates the per-request `_meta` triple (`io.modelcontextprotocol/protocolVersion`,
  `clientInfo`, `clientCapabilities`, plus the optional deprecated `logLevel`). A request is classified as modern only
  when the full triple is present, matching the TypeScript SDK's `RequestMetaEnvelopeSchema` and the Python SDK's `_has_modern_envelope`,
  so partial or legacy `_meta` entries keep flowing through the legacy path untouched.
- New typed errors `Server::UnsupportedProtocolVersionError` (-32022 with `data: { supported:, requested: }`) and
  `Server::MissingRequiredClientCapabilityError` (-32021 with `data: { requiredCapabilities: }`) reuse the established `RequestHandlerError`
  `error_code`/`error_data` plumbing (the -32042 URL elicitation precedent).

Nothing dispatches through `RequestEnvelope` yet; the server-side modern handling, transport routing, and client support build on
this in follow-up changes.

Refs #389.

## How Has This Been Tested?

New `test/mcp/request_envelope_test.rb` covers the modern-triple classification (full triple, partial triple, string keys,
legacy `progressToken`), parsed field access, the -32022 error data shape, and invalid-request errors for incomplete or mistyped triples.
`test/mcp/configuration_test.rb` asserts the new constants, the predicate, and that modern versions stay rejected by `protocol_version=`.
`test/mcp/server_test.rb` asserts both typed errors surface on the wire with their SEP-2575 codes and data through `Server#handle`.
`test/mcp/error_codes_test.rb` pins -32020.

## Breaking Changes

None. Constants and classes are additive; no request path changes behavior.
2026-07-26 20:03:57 +09:00
Koichi ITO
565f4de781
Merge pull request #469 from jstar0/fix/preserve-explicit-tool-content
Preserve explicit tool response content
2026-07-26 04:19:39 +09:00
Koichi ITO
fa05845a80
Merge pull request #470 from koic/release_1_0_0
Release 1.0.0
2026-07-24 17:32:39 +09:00
Koichi ITO
7f04cd3000
Merge pull request #468 from koic/fix_hash_except_ruby_2_7
Fix a `NoMethodError` on Ruby 2.7 caused by `Hash#except`
2026-07-24 04:54:12 +09:00
Koichi ITO
1ddd4d5910 Release 1.0.0
This first stable release marks the public API as stable per SEP-1730:
breaking changes now ship only in major releases, with the narrow exceptions
documented in VERSIONING.md. The release adds ROADMAP.md and VERSIONING.md
and contains no behavior changes.

Future feature proposals can be incorporated without breaking changes.
No incompatibilities have been identified with the known issues and pull requests.
2026-07-23 13:10:51 +09:00
Koichi ITO
4147b9b980
Merge pull request #466 from koic/add_versioning_policy
Add VERSIONING.md documenting the versioning and breaking-change policy
2026-07-23 13:05:52 +09:00
Koichi ITO
62d2ab7d6e
Merge pull request #465 from koic/add_roadmap
Add ROADMAP.md outlining the path toward SEP-1730 Tier 1
2026-07-23 13:05:18 +09:00
King Star
43a0ba6266
fix: preserve explicit tool response content 2026-07-23 03:11:48 +08:00
Koichi ITO
74fd99a86c Fix a NoMethodError on Ruby 2.7 caused by Hash#except
## Motivation and Context

The gemspec already declares `required_ruby_version >= 2.7.0`, but the conformance Rake task used `Hash#except` to drop
the `:port` option before handing the remaining options to `Conformance::ClientRunner`. `Hash#except` was only added in Ruby 3.0,
so running `rake conformance` on Ruby 2.7 aborted before any scenario ran, raising `NoMethodError: undefined method except for {}:Hash`.

CI missed this because no job runs `rake conformance` on Ruby 2.7: the conformance workflow runs only on Ruby 4.0,
while the Ruby 2.7.0 matrix entry runs `rake test` alone.

## How Has This Been Tested?

Replace `options.except(:port)` with `options.reject { |key, _| key == :port }`, which has been available since well
before Ruby 2.7 and returns an equivalent Hash without mutating the original. `rake conformance` now runs the full suite on Ruby 2.7,
and its baseline still passes on current Ruby, verified on Ruby 4.0.

## Breaking Changes

None.
2026-07-23 02:25:39 +09:00
Koichi ITO
f6ab1e2366
Merge pull request #464 from modelcontextprotocol/dependabot/github_actions/actions/setup-node-7
Bump actions/setup-node from 6 to 7
2026-07-22 10:01:09 +09:00
Koichi ITO
975019bb9c Add VERSIONING.md documenting the versioning and breaking-change policy
## Motivation and Context

The SDK tiering system (SEP-1730) requires Tier 1 SDKs to publish a clear
versioning policy with a documented breaking-change policy. The CHANGELOG
already states that the project adheres to Semantic Versioning, but there
was no standalone document describing what counts as a breaking change,
how the 0.x phase differs from post-1.0.0, or how incompatibilities are
communicated to users.

One policy decision is worth calling out: minor releases avoid incompatible
changes as much as possible, but fixes for incorrect MCP spec conformance,
for security vulnerabilities, and for clear defects (behavior contradicting
the documentation, crashes, or data corruption) may ship in a minor release
even when they are behavior-breaking. The SDK's primary contract is
conformance to the MCP specification, so behavior that deviates from
the spec is treated as a bug rather than an API guarantee, and preserving
compatibility with a clear defect would mean preserving the defect itself.

## How Has This Been Tested?

Documentation-only change; there is no code to exercise. The referenced
files (CHANGELOG.md, GitHub Releases) and their formats were verified
against the current repository state.

## Breaking Changes

None. This adds a new top-level Markdown document and touches no code.
2026-07-21 11:33:20 +09:00
Koichi ITO
3fcef2dda3 Add ROADMAP.md outlining the path toward SEP-1730 Tier 1
## Motivation and Context

The SDK tiering system (SEP-1730) requires a published roadmap for both Tier 1 and Tier 2.
Until now the Ruby SDK had no roadmap document, which left users without visibility into
upcoming feature support and blocked the tiering requirement.

This document records the SDK's current conformance status (all server and client scenarios passing),
the API stability policy backed by Semantic Versioning and VERSIONING.md,
the handling of features deprecated by the 2026-07-28 spec revision (SEP-2577),
and how new MCP spec revisions will be tracked. Legacy SSE transport is explicitly called
out as out of scope so users are not left guessing about it.

## How Has This Been Tested?

Documentation-only change; there is no code to exercise. The conformance figures cited in
the roadmap were taken from the current SEP-1730 tier assessment run against the latest main.

## Breaking Changes

None. This adds a new top-level Markdown document and touches no code.
2026-07-21 11:30:25 +09:00
dependabot[bot]
9ac6f577e0
Bump actions/setup-node from 6 to 7
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 6 to 7.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-20 20:13:45 +00:00
Koichi ITO
72400ca12b
Merge pull request #463 from koic/work_conformance_client_merged
[Conformance] Report expected client terminal failures quietly
2026-07-20 01:05:02 +09:00
Koichi ITO
f3ffe43cdb [Conformance] Report expected client terminal failures quietly
## Motivation and Context

Negative auth scenarios such as `auth/resource-mismatch` and `auth/scope-retry-limit` are
designed to drive the client into a terminal failure: the SDK correctly refuses
a mismatched protected-resource metadata `resource` and stops after the scope step-up retry limit.
The conformance harness asserts on the observed protocol exchange and already marks these scenarios as passed,
but the client script had no top-level rescue, so each run leaked a raw Ruby backtrace to stderr inside a noisy
"Client exited with code 1" block.

This change wraps the connect and scenario dispatch in a rescue that reports the expected `AuthorizationError`,
`RequestHandlerError`, and `Faraday::Error` outcomes as a concise one-line reason on stderr and exits with status 0.
The harness echoes the client's output only when the exit status is non-zero and does not consult the exit status
for its verdict, so the expected failures no longer produce any output block at all; the one-line reason remains
visible in manual runs and in the harness `--output-dir` stderr artifact. Any unexpected error still raises with
a full backtrace and a failing exit status so genuine SDK bugs remain visible.

## How Has This Been Tested?

Ran `bundle exec rake conformance`: the server suite passes 40/40 and the client suite passes 280/280
with no "Client exited with code" or "Stderr:" blocks in the output. Exercised `auth/resource-mismatch`
and `auth/scope-retry-limit` individually via `Conformance::ClientRunner`; both pass with clean output.

## Breaking Changes

None. Only the conformance client script output changes; no library code is affected.
2026-07-19 10:53:31 +09:00
Koichi ITO
f9fd78e3fb
Merge pull request #462 from koic/release_0_25_0
Release 0.25.0
2026-07-18 14:04:54 +09:00
Koichi ITO
df578d79ca Release 0.25.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-07-18 10:57:14 +09:00
Koichi ITO
0b51173441
Merge pull request #460 from koic/lowercase_response_header_names
Lowercase response header names in `StreamableHTTPTransport`
2026-07-18 10:35:29 +09:00
Koichi ITO
b1b50da0fd
Merge pull request #461 from koic/avoid_cancelling_conformance_runs_on_main
Avoid cancelling in-progress conformance runs on main
2026-07-18 10:35:12 +09:00
Koichi ITO
c78d4a2301 Avoid cancelling in-progress conformance runs on main
## Motivation and Context

When two PRs are merged to main in quick succession, the Conformance Tests run for
the earlier merge commit is cancelled by the run for the later one.

On push events, `github.ref` is always `refs/heads/main`, so every merge to main shares
the same concurrency group and `cancel-in-progress: true` cancels all but the latest run.
As a result, only the last merged PR gets a conformance result.

This change appends `github.sha` to the concurrency group for push events so that
each merge commit runs independently. For pull_request events the SHA part is empty,
keeping the existing behavior where pushing new commits to a PR cancels its superseded runs.

## How Has This Been Tested?

Validated the workflow YAML syntax locally. The concurrent behavior itself can only be
observed on GitHub Actions, by confirming that both Conformance Tests runs complete
when two pushes land on main within a short interval.

## Breaking Changes

None.
2026-07-17 10:20:40 +09:00
Koichi ITO
991926a10d Lowercase response header names in StreamableHTTPTransport
## Motivation and Context

The Rack 3 SPEC requires response header names to be lowercase.
https://github.com/rack/rack/blob/main/SPEC.rdoc says in its "The Headers" section:

> Header keys must not contain uppercase ASCII characters (A-Z).

https://github.com/rack/rack/blob/main/SPEC.rdoc#the-headers

However, `StreamableHTTPTransport` emitted capitalized names such as `Content-Type` and `Mcp-Session-Id`.
Any `Rack::Lint`-wrapped stack, including the default development mode of rackup, rejects every response
from the transport with a `LintError` 500. Lowercasing the names restores Rack 3 compliance.
HTTP header names are case-insensitive on the wire, so HTTP clients are unaffected;
only in-process consumers that read the raw Rack headers hash see the new keys.

Lowercase is also the only representation valid across HTTP versions: RFC 9113 makes uppercase field names
a protocol error on HTTP/2, so proxies and h2-capable servers already require it.
The TypeScript SDK sets `headers['mcp-session-id']` and the Python SDK defines `MCP_SESSION_ID_HEADER = "mcp-session-id"`,
so lowercase also matches what the reference SDKs emit; the MCP spec's `Mcp-Session-Id` casing is prose convention,
not a wire requirement.

Examples and documentation deliberately keep the spec's `Mcp-Session-Id` casing where it does not name
a Rack response hash key: curl invocations and `examples/streamable_http_client.rb` set request headers,
which the Rack response rule does not govern; the rack-cors `expose:` entry carries a header name as
an `Access-Control-Expose-Headers` value, which browsers match case-insensitively;
and README/docs prose follows the MCP specification's documentation convention.
Only code reading the raw Rack response headers hash, a case-sensitive Hash lookup, had to switch to lowercase keys.

AGENTS.md now records the lowercase rule under the code style guidelines, since the MCP spec's `Mcp-Session-Id` prose casing
invites reintroducing capitalized names in future transport work.

## How Has This Been Tested?

Added a regression test asserting that header names are lowercase in initialize, GET SSE, DELETE, and parse error responses.
Existing tests that read the raw headers hash were updated to the new keys. Verified with rake test, rake rubocop,
and rake conformance.

## Breaking Changes

Code that reads the raw Rack response headers hash returned by `handle_request`, or by middleware around the mounted transport,
with exact-case keys such as `"Mcp-Session-Id"` must switch to the lowercase keys. Clients speaking HTTP are
unaffected because header names are case-insensitive on the wire.
2026-07-16 11:45:48 +09:00
Koichi ITO
cc219a2151
Merge pull request #458 from koic/feature_sampling_client
Support client-side sampling via `MCP::Client#on_sampling`
2026-07-16 01:04:28 +09:00
Koichi ITO
7ebaf989d9
Merge pull request #459 from koic/bound_client_sse_event_buffering
Bound client-side message buffering in the HTTP transport
2026-07-16 01:00:26 +09:00
Koichi ITO
5533a6df92
Merge pull request #454 from koic/cross_app_access
Support SEP-990 Cross-App Access via ID-JAG and the jwt-bearer Grant
2026-07-16 00:58:08 +09:00
Koichi ITO
ced5cd1a95 Bound client-side message buffering in the HTTP transport
## Motivation and Context

`MCP::Client::HTTP` buffers server bytes with no upper bound in two places:

- SSE responses are parsed incrementally, but the parser accumulates `data:` lines until
  a blank line dispatches the event, so a server that never terminates an event grows
  the buffer indefinitely. The abort-on-response signal does not help here, since it only fires
  after a complete response event has been dispatched.
- Non-SSE (JSON) bodies accumulate in `SSEStream#buffer` chunk by chunk with no limit.

Both the POST response stream and the standalone GET listening stream are affected.
The stdio client already bounds server frames (`max_line_bytes:`, 4 MiB default)
and the server transports bound request bodies (`max_request_bytes:`, 4 MiB default);
this brings the HTTP client in line.

`MCP::Client::HTTP.new` gains `max_message_bytes:` (default 4 MiB), which caps the bytes buffered
for a single message - an SSE event or a JSON response body. External byte counting cannot tell
consumed-and-discarded bytes (comments, field names, delimiters) from consumed-and-retained ones,
so the check measures the parser's own String buffers after each chunk. An over-limit message raises
`RequestHandlerError` on the request path and stops the GET listening stream instead of reconnecting to
the same over-limit event.

## How Has This Been Tested?

New tests in `test/mcp/client/http_test.rb` cover the SSE and JSON rejection paths end-to-end,
the per-event reset (events that individually fit must not count against later ones),
the env-less `on_data` fallback, and the constructor validation. `bundle exec rake`
(tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

Responses larger than 4 MiB are now rejected by default; pass a larger g`max_message_bytes:` to accept them.
2026-07-15 12:02:15 +09:00
Koichi ITO
84090a88eb
Merge pull request #456 from koic/handle_initialize_request_without_id
Handle an initialize request sent without an ID
2026-07-15 12:01:59 +09:00
Koichi ITO
5425c9c4ee
Merge pull request #455 from koic/reject_notifications_for_unknown_sessions
Reject notifications carrying an unknown or expired session
2026-07-15 12:01:42 +09:00
Koichi ITO
f3d6da2371 Support client-side sampling via MCP::Client#on_sampling
## Motivation and Context

The MCP specification defines `sampling/createMessage` as a server-to-client request
that lets a server ask the client to generate an LLM completion, so the server can leverage
the client's model access without its own API keys.
The Ruby SDK already supports the server side (sending the request) and, on the client side,
the generic server-to-client request infrastructure introduced for elicitation
(the standalone GET SSE listening stream and `on_server_request` dispatch).
This adds the client-side `sampling/createMessage` handler on top of that infrastructure.

## Changes

- Add `MCP::Client#on_sampling`, a thin wrapper that registers a `sampling/createMessage` handler
  via `transport.on_server_request`, mirroring `on_elicitation`. The handler receives the request params
  and returns a `CreateMessageResult`-shaped Hash sent back as the JSON-RPC result.
- Document client-side sampling in the README, including the `sampling` (and `sampling.tools`)
  capability declaration and the human-in-the-loop guidance from the specification.

## How Has This Been Tested?

- Unit tests for `on_sampling` covering handler registration on the transport
  and the error raised when the transport does not support server-to-client requests.
- An HTTP transport test that dispatches a `sampling/createMessage` server request delivered on
  the SSE stream and returns a `CreateMessageResult`.

## Deprecation Note

SEP-2577 deprecates sampling (along with roots and logging) starting with protocol version `2026-07-28`.
The deprecation warnings are added in https://github.com/modelcontextprotocol/ruby-sdk/pull/406.
Sampling remains fully supported under the current `2025-11-25` protocol version and stays available
throughout the spec's deprecation window, so the client side is implemented here for parity with
the server side and with the Python and TypeScript SDKs.

`MCP::Client#on_sampling` carries the same `@deprecated` annotation as the server-side senders
annotated in #429, tailored to the receiving side: the handler exists to interoperate with servers
that still send sampling requests during the deprecation window. The README section carries
the same note.

Ref: https://modelcontextprotocol.io/specification/2025-11-25/client/sampling
2026-07-15 01:51:41 +09:00
Koichi ITO
1101900f31
Merge pull request #457 from koic/fix_rubocop_shopify_3_0_offenses
Fix RuboCop offenses detected with rubocop-shopify 3.0.0
2026-07-15 01:51:06 +09:00
Koichi ITO
ab4075c8c7 Fix RuboCop offenses detected with rubocop-shopify 3.0.0
## Motivation and Context

This repository does not track Gemfile.lock, so `bundle install` resolves to the latest RuboCop gems.
Upgrading rubocop-shopify from 2.x to 3.0.0 surfaces 8 new offenses because the shared config no longer
disables `Style/MutableConstant`, newly disables `Lint/RescueException` and `Naming/AccessorMethodName`,
and drops `AllowedPatterns` for `Naming/MethodName`. Upgrading rubocop itself to 1.88 surfaces one more offense
from the new `Style/ReduceToHash` cop.

This change fixes them as follows:

- Freeze mutable constants. Regexp constants are also flagged because `TargetRubyVersion` is 2.7,
  where Regexp literals are not frozen.
- Remove inline disable directives that became redundant.
- Restore `AllowedPatterns: ['\Atest_']` for `Naming/MethodName` so `def test_` style test names
  can reference class names such as `NoMethodError`.
- Swap out the frozen `SUPPORTED_STABLE_PROTOCOL_VERSIONS` constant in the protocol version fallback test
  since Mocha cannot stub methods on frozen objects.
- Use `to_h` instead of `each_with_object` in `Server#index_resources_by_uri`.

Ref: https://rubygems.org/gems/rubocop-shopify/versions/3.0.0

## How Has This Been Tested?

`bundle exec rake` passes: 1402 runs, 0 failures, 0 errors, and RuboCop reports no offenses.
The conformance suite also passes against its baseline.

## Breaking Changes

None. Freezing these constants only affects code that mutates them in place, which has never been supported.
2026-07-15 01:46:51 +09:00
Koichi ITO
fc0c6b8f3f Handle an initialize request sent without an ID
## Motivation and Context

`StreamableHTTPTransport#handle_post` routes to `handle_initialization` via `initialize_request?`,
which matches on the method name alone. An `initialize` message sent without an id (framed as a notification)
therefore reaches `handle_initialization`. `Server#init` runs and marks the session initialized,
but JSON-RPC emits no response for an id-less request, so `handle_json` returns nil.

Two things then went wrong:

- `handle_initialization` returned `[200, headers, [nil]]`. A `nil` body element is not a valid Rack response,
  so the web server raises while serializing it (`NoMethodError` on `nil.bytesize`)
  and the client gets a malformed response or a 500.
- The `if session_id && !server_session.initialized?` cleanup guard was skipped, because the session is marked initialized.
  The session was retained with a `Mcp-Session-Id` header, so a stream of id-less `initialize` messages accumulates sessions
  toward the `max_sessions` cap until the reaper reclaims them.

`handle_initialization` now treats a nil response as an id-less initialize: it discards the orphaned session
and acks with 202, mirroring how `handle_regular_request` already handles a nil response.
A well-formed `initialize` request (with an id) is unaffected.

## How Has This Been Tested?

A new test in `test/mcp/server/transports/streamable_http_transport_test.rb` posts an `initialize`
with no id and asserts a 202 with an empty body, no `Mcp-Session-Id` header, and an empty session map.
It fails against the previous code (a 200 with a nil body element and a retained session) and passes now.

## Breaking Changes

None. A conforming client sends `initialize` as a request with an id and is unaffected;
only the malformed id-less form changes, from a broken 200 to a 202 with no retained session.
2026-07-14 01:09:18 +09:00
Koichi ITO
6236ea1b34 Reject notifications carrying an unknown or expired session
## Motivation and Context

In `StreamableHTTPTransport#handle_post`, the response and regular-request branches reject
a message whose session no longer exists (the response branch via `session_exists?`,
the regular path via `validate_and_touch_session`), but the notification branch dispatched unconditionally.
A notification carrying a present-but-unknown (or expired-but-not-yet-reaped) `Mcp-Session-Id`
therefore passed the `missing_session_id` gate and the ownership gate (which returns true
when the session does not exist) and reached `dispatch_notification` with no session,
running against the shared `Server` instead of a live `ServerSession`. With the default no-op notification
handlers this had no visible effect, but a custom notification handler would then run without
a live session behind it.

`handle_post` now checks `session_active?` in the notification branch, mirroring the other two branches.
`session_active?` rejects an unknown or expired session (evicting the expired one) without extending its lifetime,
so a stale session ID yields `404 Session not found` and a live session is dispatched exactly as before.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` assert that
a notification with an unknown session ID is rejected with `404 Session not found`
and that a notification carrying a live session ID is still accepted with `202`.
The new rejection test fails against the previous code (it returned `202`) and passes now.

## Breaking Changes

None for a conforming client: a client that has completed `initialize` sends its notifications with
the live session ID and is unaffected. Only a notification bearing an unknown or expired session ID,
previously accepted with `202`, now receives `404 Session not found`.
2026-07-14 01:07:25 +09:00
Koichi ITO
145a6b6230 Support SEP-990 Cross-App Access via ID-JAG and the jwt-bearer Grant
## Motivation and Context

The MCP Enterprise Managed Authorization extension (SEP-990, modelcontextprotocol/modelcontextprotocol#990,
accepted/final, published in the ext-auth repository) lets enterprise identity providers govern MCP authorization:
the client exchanges an IdP-issued ID token for an Identity Assertion Authorization Grant (ID-JAG) via
RFC 8693 token exchange at the IdP, then presents the ID-JAG to the MCP authorization server with
the RFC 7523 `jwt-bearer` grant, authenticating with `client_secret_basic`.
The `auth/cross-app-access-complete-flow` conformance scenario exercises the complete flow and previously failed
its two core checks (the Ruby client ran the authorization-code flow instead).

This mirrors the merged TypeScript SDK implementation (`requestJwtAuthorizationGrant` / `CrossAppAccessProvider` in
typescript-sdk; the Python SDK tracks the same work in the open python-sdk#1721), adapted to this SDK's provider design:

- New `MCP::Client::OAuth::IDJAGTokenExchange.request` performs the RFC 8693 exchange at the IdP token endpoint
  (`subject_token_type` id_token, `requested_token_type` id-jag, `audience` = the MCP authorization server's issuer,
  `resource` = the canonical MCP server URL) and validates that the response's `issued_token_type` is an ID-JAG
  before returning the assertion. The ID-JAG itself is treated as opaque, as in the TypeScript SDK.
- New `MCP::Client::OAuth::CrossAppAccessProvider` declares `authorization_flow :jwt_bearer` and takes the assertion
  from a callable (`call(audience:, resource:)`), so the common `IDJAGTokenExchange` case, enterprise secret stores,
  and tests all plug in the same way (the TypeScript provider's assertion callback works identically).
  The MCP AS credentials are stored as `client_secret_basic` client information.
- `Flow` dispatches `:jwt_bearer` alongside `:client_credentials`: discovery, issuer validation, and endpoint security checks
  are shared with `run!`, then `run_jwt_bearer!` requests the assertion with the validated issuer as the audience and posts
  the `jwt-bearer` grant through the existing `post_to_token_endpoint`.
- The conformance client builds a `CrossAppAccessProvider` when the harness injects `idp_id_token` (exchanging it at
  `idp_token_endpoint` with `idp_client_id`, like the TypeScript and Python conformance clients),
  and `auth/cross-app-access-complete-flow` is removed from `conformance/expected_failures.yml`.

## How Has This Been Tested?

- New `test/mcp/client/oauth/id_jag_token_exchange_test.rb` asserts the exact RFC 8693 form parameters on the wire
  and the response validation: a non-ID-JAG `issued_token_type` is rejected, as are a missing `access_token`,
  non-2xx responses, unparseable bodies, and non-object JSON.
- New `test/mcp/client/oauth/cross_app_access_provider_test.rb` covers the provider surface:
  stored `client_secret_basic` credentials, the `:jwt_bearer` flow declaration, audience/resource passthrough to
  the assertion callable, constructor validation (missing client_id, missing client_secret, non-callable assertion provider),
  and storage delegation.
- New tests in `test/mcp/client/oauth/flow_test.rb` run the full grant against WebMock stubs: the token request carries
  `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer`, the assertion, the RFC 8707 `resource`, and HTTP Basic credentials,
  with no DCR and no authorization-code machinery; the assertion callable receives the validated issuer as `audience`
  and the canonical server URL as `resource`; an empty assertion aborts before the token endpoint is contacted.

## Breaking Changes

None. `IDJAGTokenExchange` and `CrossAppAccessProvider` are new, and the `Flow` dispatch only activates for providers
that declare `authorization_flow :jwt_bearer`.
2026-07-13 11:45:42 +09:00
Koichi ITO
e85f6d0632
Merge pull request #453 from koic/release_0_24_0
Release 0.24.0
2026-07-12 13:24:06 +09:00
Koichi ITO
1d8db69df0 Release 0.24.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.

One of the requirements for the official SDK to move from Tier 3 to Tier 2 is reaching v1.0,
and that milestone is now quite close.

The main considerations for v1.0 are API stability and minimizing breaking changes.
Based on the work in my local branch, a path toward Tier 1 is already becoming clear from
my perspective, and this release is part of the work to prepare for Tier 2.
2026-07-12 02:32:53 +09:00
Koichi ITO
be59660500
Merge pull request #443 from koic/elicitation_sep1034_defaults
Support client-side elicitation with SEP-1034 schema defaults
2026-07-12 02:18:27 +09:00
Koichi ITO
5f9c84df1b
Merge pull request #441 from koic/mcp_apps
Add Server-Side MCP Apps Helpers per SEP-1865
2026-07-12 02:17:49 +09:00
Koichi ITO
a793dde6cd
Merge pull request #440 from koic/mcp_2026_07_28_spec_associate_server_requests
Associate server-to-client requests with the originating client request per SEP-2260
2026-07-12 02:17:04 +09:00
Koichi ITO
e1fabe3fcb
Merge pull request #439 from koic/issuer_bound_client_credentials
Bind Stored Client Credentials to the Authorization Server Issuer per SEP-2352
2026-07-12 02:16:12 +09:00
Koichi ITO
c43ea6e51b
Merge pull request #433 from koic/mrtr_result_type
Recognize multi round-trip `input_required` results per SEP-2322
2026-07-12 02:15:01 +09:00
Koichi ITO
562afdf71e
Merge pull request #432 from koic/client_credentials_jwt
Support `private_key_jwt` Client Authentication for the client_credentials Grant
2026-07-12 02:14:11 +09:00
Koichi ITO
3d442d0a65
Merge pull request #448 from koic/handle_non_object_json_rpc_messages
Handle non-object JSON-RPC messages without raising
2026-07-12 02:12:46 +09:00
Koichi ITO
8aae052efd
Merge pull request #431 from koic/iss_parameter_validation
Validate the RFC 9207 `iss` Authorization Response Parameter per SEP-2468
2026-07-12 02:11:52 +09:00
Koichi ITO
6ddcc49865 Associate server-to-client requests with the originating client request per SEP-2260
## Motivation and Context

SEP-2260 (modelcontextprotocol/modelcontextprotocol#2260, merged for the 2026-07-28 spec release)
requires servers to send `roots/list`, `sampling/createMessage`, and `elicitation/create` only in
association with an originating client request (`ping` is exempt); standalone server-initiated requests
on independent streams must not be implemented. On the Streamable HTTP transport, an associated request
rides the originating POST's SSE response stream instead of the standalone GET stream.

The Ruby SDK's `ServerContext` already satisfies the requirement for handler-scoped calls:
`list_roots`, `create_sampling_message`, `create_form_elicitation`, and `create_url_elicitation` stamp
the originating request id as `related_request_id`, and because the literal keyword appears after `**kwargs`,
a caller-supplied `related_request_id:` is overridden. That behavior was previously untested and undocumented.
This change pins it down and adds a migration signal for direct `ServerSession` calls, mirroring
the TypeScript SDK's approach (typescript-sdk#2228, non-overridable `relatedRequestId` stamping on ctx-scoped requests):

- `ServerContext` documents the non-overridable stamping, and new tests lock it in for all four request helpers.
- `ServerSession#list_roots`, `#create_sampling_message`, `#create_form_elicitation`, and `#create_url_elicitation`
  emit a deprecation warning when called without `related_request_id:` (the call still goes out unchanged,
  on the GET stream for Streamable HTTP). `ServerSession#ping` is exempt per the SEP. Hard enforcement is
  deferred to a future protocol-version gate for 2026-07-28.
- A new transport test verifies that `send_request` with `related_request_id` delivers on the originating POST stream
  and never falls back to the GET stream.

Resolves #381.

## How Has This Been Tested?

- `test/mcp/server_context_test.rb`: `list_roots` stamps the originating request id; `create_sampling_message`,
  `create_form_elicitation`, and `create_url_elicitation` stamp it non-overridably (a caller-supplied `related_request_id:
  "attacker"` is replaced).
- `test/mcp/server_roots_test.rb`, `test/mcp/server_sampling_test.rb`, `test/mcp/server_elicitation_test.rb`:
  each `ServerSession` method warns (matching /SEP-2260/) without `related_request_id:` and stays silent with it.
  The warning assertions temporarily set `$VERBOSE = false` because the rake test task runs with `-W0`, following
  the existing `assert_implicit_connect_deprecation_warning` precedent.
- `test/mcp/server/transports/streamable_http_transport_test.rb`: a `roots/list` request with `related_request_id`
  is written to the registered POST request stream and not to the GET SSE stream.
- Existing direct-call test sites were updated to pass `related_request_id:` (or capture the warning) so the suite output
  stays clean; their assertions are unchanged.

## Breaking Changes

None. Behavior is unchanged; direct `ServerSession` calls without `related_request_id:` now emit a deprecation warning
but are still sent exactly as before.
2026-07-12 02:10:16 +09:00
Koichi ITO
d8ba1a84ff
Merge pull request #452 from koic/fix_mutex_probe_test_helper_initialize_params
Send required `initialize` params in the mutex probe test helper
2026-07-12 01:56:31 +09:00
Koichi ITO
ac12f91525 Send required initialize params in the mutex probe test helper
## Motivation and Context

`bundle exec rake` fails on main with four errors in `streamable_http_transport_test.rb`:

```
NoMethodError: undefined method '[]=' for nil
  streamable_http_transport_test.rb:5119 (install_mutex_probe_stream)
```

This is a semantic conflict between two merged PRs. #451 made the server reject `initialize` requests
that lack the required `protocolVersion`, `capabilities`, and `clientInfo` params with -32602. #449,
merged after but developed before it, added the "writes outside the mutex" tests,
whose `initialize_test_session` helper sends an `initialize` request with no params.
That request is now rejected, no session is created, so `@sessions[session_id]` is nil and installing
the probe stream raises `NoMethodError`.

The fix adds `params: initialize_params` to the helper's request body, matching the pattern used
by every other `initialize` request in the file via `InitializeParamsTestHelper`.

## How Has This Been Tested?

`bundle exec rake` now passes: 1318 runs, 0 failures, 0 errors, and RuboCop reports no offenses.
The four previously failing tests are the regression coverage.

## Breaking Changes

None. Test-only change.
2026-07-12 01:53:12 +09:00
Koichi ITO
e81196e9de
Merge pull request #449 from koic/avoid_blocking_sse_writes_under_session_mutex
Perform SSE stream writes outside the session mutex
2026-07-12 01:43:45 +09:00
Koichi ITO
a1b7b00b22
Merge pull request #444 from koic/add_rails_example
Add Rails example app
2026-07-12 01:43:04 +09:00
Koichi ITO
287db21690
Merge pull request #451 from koic/validate_required_initialize_and_subscribe_params
Validate Required Params for `initialize` and `resources/subscribe`
2026-07-12 01:42:39 +09:00
Koichi ITO
abd1070cfa Validate Required Params for initialize and resources/subscribe
## Motivation and Context

Fixes https://github.com/modelcontextprotocol/ruby-sdk/issues/450

The MCP schema requires `protocolVersion`, `capabilities`, and `clientInfo` on `initialize` params,
and `uri` on `resources/subscribe` and `resources/unsubscribe` params. The server accepted requests with
these fields absent: `initialize` silently negotiated the server's default protocol version,
and `resources/subscribe` returned an empty success result. Both now return `-32602` Invalid params,
matching the Python SDK, which rejects such requests during pydantic validation.
The `uri` check runs before dispatch so it also covers handlers registered via `resources_subscribe_handler`
and `resources_unsubscribe_handler`.

A `protocolVersion` value that is present but unsupported still negotiates the server's fallback version,
as the spec's lifecycle section requires.

## How Has This Been Tested?

Reproduced the issue's stdio repro steps: both malformed requests now return `-32602` instead of succeeding.

## Breaking Changes

Clients that send `initialize` without `protocolVersion`, `capabilities`, or `clientInfo`,
or `resources/subscribe` / `resources/unsubscribe` without `uri`, now receive `-32602` Invalid params
instead of a success response. Such requests violate the MCP schema, but any code relying on
the previous lenient behavior (for example, test harnesses sending bare `initialize` requests)
must now include the required fields.
2026-07-11 22:36:34 +09:00
Koichi ITO
d71ec506c4
Merge pull request #447 from koic/support_class_based_resource_definitions
Support class-based Resource and ResourceTemplate definitions
2026-07-11 22:00:58 +09:00
Koichi ITO
5b935eb031 Perform SSE stream writes outside the session mutex
## Motivation and Context

`StreamableHTTPTransport` guards its `@sessions` and `@pending_responses` maps with one `@mutex`.
The send paths wrote to an SSE stream while holding that lock: the targeted and
broadcast branches of `send_notification`, the server-to-client `send_request`,
and `send_keepalive_ping` all called `send_to_stream`/`send_ping_to_stream`
(a `stream.write` plus `stream.flush`) inside `@mutex.synchronize`.

A stream write is blocking I/O with no timeout: if a client reads its SSE stream slowly,
the server-side `write` waits until the socket buffer drains.
Performing that write under `@mutex` serializes every other session on the same lock (head-of-line blocking):
new `initialize` inserts, session validation, `handle_response`, the reaper, and delivery to other sessions
all wait behind one slow reader. The broadcast path holds the lock across every session,
so one slow stream also delays delivery to the sessions after it.

The cleanup paths already release the lock before touching a stream: they collect `streams_to_close`
and call `close` outside `synchronize`. This change applies the same discipline to the writes.

- Each send path resolves its target stream under `@mutex` (and, for `send_request`, registers
  the pending response there), then releases the lock before writing.
- A write error still drops the broken stream. That teardown is centralized in a new `drop_broken_stream`,
  which mutates `@sessions` under `@mutex` and closes the affected streams outside it.
  A request-scoped stream is dropped on its own; a GET SSE failure removes the whole session,
  matching the previous behavior.
- `send_notification` splits into `deliver_targeted_notification` and `deliver_broadcast_notification`;
  the return values (true/false for a session, the delivered count for a broadcast) are unchanged.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` install a probe stream that records,
via `mutex.try_lock`, whether `@mutex` is held during each write, and assert it is not held for the targeted notification,
broadcast, `send_request`, and keepalive paths. Each new test fails against the previous code and passes now.
The existing send and cleanup tests still pass.

## Breaking Changes

None. Delivery semantics and return values are unchanged; the lock is simply no longer held while writing to a stream.
2026-07-11 17:17:59 +09:00
Koichi ITO
8875990909 Handle non-object JSON-RPC messages without raising
## Motivation and Context

A JSON-RPC message is an object, but two stdio-facing paths assumed that and raised
on a non-object value parsed from an incoming frame:

- `JsonRpcHandler.handle` maps each element of a batch array through `process_request`,
  which reads `request[:id]` assuming a Hash. A non-object batch element (for example `[[]]`
  or `[5]`) makes `[][:id]` raise `TypeError`. `handle_json` rescued only `JSON::ParserError`,
  so the error escaped; over stdio it escaped the `StdioTransport#open` read loop.
  The HTTP transport already rejects array bodies before dispatch, so this surfaced only on stdio.
- `MCP::Client::Stdio#read_response` parses each frame from the server and calls `parsed.key?("id")`,
  which raises `NoMethodError` when the server emits a non-object frame.
  Only `JSON::ParserError` was rescued, so one malformed line from the server escaped.

Both are robustness gaps: a malformed frame should be reported or skipped, not raise
an unhandled exception out of the transport.

- `process_request` now returns an `INVALID_REQUEST` error response for a non-object request
  before touching `request[:id]`, so a malformed batch element becomes a normal per-element error.

- `handle_json` gains a last-resort `StandardError` rescue that returns an `INTERNAL_ERROR` response,
  so an unexpected handling error still produces a JSON-RPC reply.
- `read_response` skips a non-object frame the same way it skips a frame without an id.

## How Has This Been Tested?

New tests in `test/json_rpc_handler_test.rb` cover non-object batch elements
(`[[]]`, `[5]`, `["x"]`, `[nil]`, `[true]`), a valid request followed by one non-object element,
and `handle_json("[[]]")` returning an error instead of raising. A test in
`test/mcp/server/transports/stdio_transport_test.rb` drives `open` with a `[[]]` line and
asserts it emits an error response without raising. A test in `test/mcp/client/stdio_test.rb`
has the server emit non-object frames before the response and asserts the client skips them
and still returns the response.

## Breaking Changes

None. A well-formed request, batch, or response is handled exactly as before;
only a non-object message now yields a JSON-RPC error on the server or is skipped by the client
instead of raising.
2026-07-11 17:06:37 +09:00
Koichi ITO
b6df40b134 Support class-based Resource and ResourceTemplate definitions
## Motivation and Context

Resolve the design difference raised in issue #98: Tools and Prompts support class-based definitions
while Resources and Resource Templates were plain data objects requiring a `resources_read_handler` block
with manual URI routing.

`MCP::Resource` and `MCP::ResourceTemplate` now support the same class-level DSL as `MCP::Tool`
and `MCP::Prompt` (`uri`, `resource_name`, `title`, `description`, `icons`, `mime_type`, `annotations`,
`size`, `meta`, and `uri_template` / `resource_template_name` for templates), plus `define` factory methods
and `MCP::Server#define_resource` / `#define_resource_template`.

The default `resources/read` handler now routes requests automatically: an exact URI match calls
the class-based resource's `contents` method, and class-based resource templates match
simple RFC 6570 level 1 `{var}` expressions, passing extracted variables as keyword arguments.
`contents` can opt in to a `server_context:` keyword argument. When class-based entries are registered
and no match is found, the server responds with -32602 carrying the URI in error data per SEP-2164.

## How Has This Been Tested?

- Added regression tests covering the class-level DSL, URI template matching, auto-routing,
  `server_context:` opt-in, error responses, and backward compatibility of the no-op default.
- Verified end-to-end with a smoke script exercising exact-match reads, template-match reads,
  unknown URIs, and legacy instance-only setups.

## Breaking Changes

No. Instance-based registration, `resources_read_handler` precedence, and the no-op `[]` response for
setups without class-based entries are unchanged. Reassigning `Server#resources` now rebuilds
the internal URI index.

Closes #98
2026-07-10 22:39:42 +09:00
Koichi ITO
61233ed43b
Merge pull request #438 from koic/server_discover
Add `server/discover` and stateless lifecycle error codes per SEP-2575
2026-07-10 00:26:49 +09:00
Koichi ITO
f013bcbf8c
Merge pull request #436 from koic/list_result_ttl
Add Opt-In `ttlMs` / `cacheScope` Cache Hints to List and Read Results per SEP-2549
2026-07-10 00:26:21 +09:00
Koichi ITO
16a6df340c Add Rails example app
## Motivation and Context

The README.md documents the "Rails (mount)" integration pattern, but the repository
had no runnable Rails example. This adds a minimal Rails application under examples/rails
that mounts StreamableHTTPTransport at /mcp and demonstrates class-based tools and
a resource with a read handler.

The MCP server is built in config/routes.rb rather than in an initializer because
Zeitwerk sets up autoloading after initializers run, so the tool classes in app/tools
cannot be referenced there.
Code reloading is disabled because the transport holds the server built at boot.
The app is booted with puma instead of rackup because rackup inserts `Rack::Lint`
in its development default, which rejects the capitalized response header names
that the transport currently emits.

Closes #44.

## How Has This Been Tested?

The curl walkthrough in examples/rails/README.md has been verified end to end against
the running app: initialize and the initialized notification, tools/list, tools/call for
both tools, resources/list, resources/read, the standalone SSE stream,
and session termination via DELETE.

## Breaking Changes

None. This only adds an example application and documentation links.
2026-07-09 01:37:58 +09:00
Koichi ITO
04bb739c68 Support client-side elicitation with SEP-1034 schema defaults
## Motivation and Context

Resolves the `elicitation-sep1034-client-defaults` client conformance scenario
(SEP-1034, https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1034).

The Ruby HTTP client could not receive server-to-client requests at all:
it never opened the spec's standalone GET SSE listening stream, and SSE events that
were not responses were discarded. A server sending `elicitation/create` during a tools/call
(such as the conformance harness, which is built on the TypeScript SDK server)
either dropped the request silently or deadlocked the tool call waiting for an answer that
could never arrive.

This change adds three pieces:

### Server-to-client request dispatch

`MCP::Client::HTTP#on_server_request(method) { |params| ... }` registers a handler;
when a JSON-RPC request (a message with both `method` and `id`) arrives on any SSE stream,
the handler's return value is POSTed back to the server as the JSON-RPC `result`
(the server ACKs with 202 Accepted, per the transport spec).
Methods without a handler are answered with a `-32601` method-not-found error.
A handler may raise `MCP::Client::ServerRequestError` to answer with a specific JSON-RPC error code
(for example `-1` for a rejected sampling request, per the sampling spec),
mirroring the TypeScript SDK's `McpError` and the Python SDK's `ErrorData` return;
any other error is answered with a `-32603` internal error. In every case the server is not left waiting,
matching how the TypeScript and Python SDKs convert handler failures into JSON-RPC error responses.

### A standalone GET SSE listening stream

Registering a handler (once connected) opens the spec's listening stream on a background thread,
because servers deliver requests that are not tied to a client request on that stream -
the TypeScript SDK's `StreamableHTTPServerTransport` silently drops them when no GET stream is open.
Mirrors the TypeScript and Python SDK clients, which start listening right after the `initialize` handshake
without awaiting stream establishment. Reconnection semantics also follow both SDKs:
a gracefully closed stream is retried indefinitely after the server's `retry:` interval,
while consecutive connection failures (HTTP errors and idle read timeouts) stop the listener once
they reach the reconnection attempt cap, with a successful stream resetting the count;
a 405 stops immediately without retrying, since it is the spec's answer from a server that
offers no listening stream. The listening GET uses a 5-minute read timeout matching
the Python SDK's `sse_read_timeout` default. `close` terminates the thread.

### SEP-1034 defaults

`MCP::Client::Elicitation.apply_defaults` fills fields omitted from the elicitation content with
the `default` values declared in `requestedSchema` properties, never overwriting provided values
and skipping properties without a default. This follows the Python SDK, which applies defaults in
the elicitation callback; the TypeScript SDK's automatic `applyElicitationDefaults`
(gated on the `elicitation.form.applyDefaults` capability) is a possible follow-up.
`MCP::Client#on_elicitation` registers a handler for `elicitation/create` as a convenience.

The conformance client gains an `elicitation-sep1034-client-defaults` branch that connects with
`capabilities: { elicitation: {} }`, accepts the elicitation with defaults applied, and calls
the harness's `test_client_elicitation_defaults` tool; the scenario is removed from the expected failures baseline.

## How Has This Been Tested?

New unit tests covering: handler dispatch from a request's POST SSE stream with
the response body and 202 ACK verified, the `-32601` answer for unregistered methods,
the `-32603` answer for a raising handler, the custom-code answer when a handler raises
`ServerRequestError`, listener startup from both registration-after-connect and
connect-with-registered-handlers, listener shutdown after consecutive connection failures with
the count resetting after a successful stream and an immediate stop on 405,
and `apply_defaults` for all five SEP-1034 property types (string, integer, number, enum, boolean),
non-overwriting of provided values, omission of properties without defaults, and symbol-keyed schemas

## Breaking Changes

None. The listening stream and its background thread are created only when a server-request handler is registered;
clients that never call `on_server_request` / `on_elicitation` keep the existing single-request behavior.
2026-07-08 01:44:24 +09:00
Koichi ITO
ab65b919e2
Merge pull request #426 from koic/sse_retry
Support SSE Reconnection Per SEP-1699 in the HTTP Client Transport
2026-07-08 01:09:56 +09:00
Koichi ITO
95feef2dcf
Merge pull request #442 from koic/release_0_23_0
Release 0.23.0
2026-07-07 22:48:00 +09:00
Koichi ITO
494f43d3a7 Release 0.23.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-07-07 22:17:27 +09:00
Koichi ITO
6cb78eaad8
Merge commit from fork
Bound Request Body and Frame Reads to Prevent Memory-Exhaustion DoS
2026-07-07 22:10:06 +09:00
Koichi ITO
772e0cb1f9 Bound Request Body and Frame Reads to Prevent Memory-Exhaustion DoS
## Motivation and Context

Both transports read a peer-controlled message fully into memory with no upper bound,
so a single unauthenticated message can allocate gigabytes and OOM the worker:

- `StreamableHTTPTransport#handle_post` did `request.body.read` with no size limit
  before `JSON.parse`. A single ~512 MB POST grew a worker from 44 MB to 1.66 GB RSS
  in the reporter's measurement. The path runs before session validation,
  so it is reachable unauthenticated in both stateful and `stateless: true` modes.
- `StdioTransport` and `MCP::Client::Stdio` read frames with `IO#gets` and no `limit:`,
  so a peer that never emits a newline grows a single String until the process is OOM-killed.
  This matters when a host pipes an untrusted server's stdout into an unconstrained process.

The spec does not mandate a request size limit, and the reference SDKs vary
(the TypeScript SDK caps at a 4 MB default; Python/Go delegate to the web framework).
A finite default here bounds the allocation at the transport layer regardless of the deployment,
matching the TypeScript SDK's default.

- `StreamableHTTPTransport` gains `max_request_bytes:` (default 4 MiB). `handle_post`
  rejects a declared `Content-Length` over the cap before reading, and also bounds
  the actual read to one byte past the cap so a missing or spoofed `Content-Length`
  (chunked transfer) is still caught, returning HTTP 413. `parse_request_body` now passes
  `max_nesting:` (64) so a deeply nested body cannot exhaust the stack (complements the byte cap).
  The constructor validates the new option as a positive Integer, since `nil` or a non-positive
  value makes the underlying read unbounded and would silently disable the protection.
- The stdio `max_line_bytes:` bound (default 4 MiB) has since been merged upstream through
  a separate advisory, so this change carries the remaining piece of the reported stdio fix:
  an over-limit frame leaves leftover bytes in the pipe, desyncing the stream beyond recovery,
  so `MCP::Client::Stdio` now closes the transport before raising and a later `send_request`
  fails cleanly instead of parsing a truncated frame.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` cover the 413 rejection
with and without `Content-Length`, the boundary body being accepted, the nesting-depth rejection,
and the constructor validation. The client stdio over-limit test now also asserts the transport
is closed afterward (`refute_predicate(transport, :connected?)`).

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes. Verified end-to-end that
a 256 MB POST with no declared `Content-Length` is rejected with 413 without the transport reading
the whole body (a throttled `rack.input` that raises if read far past the cap is never tripped).

## Breaking Changes

None. The 4 MiB defaults comfortably fit a typical JSON-RPC message (a 4 MiB JSON string decodes to
roughly 3 MiB of base64 payload), and the new keyword arguments are additive and optional.
2026-07-07 22:03:41 +09:00
Koichi ITO
0ede5fc146
Merge commit from fork
Add a Session-Ownership Hook to StreamableHTTPTransport
2026-07-07 21:44:50 +09:00
Koichi ITO
3546660531 Add a Session-Ownership Hook to StreamableHTTPTransport
## Motivation and Context

`StreamableHTTPTransport` issues a random `SecureRandom.uuid` session ID and validates
an incoming request by session existence and idle timeout only, with no binding to a client identity.
An attacker who obtains a victim's session ID (network sniffing, logs, etc.) can therefore POST
a `tools/call` on that session and the server executes it, silently poisoning the victim's session.
The previously shipped 409 fix guards the GET SSE stream slot but does nothing for the POST write path,
so this is not covered by it.

Binding a session to a user is fundamentally the deploying application's responsibility:
the transport hands the server only the JSON-RPC body string and never receives the authenticated principal
(`Authorization`/`Origin` headers do not reach handlers), and the MCP spec frames session-to-user binding as
a SHOULD. The Python, Go, and C# SDKs bind automatically only when an authenticated identity is present.
This gives the Ruby SDK the seam to do the same:

- A `session_request_validator` constructor option, called as `->(request, session_id) { true | false }`
  on every non-`initialize` POST, GET, and DELETE against an existing session; a falsy return rejects
  with HTTP 403. The gate is applied uniformly to regular requests, notifications, and client responses,
  not just tool calls - otherwise a stolen session ID could POST `notifications/cancelled` to cancel
  a victim's in-flight request, or a forged client response, by taking a branch the gate did not cover.
  `initialize` is exempt because it establishes the session. An application that has an authenticated principal
  uses the validator to enforce that the caller owns the session; without one, ownership is not enforced.
- A limited built-in Origin-consistency check as defense in depth (not authentication): the `Origin` header
  is recorded at `initialize` and a later request whose `Origin` differs is rejected, but only when
  both are present. A non-browser client that omits `Origin` (curl, a script - i.e. the advisory's own PoC)
  is not stopped by this check; it only raises the bar against a browser-based cross-origin attacker.
  Enforcing ownership against a determined attacker requires the validator.

Stateless mode retains no sessions, so neither check applies to it.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb`: a POST whose Origin differs
from `initialize` is rejected with 403; a matching Origin and a no-Origin request both succeed;
a custom `session_request_validator` both rejects (403) and allows (200) and receives the request and session ID;
the validator also gates notification (`notifications/cancelled`) and client-response POSTs, not just regular requests;
and stateless mode never consults the validator.

## Breaking Changes

None. `session_request_validator` defaults to `nil`, and the built-in Origin check only rejects when both
the session and the request carry an `Origin` and they differ, so existing applications are unaffected.
2026-07-07 21:41:29 +09:00
Koichi ITO
4b400be6ed
Merge commit from fork
Bound Stateful Session Retention to Prevent an Initialize-Flood DoS
2026-07-07 21:32:45 +09:00
Koichi ITO
dfdd4efc24 Merge upstream modelcontextprotocol/ruby-sdk main
Resolves conflicts in lib/mcp/server/transports/streamable_http_transport.rb
between the DNS rebinding protection merged upstream (allowed_origins,
allowed_hosts, dns_rebinding_protection keywords) and this branch's session
retention hardening (session_idle_timeout default and max_sessions keyword)
by combining both sets of keyword arguments and constructor logic.
2026-07-07 21:28:11 +09:00
Koichi ITO
cfccb7ca25
Merge commit from fork
Validate `Host` and `Origin` Headers to Prevent DNS Rebinding per MCP 2025-11-25
2026-07-07 21:16:03 +09:00
Koichi ITO
c8930758ad
Merge commit from fork
Bound stdio frame reads with max_line_bytes
2026-07-07 21:10:07 +09:00
Koichi ITO
7d9fda4360 Add Server-Side MCP Apps Helpers per SEP-1865
## Motivation and Context

SEP-1865 "MCP Apps - Interactive User Interfaces for MCP" is Final on the Extensions Track:
(https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1865) an optional extension,
negotiated through the SEP-2133 `capabilities.extensions` mechanism, that lets a server ship
HTML user interfaces which the host renders for tool results.
The normative spec lives in the ext-apps repository (`specification/2026-01-26/apps.mdx`).
The Python SDK implements it in-SDK (python-sdk#3003, the `Apps` extension); the TypeScript
ecosystem ships it as the separate `@modelcontextprotocol/ext-apps` package on top of
the core SDK's SEP-2133 support.

Server-side support is a thin convention layer over primitives this SDK already has
(SEP-2133 extension capabilities, `_meta` on tools and resources, free-form resource URIs
and MIME types). New `MCP::Apps` module:

- Wire vocabulary constants shared with the reference implementations: `EXTENSION_ID`
  (`"io.modelcontextprotocol/ui"` - note `/ui`, not `/apps`), `RESOURCE_MIME_TYPE`
  (`"text/html;profile=mcp-app"`), `URI_SCHEME` (`"ui://"`), and the legacy flat meta key
  `RESOURCE_URI_META_KEY` (`"ui/resourceUri"`).
- `Apps.capability(mime_types:)` builds the `capabilities.extensions` fragment for
  `support_extensions` on the server or `connect` on the client.
- `Apps.ui_resource(uri:, name:, ...)` builds an `MCP::Resource` for a UI template,
  enforcing the spec's MUSTs (a `ui://` URI; the parameterized HTML MIME type by default).
- `Apps.tool_meta(resource_uri:, visibility:, meta:, legacy:)` builds the `_meta.ui.resourceUri`
  linkage (optionally also emitting the legacy flat alias, matching the reference server helper
  that keeps both shapes in sync), merged non-destructively into caller-supplied meta.
- `Apps.client_supports?(client_capabilities, mime_type:)` gates the text-only fallback
  the extension requires for clients that did not declare the capability (symbol/string tolerant).

Everything else the extension defines (the sandboxed iframe, the `ui/*` postMessage bridge methods,
consent for UI-initiated calls) is HOST responsibility and out of scope for a server SDK;
a server only ever receives ordinary `resources/read` and `tools/call` requests.
The README section states this boundary.

Resolves #376.

## How Has This Been Tested?

New `test/mcp/apps_test.rb` pins the wire vocabulary and covers the capability fragment,
`ui_resource` scheme validation and MIME default, `tool_meta` non-destructive merging,
visibility, the legacy alias, and `client_supports?` across symbol/string keys, mimeTypes narrowing,
and missing declarations.

New integration tests in `test/mcp/server_test.rb` drive a full server: the `initialize` result
advertises the extension, tools/list serializes `_meta.ui.resourceUri`, `resources/read` serves
the HTML template, and `client_supports?` distinguishes hosts with and without the declared extension.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes. Also verified end-to-end
over stdio: a client connecting with the extension declared negotiates the capability,
discovers the tool linkage via `_meta.ui.resourceUri`, and reads the `ui://` template
as `text/html;profile=mcp-app` content.

## Breaking Changes

None. Purely additive helper module; no existing code paths change.
2026-07-07 01:16:02 +09:00
Koichi ITO
267b8fa628 Bound stdio frame reads with max_line_bytes
## Motivation and Context

CRuby's `IO#gets` without a limit reads until the next newline with no upper bound.
A peer that never emits a newline can therefore grow a single String until the process
is killed by the OS OOM killer.

This is a denial-of-service exposure (GHSA-7683-3w9x-ch42), identified during
a cross-SDK audit of the same unbounded-buffer pattern across the MCP SDKs.
It is most relevant when a host application spawns a sandboxed or untrusted MCP server
and pipes its stdout into an unconstrained host process, where a memory-capped peer
can exhaust the host.

Each frame is now capped at a configurable `max_line_bytes` (default 4 MiB,
large enough for any realistic frame including base64-embedded images,
and the value recommended in the advisory). A frame that reaches the limit without
a newline is treated as a transport error: the client raises, and the server reports
the error and closes the connection. A short final frame that ends at EOF without
a trailing newline is still accepted, so legitimate traffic is unaffected.

Both constructors validate `max_line_bytes:` as a positive Integer,
since `nil` or a non-positive value makes `IO#gets` read without an upper bound and
would silently disable the protection.

## How Has This Been Tested?

Server tests cover the `open` read loop stopping and reporting on an over-limit frame,
the `send_request` read loop raising on an over-limit response, and a valid final frame
without a trailing newline still being processed.

Client tests cover `read_response` raising on an over-limit response frame and
a normal response still round-tripping within a custom `max_line_bytes`.

Both transports also have tests rejecting invalid `max_line_bytes:` values
(`nil`, zero, negative, non-Integer) with an `ArgumentError`.

The full test suite and RuboCop pass.

## Breaking Changes

None. The default 4 MiB limit is far larger than any realistic JSON-RPC frame,
so existing well-behaved traffic is unaffected. The new `max_line_bytes:` keyword
on both transport constructors is purely additive and optional.
2026-07-05 21:30:28 +09:00
Koichi ITO
afb968c468 Bound Stateful Session Retention to Prevent an Initialize-Flood DoS
## Motivation and Context

In its default configuration `StreamableHTTPTransport` never expired sessions: every successful `initialize` stored
a new `ServerSession` under a fresh UUID, and the only removal path was an explicit client DELETE. An unauthenticated attacker
could repeatedly initialize and immediately disconnect, forcing the server to retain an unbounded number of sessions until
memory is exhausted; the reporter created and held 50,000 sessions in 26.6 seconds from a single client.
The reaper existed but only started when `session_idle_timeout` was set, and there was no cap on the concurrent session count,
so the insecure behavior was the default.

Of the reference SDKs only C# hardens this by default (a finite idle timeout plus a max session count); TypeScript, Python,
and Go all leave sessions unbounded out of the box, and the spec permits (MAY) session expiry. This adopts secure defaults
in the same spirit as C#, with one deliberate difference at the cap (reject vs. evict, below):

- `session_idle_timeout` now defaults to a finite 1800 seconds (30 minutes) in stateful mode, so the existing reaper starts by default
  and idle sessions are reclaimed. Passing `session_idle_timeout: nil` opts out (the previous unbounded behavior); stateless mode
  retains no sessions and keeps no timeout regardless. An internal sentinel distinguishes "argument omitted, apply the default" from
  an explicit `nil`.
- A new `max_sessions` keyword (default 10000) caps the concurrent session count. `handle_initialization` checks and inserts under
  the existing mutex so concurrent initializes cannot race past the limit. At the cap it first reclaims slots held by already-expired sessions
  the 60s reaper has not yet collected (so the cap rejects only when genuinely full, not up to a reaper interval after sessions expired),
  and if still full rejects the new `initialize` with HTTP 503. Unlike the C# SDK, which evicts the oldest idle session, this rejects:
  established sessions stay stable and a legitimate idle session is not evicted on an attacker's behalf, at the cost of refusing new sessions
  while full; a global cap thus bounds memory but can convert the memory-exhaustion DoS into a session-slot-exhaustion DoS,
  which the idle timeout drains over time. Passing `max_sessions: nil` opts out; the cap does not apply to stateless mode.
  The value is validated as a positive Integer or `nil`.

## How Has This Been Tested?

New and updated tests in `test/mcp/server/transports/streamable_http_transport_test.rb`: the finite idle timeout is applied and
the reaper starts by default while normal request flow is unaffected, `session_idle_timeout: nil` and stateless mode both keep
no timeout/reaper, a new `initialize` at `max_sessions` is rejected with 503 while the store stays at the cap, an already-expired session
is reclaimed in-line so a new initialize succeeds at the cap instead of being rejected, `max_sessions: nil` opts out,
and an invalid `max_sessions` raises `ArgumentError`. The pre-existing test asserting the old never-expire default was rewritten to
the new secure default.

## Breaking Changes

Stateful deployments now expire sessions after 30 minutes of inactivity and reject new sessions past 10000 concurrent, where before sessions
lived until an explicit DELETE. This is a security-hardening behavior change, documented in the README; deployments that require
the old unbounded behavior can pass `session_idle_timeout: nil` and `max_sessions: nil`.
2026-07-05 19:39:56 +09:00
Koichi ITO
36ff2627e0 Bind Stored Client Credentials to the Authorization Server Issuer per SEP-2352
## Motivation and Context

SEP-2352 (modelcontextprotocol/modelcontextprotocol#2352, merged for the 2026-07-28 spec release) clarifies
authorization server binding and migration: clients MUST key persisted client credentials by the issuing
authorization server's issuer identifier, MUST NOT reuse credentials across different authorization servers,
and MUST re-register when the server's authorization server changes. CIMD `client_id`s (HTTPS URLs) are
explicitly portable across authorization servers, and a mismatch SHOULD surface an error rather than silently use
mismatched credentials.

The Ruby flow previously reused any stored `client_information` with a `client_id` unconditionally,
so a server that migrated to a new authorization server would have the old server's credentials
(and its dead tokens) replayed forever. This change follows the detect-change, invalidate,
and re-register approach that both reference SDKs converged on (typescript-sdk#2348/#2358, merged 2026-06-24;
python-sdk#2933/#2936/#2946, which uses the same proactive compare-before-reuse design as this change)
while keeping the 4-method storage contract intact by stamping the binding into the persisted hash:

- Successful Dynamic Client Registration now persists the credentials with an `"issuer"` member set to
  the validated AS metadata `issuer` (which `ensure_issuer_matches!` has already pinned to the discovery URL).
- `Flow#ensure_client_registered` reuses stored credentials only when the stored issuer matches the current one.
  Credentials without an issuer binding (data persisted by older SDK versions, or user-supplied pre-registered credentials)
  are bound to the current issuer on first use. A portable CIMD `client_id` is reused and re-bound.
  Any other issuer mismatch discards the stale registration and its tokens (tokens minted by the old AS are dead at the new one)
  and re-registers via CIMD/DCR.
- `Flow#refresh!` raises `AuthorizationError` instead of replaying another authorization server's credentials at the token endpoint;
  `MCP::Client::HTTP#attempt_refresh` already rescues that error and falls back to the full flow, which performs
  the discard-and-re-register.
- The `client_credentials` grant (machine-to-machine) reads static pre-registered credentials without going through
  `ensure_client_registered`, so it would have silently sent another authorization server's credentials after a migration.
  `run_client_credentials!` now surfaces an `AuthorizationError` when the stored `issuer` mismatches the current authorization server,
  implementing the spec's "SHOULD surface an error" (the TypeScript SDK raises `AuthorizationServerMismatchError` here).
  Re-registration is not an option for pre-registered m2m credentials, so the operator must update the stored credentials;
  credentials without a recorded issuer keep working unchanged.

Two adjacent hardenings from the reference implementations were checked and need no change here:
the legacy-fallback issuer stamp is self-consistent because this SDK's fallback registers at the same origin it
uses as the issuer (the cross-origin never-reached-AS binding python-sdk#2946 closed cannot arise),
and preserving a non-rotated `refresh_token` across refreshes already exists via `preserve_refresh_token`.
The TypeScript SDK's redirected-to-issuer callback gate is not adopted: the RFC 9207 `iss` validation (SEP-2468) covers that mix-up leg.

Resolves #385.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb`:

- stored credentials with a matching issuer skip DCR
- an issuer mismatch re-registers and persists the new `client_id` with the new issuer
- the stale registration's tokens are cleared before re-registration (observed by aborting the flow at the DCR step)
- legacy credentials without an issuer (string- and symbol-keyed) are reused and bound to the current issuer on first use
- a CIMD `client_id` with a mismatched issuer is reused without DCR and re-bound
- fresh DCR persists the issuer binding
- `refresh!` succeeds with a matching stored issuer and raises (without contacting the token endpoint) with a mismatched one
- the `client_credentials` grant succeeds with a matching stored issuer and raises (without contacting the token endpoint) with
  a mismatched one

All existing flow, HTTP OAuth, and provider tests pass unchanged.

## Breaking Changes

None for the documented storage contract: `client_information` hashes gain an additional `"issuer"` member that storages persist opaquely,
and credentials stored without one keep working via first-use binding. Behavior changes only in the previously broken case where
the authorization server changed, which now re-registers (or, for static machine-to-machine credentials, surfaces an error) instead of
replaying the old server's credentials.
2026-07-05 01:12:08 +09:00
Koichi ITO
c145876bb9 Add server/discover and stateless lifecycle error codes per SEP-2575
## Motivation and Context

SEP-2575 (modelcontextprotocol/modelcontextprotocol#2575, merged for the 2026-07-28 spec release)
makes MCP stateless, removing the `initialize`/`notifications/initialized` handshake in favor of
per-request `_meta`-carried negotiation. The full lifecycle rewrite is unmerged in both
the TypeScript SDK (the closed #2063/#2064/#2251 prototype stack, on hold since 2026-06-08) and
the Python SDK, but two pieces of its wire contract stayed stable across every prototype iteration
and are purely additive:

- The `server/discover` method, which servers MUST implement: sessionless capability discovery
  returning `supportedVersions`, `capabilities`, `serverInfo`, and `instructions`.
  The new `Server#discover` handler reuses the same data `init` already builds, but is state-free
  and idempotent: it stores no client info, never marks a session initialized, and responds regardless
  of declared capabilities or initialization state (added to the no-capability group in `Methods.ensure_capability!`).
  `serverInfo` is returned unfiltered because discovery precedes version negotiation;
  the draft's `ttlMs`/`cacheScope` fields on `DiscoverResult` are left to the SEP-2549 work.
  On `StreamableHTTPTransport`, a `server/discover` POST is exempt from the `Mcp-Session-Id` requirement
  and the `MCP-Protocol-Version` header check, like `initialize`, so clients can probe a server with
  a bare POST in both stateful and stateless modes.
- The error code vocabulary: the new `MCP::ErrorCodes` module exports `MISSING_REQUIRED_CLIENT_CAPABILITY = -32003`
  and `UNSUPPORTED_PROTOCOL_VERSION = -32004`. Constants only; nothing raises them yet
  (that belongs to the 2026-07-28 lifecycle work), and the existing inline `-32042` of
  `URLElicitationRequiredError` is intentionally left untouched.

The removal of `initialize`, `ping`, and `logging/setLevel` that SEP-2575 also specifies is
deliberately NOT implemented: the SDK targets protocol versions up to 2025-11-25,
where those methods are required.

Part of #389.

## How Has This Been Tested?

- `test/mcp/server_test.rb`: `server/discover` returns the supported versions, the server's capabilities,
  server info, and instructions; it responds before `initialize` and with empty capabilities;
  it does not mark the session initialized (a subsequent `initialize` still succeeds);
  `instructions` is omitted when the server has none; and `define_custom_method(method_name: "server/discover")`
  now raises `MethodAlreadyDefinedError`.
- `test/mcp/methods_test.rb`: `ensure_capability!` does not raise for `SERVER_DISCOVER` with empty capabilities.
- `test/mcp/server/transports/streamable_http_transport_test.rb`: a `server/discover` POST without a session ID
  returns 200 with the discover result in both stateful and stateless modes, without issuing an `Mcp-Session-Id`.
- New `test/mcp/error_codes_test.rb` pins the -32003/-32004 values.

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

None at the wire level for existing clients. One narrow API consequence: servers that previously registered
their own `"server/discover"` handler via `define_custom_method` now get `MethodAlreadyDefinedError` because
the method is built in.
2026-07-04 20:24:37 +09:00
Koichi ITO
8b1a41aedd
Merge pull request #437 from yuki3738/fix_tool_name_in_http_server_example
[Doc] Use registered callable names in examples/README.md
2026-07-03 02:09:59 +09:00
Yuki Minamiya
ac392cba55 [Doc] Use registered callable names in examples/README.md
The `tools/call` cURL example in `examples/README.md` uses `"name": "ExampleTool"`, but a tool registered by class without an explicit `tool_name` gets a snake_case name derived from its class name (via `StringUtils.handle_from_class_name`), so the example fails with `Tool not found: ExampleTool`. The Tools/Prompts lists in the same file had the same mismatch (`ExampleTool`, `ExamplePrompt`, `NotificationTool`). All entries now use the registered callable names.

How Tested: Ran `ruby examples/http_server.rb` and exercised the cURL flow. `tools/list` returned `example_tool` and `echo`; `tools/call` with `"name": "ExampleTool"` returned `Tool not found: ExampleTool`; with `"name": "example_tool"` returned `The sum of 5 and 3 is 8`. `prompts/list` returned `example_prompt`. The full unit suite and RuboCop pass locally.

Breaking Changes: None (documentation only).
2026-07-03 01:08:45 +09:00
Koichi ITO
3339ceb8c1 Add Opt-In ttlMs / cacheScope Cache Hints to List and Read Results per SEP-2549
## Motivation and Context

SEP-2549 (modelcontextprotocol/modelcontextprotocol#2549, merged for the 2026-07-28 spec release) adds a `CacheableResult`
shape with `ttlMs` (freshness lifetime in milliseconds, max-age semantics, 0 = do not cache) and `cacheScope`
(`"public"` or `"private"`, whether shared intermediaries may cache) to `ListToolsResult`, `ListPromptsResult`,
`ListResourcesResult`, `ListResourceTemplatesResult`, and `ReadResourceResult`, complementing the `listChanged` notifications.

The field shape follows the Python SDK's implementation (python-sdk#2824, `ttlMs` + `cacheScope` with `ttlMs: 0` /
`cacheScope: "public"` defaults; the TypeScript SDK's earlier `ttl`-seconds prototype #2070 was superseded by this shape).
Because this SDK negotiates protocol versions up to 2025-11-25, where the fields do not exist, emission is opt-in:
when neither `ttl_ms` nor `cache_scope` is configured, responses are serialized exactly as before. The fields become REQUIRED
in 2026-07-28; a follow-up can auto-emit defaults once that version enters `SUPPORTED_STABLE_PROTOCOL_VERSIONS`.

- `MCP::Server.new` gains `ttl_ms:` and `cache_scope:` keywords with validating writers modeled on `page_size=`
  (`ttl_ms` must be nil or a non-negative Integer; `cache_scope` must be nil, `"public"`, or `"private"`).
- A private `apply_cache_metadata` wraps the five emission points. When the user sets only one of the two values,
  the other is filled with the spec defaults (`ttlMs: 0`, the only universally safe freshness value, and `cacheScope: "public"`,
  the spec and Python default).
- A `resources_read_handler` may return a full `{ contents:, ttlMs:, cacheScope: }` hash to override the server-level hints per result;
  the documented bare-contents return shape keeps working unchanged.
- The client's `ListToolsResult` / `ListPromptsResult` / `ListResourcesResult` / `ListResourceTemplatesResult` structs gain
  `ttl_ms` and `cache_scope` members populated from the response fields.

Resolves #387.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb`:

- with `ttl_ms: 5000`, all four list results carry `ttlMs: 5000` and the filled `cacheScope: "public"` default
- with only `cache_scope: "private"`, `resources/read` carries `ttlMs: 0`
- with neither configured, list and read results omit both fields (wire-format regression)
- the hints appear alongside `nextCursor` when paginating
- a `resources_read_handler` returning `{ contents:, ttlMs: 60_000 }` overrides the server-level value while the missing `cacheScope` is filled
- invalid writer values (`-1`, `1.5`, `"internal"`) raise `ArgumentError`

New tests in `test/mcp/client_test.rb` assert all four list result structs expose `ttl_ms` / `cache_scope`,
and that both are nil when the server omits the fields.

## Breaking Changes

None. Emission is opt-in, the new constructor keywords default to nil, and the client structs gain additive members.
2026-07-02 17:51:01 +09:00
Koichi ITO
49d6d7f254
Merge pull request #435 from koic/fix_result_null_for_id_bearing_notification
Fix an incorrect `result: null` response to an id-bearing notification message
2026-07-02 07:40:40 +09:00
Koichi ITO
6d42cf7826 Fix an incorrect result: null response to an id-bearing notification message
## Motivation and Context

A JSON-RPC notification carries no id and must not receive any response.
When a client erroneously sent a notification-only method such as `notifications/cancelled` with an id,
the server replied with a successful `result: null`, which is neither a valid MCP result nor
a legal reply to a notification.

Such a message is now treated as a request for a method that has no request handler and rejected with
Method not found, matching the behavior of the TypeScript and Python SDKs. A well-formed notification
that omits the id continues to receive no response.

Fixes #434.

## How Has This Been Tested?

Added regression tests covering id-bearing `notifications/cancelled`, `notifications/initialized`,
and `notifications/progress`, a batch that mixes an id-bearing notification with other messages,
custom `notifications/*` methods, and the same case over the HTTP transport.

## Breaking Changes

None for spec-conformant clients, which never put an id on a notification.
The only behavioral change is that a malformed id-bearing notification now receives a Method not found error
instead of a spurious `result: null`.
2026-07-01 01:55:15 +09:00
Koichi ITO
4401833333 Recognize multi round-trip input_required results per SEP-2322
## Motivation and Context

SEP-2322 (modelcontextprotocol/modelcontextprotocol#2322, merged for the 2026-07-28 spec release)
introduces Multi Round-Trip Requests: instead of issuing in-flight server-to-client JSON-RPC requests,
a server answers with a result whose `resultType` is `"input_required"`, carrying an `inputRequests` map
(of `sampling/createMessage`, `roots/list`, and `elicitation/create` request shapes) and
an opaque `requestState`; the client fulfills the requests and re-issues the original request with
`inputResponses` and the echoed `requestState`.

The wire contract (the `resultType` discriminator and the `inputRequests`/`requestState` shape)
stayed stable across all three closed TypeScript prototype iterations (typescript-sdk#2062/#2065,
the v2-stateless stack, and #2251) and the Python draft (python-sdk#2322), but the server-side
suspend/resume mechanism is still unsettled in both SDKs (typescript-sdk#2251 was put on hold on 2026-06-08).
This change therefore implements only the stable, additive vocabulary and the client-side recognition,
leaving server emission and automatic resumption for a follow-up once the reference design lands:

- New `MCP::ResultType` module with `COMPLETE` and `INPUT_REQUIRED` constants documenting the `resultType` values.
- `MCP::Client` raises the new `MCP::Client::InputRequiredError` (exposing `input_requests`, `request_state`,
  and the raw `result`) when any response carries `resultType: "input_required"`, instead of silently returning
  a non-final result as if it were the answer. The check lives in the shared request path,
  so every client method is covered. Servers on stable protocol versions never emit `resultType`,
  so default behavior is unchanged.

Part of #382.

## How Has This Been Tested?

New tests in `test/mcp/client_test.rb`:

- `call_tool` raises `InputRequiredError` for an `input_required` result and exposes `input_requests`,
  `request_state`, and the full raw result
- `call_tool` returns normally when `resultType` is `"complete"` and when it is absent
  (wire-compat regression for stable-protocol servers)
- `list_tools` also raises for `input_required` results, proving the recognition covers the shared request path

`bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

None for spec-compliant stable servers, which never send `resultType`. A response that does carry
`resultType: "input_required"` now raises `MCP::Client::InputRequiredError` instead of being returned as
a final result, which was always a misinterpretation of the draft semantics.
2026-06-30 11:34:17 +09:00
Koichi ITO
4327fc8373 Support private_key_jwt Client Authentication for the client_credentials Grant
## Motivation and Context

The MCP `io.modelcontextprotocol/oauth-client-credentials` extension
(SEP-1046, modelcontextprotocol/modelcontextprotocol#1046) specifies
two client authentication methods for the `client_credentials` grant:
`client_secret_basic` and the RECOMMENDED `private_key_jwt`
(RFC 7523 Section 2.2 JWT client assertion). The previous commit added
the grant with secret-based authentication; this adds the JWT method,
which is what the `auth/client-credentials-jwt` conformance scenario exercises.

This mirrors the merged implementations in the TypeScript SDK
(`PrivateKeyJwtProvider`, typescript-sdk#1157) and the Python SDK
(`PrivateKeyJWTOAuthProvider` / `SignedJWTParameters`, python-sdk#1663),
adapted to this SDK's provider design:

- New `MCP::Client::OAuth::JWTClientAssertion` builds the RFC 7523 compact
  JWS with openssl, keeping the SDK free of a JWT gem dependency
  (the TypeScript and Python SDKs use jose and PyJWT). Claims follow SEP-1046:
  `iss` and `sub` carry the client_id, `aud` carries the authorization
  server's issuer identifier, plus `exp` (300-second lifetime, matching both SDKs),
  `iat`, and a unique `jti`. ES256 and RS256 are supported; ES256 signatures are
  converted from OpenSSL's ASN.1 DER form to the raw 64-byte `r || s` encoding
  JWS requires (RFC 7518 Section 3.4).
- `ClientCredentialsProvider` accepts
  `token_endpoint_auth_method: "private_key_jwt"` with `private_key:`
  (PEM string or `OpenSSL::PKey::PKey`) and a required `signing_algorithm:`
  (no default, so an algorithm mismatch with the server's
  `token_endpoint_auth_signing_alg_values_supported` fails loudly at construction;
  both reference SDKs also take the algorithm explicitly).
  The key stays on the provider and is never written to `storage`;
  a throwaway assertion is signed at construction to fail fast on an unparseable key
  or a key/algorithm mismatch.
- `Flow#post_to_token_endpoint` sends `client_assertion_type` and a freshly
  signed `client_assertion` for `private_key_jwt`,
  using the `ensure_issuer_matches!`-validated issuer as the audience,
  and omits `client_id` from the body per SEP-1046
  (identity travels in the assertion's claims).
- The conformance client builds a `private_key_jwt` provider
  when the harness injects `private_key_pem`, defaulting the algorithm to
  ES256 like the TypeScript and Python conformance clients,
  and `auth/client-credentials-jwt` is removed from
  `conformance/expected_failures.yml`.

Scope notes: only ES256 and RS256 are supported for now (the TypeScript and
Python SDKs accept whatever their JWT libraries support);
adding further algorithms is additive. There is also no injection point yet for
externally signed assertions (the TypeScript SDK's `StaticPrivateKeyJwtProvider` and
the Python SDK's `assertion_provider` callback cover KMS/HSM-held keys);
that is a separate follow-up.

## How Has This Been Tested?

New `test/mcp/client/oauth/jwt_client_assertion_test.rb` covers the JWS construction:
header and RFC 7523 claims, unpadded base64url segments,
ES256 signature round-trip verification (raw -> DER -> `OpenSSL::PKey::EC#verify`),
RS256 verification, PEM and parsed-key input, lifetime override, unique `jti` per assertion,
and rejection of unsupported algorithms, key/algorithm mismatches
(including a P-384 key with ES256), unparseable PEM, and public-only keys.

New tests in `test/mcp/client/oauth/client_credentials_provider_test.rb` cover
the provider surface: `private_key_jwt` construction, the key and
secret never reaching `client_information`, required `private_key` / `signing_algorithm`,
rejection of a simultaneous `client_secret`, fail-fast on key/algorithm mismatch,
and `client_assertion(audience:)` producing a JWT with the expected claims.

A new test in `test/mcp/client/oauth/flow_test.rb` runs the full grant against WebMock stubs
and asserts the token request carries `grant_type=client_credentials`,
the RFC 7523 `client_assertion_type`, an assertion whose `iss`/`sub` are the client_id
and whose `aud` is the issuer, the RFC 8707 `resource`, and neither `client_id` nor
any secret in the body or headers.

`bundle exec rake` passes; the `auth/client-credentials-jwt` conformance scenario
passes 7/7 checks and the baseline check passes with its expected-failure entry removed.

## Breaking Changes

None. `client_secret:` becomes optional on `ClientCredentialsProvider` only
in the signature; it is still required for the secret-based methods, and all
existing construction paths behave unchanged.
2026-06-28 20:59:37 +09:00
Koichi ITO
14b4f7c8c7 Validate the RFC 9207 iss Authorization Response Parameter per SEP-2468
## Motivation and Context

SEP-2468 (modelcontextprotocol/modelcontextprotocol#2468, merged for the 2026-07-28 spec release) recommends
that authorization servers include the RFC 9207 `iss` parameter in authorization responses and requires MCP clients
to validate a present `iss` against the expected issuer before redeeming the authorization code.
This mitigates mix-up attacks in multi-IdP setups, where an attacker-controlled authorization server could otherwise capture
a code minted by an honest server.

This mirrors the TypeScript SDK's approach (typescript-sdk#2272, with typescript-sdk#1957 as the reference implementation),
adapted to the Ruby provider contract:

- `Provider`'s `callback_handler` may now return `[code, state, iss]` in addition to the existing `[code, state]`.
  The 3-element form opts into validation; returning `iss = nil` asserts the caller inspected the authorization response
  and found no `iss`.
- `Flow#run!` validates the issuer after the `state` check and before `exchange_authorization_code`,
  implementing the RFC 9207 Section 2.4 rules: a present `iss` must equal the AS metadata `issuer` exactly
  (the value `ensure_issuer_matches!` already pinned to the discovery URL); a nil `iss` from a 3-element callback is rejected
  when the AS metadata advertises `authorization_response_iss_parameter_supported: true`; a legacy 2-element callback skips the check,
  so every existing integration keeps working. On any violation the flow aborts with `AuthorizationError` before
  the code reaches a token endpoint.
- The conformance client now returns the 3-element form, plumbing `iss` through from the redirect URL.

Resolves #386.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb`:

- a matching `iss` completes the flow and persists tokens
- a mismatched `iss` raises `AuthorizationError` and never contacts the token endpoint (`assert_not_requested` on the token POST)
- a nil `iss` with `authorization_response_iss_parameter_supported: true` raises without contacting the token endpoint (fail closed)
- a legacy 2-element callback completes even when the AS advertises `iss` support (backward compatibility)
- a nil `iss` without the advertisement completes
- a mismatched `iss` is rejected even without the advertisement (validate-when-present is unconditional)

`bundle exec rake` (tests, RuboCop, and conformance baseline with the 3-element conformance callback) passes.

## Breaking Changes

None. The 2-element `callback_handler` contract continues to work unchanged; issuer validation activates only
when a callback opts in by returning the 3-element form.
2026-06-28 20:40:29 +09:00
Koichi ITO
ba543083a7 Validate Host and Origin Headers to Prevent DNS Rebinding per MCP 2025-11-25
## Motivation and Context

MCP 2025-11-25 (modelcontextprotocol/modelcontextprotocol#1439) requires servers to validate
the `Origin` header on incoming Streamable HTTP connections and recommends binding only to localhost,
to prevent DNS rebinding attacks against locally bound MCP servers.
`StreamableHTTPTransport` previously validated neither `Host` nor `Origin`,
so a malicious web page could rebind its own hostname to 127.0.0.1 and reach a local server cross-origin,
invoking tools and exfiltrating their output. This is disclosed as GHSA-rjr6-rcgv-9m7m.

The TypeScript SDK (`enableDnsRebindingProtection` defaults to `false`, and is deprecated in favor of
external middleware) and the Python SDK (`transport_security.py` disables protection by default)
both ship this off for backwards compatibility, a constraint they cannot escape after 1.0.
Because this gem is still pre-1.0, it adopts the secure default now so protection is baked into the stable baseline:

- `Host` is validated against the loopback defaults (`127.0.0.1`, `::1`, `localhost`) plus any `allowed_hosts:`,
  compared case-insensitively; each entry matches the bare host name (any port) or a full `host:port`.
  This check is the primary anti-rebinding control, because a rebound request carries a foreign `Host`.
  A request without a `Host` header (e.g. HTTP/1.0) is allowed because the rebinding vector always sends one.
- `Origin`, when present, must be same-origin or in `allowed_origins:`. Same-origin compares authority (host:port)
  case-insensitively and uses the `Origin`'s own scheme to drop a redundant default port, so `http://example.com` matches
  `Host: example.com:80`. Non-browser MCP clients that send no `Origin` header are unaffected.
- `dns_rebinding_protection: false` disables the check when an upstream proxy or middleware already validates these headers.

A rejected request returns HTTP 403 with a JSON-RPC error response carrying no `id`, as the spec permits.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb`:

- a cross-origin `Origin` is rejected by default, and a same-origin browser request is allowed
- a rebound foreign `Host` is rejected with the `Invalid Host header` body, while loopback values
  (`127.0.0.1`, `localhost`, `[::1]`) are allowed
- an upper-cased loopback `Host` is accepted (case-insensitive matching)
- a non-loopback `Host` listed in `allowed_hosts:` is allowed
- a request with no `Host` header, and one with no `Origin` header, are allowed
- a default-port `Origin` (`http://localhost`) matches `Host: localhost:80`
- opaque and malformed `Origin`s (`null`, `file://`, a path suffix) are rejected
- a `host:port` `allowed_hosts:` entry matches that port only
- `Host` validation also applies to GET requests
- `dns_rebinding_protection: false` lets a forged `Host`/`Origin` through

## Breaking Changes

`StreamableHTTPTransport` now rejects non-loopback `Host` and cross-origin `Origin` requests by default.
A deployment behind a reverse proxy or bound to a non-loopback interface must set `allowed_hosts:` / `allowed_origins:`,
or pass `dns_rebinding_protection: false` when validation is handled upstream. Loopback servers and non-browser clients
are unaffected.

Co-authored-by: tonghuaroot <tonghuaroot@gmail.com>
2026-06-28 12:06:13 +09:00
Koichi ITO
cb0eb3892b Support SSE Reconnection Per SEP-1699 in the HTTP Client Transport
## Motivation and Context

Resolves the `sse-retry` client conformance scenario (SEP-1699,
https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1699).

Per SEP-1699, a server may close a request's SSE stream right after a priming event
(an event carrying an `id:`) without delivering the response, expecting the client
to treat the graceful close like a network failure: wait the server-specified
`retry:` interval, then reconnect with an HTTP GET carrying `Last-Event-ID`
so the server can replay the pending response on the resumed stream.

The Ruby client previously read the entire SSE body to EOF and parsed it afterward,
so it had no notion of per-event state (`id:`, `retry:`) or reconnection,
and the scenario failed all three checks (graceful reconnect, retry timing, `Last-Event-ID`).

`MCP::Client::HTTP#send_request` now consumes responses incrementally
via Faraday's `on_data` streaming callback, feeding SSE chunks to `event_stream_parser`
as they arrive while buffering plain JSON bodies as before. A new internal `SSEStream`
tracks the last received event id, the `retry:` reconnection delay,
and the awaited JSON-RPC response; once the response arrives, a held-open stream is
abandoned via an internal control-flow exception since servers may never close it.
When a stream closes gracefully after a priming event but before the response,
the client sleeps for the `retry:` interval (default 1000ms when the server sent none),
then issues a GET with `Accept: text/event-stream`, the session headers, and `Last-Event-ID`,
for up to 2 attempts. The defaults match the Python SDK's `DEFAULT_RECONNECTION_DELAY_MS` and
`MAX_RECONNECTION_ATTEMPTS` (`streamable_http.py`); the TypeScript SDK's `StreamableHTTPClientTransport`
(`streamableHttp.ts`) likewise lets the `retry:` field override its backoff and reconnects only when
a priming event was received and no response has arrived.

The public behavior of `send_request` is unchanged: same return values, same error mapping,
and a stream that closes without a priming event still raises the "No valid JSON-RPC response found in SSE stream" error
without reconnecting. Because the previous implementation read `response.body` and therefore worked with any Faraday adapter,
a fallback keeps that compatibility: when nothing was parsed during streaming, the body is read from `response.body`
(adapters without `on_data` support, e.g. the Faraday test adapter) or from the buffered chunks
(Faraday < 2.1, which invokes `on_data` without `env`).

The conformance client gains an `sse-retry` branch that calls the harness's `test_reconnection` tool,
and the scenario is removed from the expected failures baseline.

## How Has This Been Tested?

New unit tests covering: reconnection with `Last-Event-ID` after a primed graceful close including the `retry:` wait,
the default 1000ms delay when `retry:` is absent, raising after the reconnection attempt cap with `Last-Event-ID`
advancing across attempts, no reconnection for unprimed streams, and the non-streaming fallbacks
(JSON and SSE responses through the Faraday test adapter, which ignores `on_data`, plus buffered SSE chunks
when `on_data` receives no `env`)

## Breaking Changes

None. The `send_request` contract is unchanged; SSE bodies are now parsed incrementally instead of after EOF,
and reconnection only activates when the server opts in by sending a priming event.
2026-06-28 11:56:02 +09:00
Koichi ITO
5518e8db03
Merge pull request #429 from atesgoral/issue-390-deprecation-annotations
docs: annotate Roots, Sampling, and Logging as deprecated per SEP-2577
2026-06-28 01:46:01 +09:00
Koichi ITO
b7bd9bb556
Merge pull request #427 from koic/require_connect_stdio
Require calling `MCP::Client#connect` before sending requests on stdio transport
2026-06-28 01:43:07 +09:00
Ates Goral
69bfe436b7 docs: annotate Roots, Sampling, and Logging as deprecated per SEP-2577
Split the advisory YARD @deprecated annotations out of #406 so the
documentation can land ahead of the 2026-07-28 protocol release.

Per maintainer feedback, this drops the protocol-version-gated runtime
Kernel.warn behavior and the new 2026-07-28 supported protocol version,
leaving only the @deprecated notes for the Roots, Sampling, and Logging
APIs deprecated by SEP-2577.

Refs #390

Co-authored-by: 🦞 Qlaw <noreply@qlaw.quick.shopify.io>
2026-06-27 14:02:27 +02:00
Koichi ITO
58d5175364
Merge pull request #428 from koic/release_0_22_0
Release 0.22.0
2026-06-27 08:23:46 +09:00
Koichi ITO
f739a4b8e8 Release 0.22.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-06-27 02:54:30 +09:00
Koichi ITO
d6a368a54f Require calling MCP::Client#connect before sending requests on stdio transport
## Motivation and Context

The MCP specification requires an `initialize` request followed by `notifications/initialized`
before any other interaction. Issue #334 makes that handshake explicit on the stdio client,
matching the Python SDK (`ClientSession.initialize()`) and TypeScript SDK (`Client.connect(transport)`).

The change was staged to avoid a hard break. Phase 1 (#336) added `MCP::Client::Stdio#connect`
while keeping an implicit-init compatibility shim on the first `send_request`.
Phase 2 (#338) emitted a deprecation warning when that shim ran. The warning has shipped since 0.16.0,
so this final phase removes the shim.

## How Has This Been Tested?

`send_request` now raises a `RuntimeError` when `connect` has not been called, and no longer
auto-starts the subprocess. `connect` is the sole entry point that spawns the process and
performs the handshake, which avoids leaving an orphaned subprocess behind.

The stdio test suite was reworked to call `connect` explicitly, a regression test was added for
the new guard, and `rake test` passes (1145 runs, 0 failures).

## Breaking Changes

Stdio clients that send requests without calling `MCP::Client#connect` now raise a `RuntimeError`
instead of silently initializing. Call `client.connect` before the first request.

Closes #334
2026-06-26 13:34:47 +09:00
Koichi ITO
0694e386db
Merge pull request #423 from koic/sep_2243_mcp_method_name_headers
Send SEP-2243 `Mcp-Method` and `Mcp-Name` headers per MCP specification
2026-06-25 01:27:33 +09:00
Koichi ITO
a284bf7314 Send SEP-2243 Mcp-Method and Mcp-Name headers per MCP specification
## Motivation and Context

The MCP specification (SEP-2243) requires the Streamable HTTP transport to mirror
selected JSON-RPC body fields into HTTP headers so that intermediaries such as load balancers,
gateways, and observability tooling can route and inspect requests without parsing the body.
`Mcp-Method` carries the JSON-RPC `method` and is required on all requests and notifications,
while `Mcp-Name` carries `params.name` (`tools/call`, `prompts/get`) or `params.uri` (`resources/read`).

The Ruby SDK client did not send these headers, so servers enforcing SEP-2243 rejected
its requests with `400 Bad Request`, breaking interoperability. This aligns the Ruby SDK with
the TypeScript and Python SDKs, both of which send these headers from their Streamable HTTP clients.

Header values that cannot be transmitted safely as-is, such as non-ASCII text, control characters
(including CR/LF, which would otherwise allow header injection), or significant leading or
trailing whitespace, are wrapped per SEP-2243 as `=?base64?<base64>?=`. Safe ASCII values are sent unchanged.
The encoding uses `Array#pack("m0")` to avoid depending on the `base64` gem.

Resolves #366

## How Has This Been Tested?

Client tests cover deriving `Mcp-Name` from `params.name` (`tools/call`, `prompts/get`) and
falling back to `params.uri` (`resources/read`), both symbol- and string-keyed params,
requests and notifications without a name or uri sending only `Mcp-Method`, and non-Hash params sending
only `Mcp-Method`. Value encoding is covered for non-ASCII names, surrounding whitespace, CR/LF
(verifying no header injection), and values that already match the `=?base64?...?=` sentinel.

## Breaking Changes

None. The change is purely additive: existing requests now carry the required `Mcp-Method` and `Mcp-Name` headers
alongside the headers already sent. The `x-mcp-header` / `Mcp-Param-*` custom headers remain out of scope,
matching the current state of the TypeScript and Python SDKs.
2026-06-24 14:04:36 +09:00
Koichi ITO
7e878827ae
Merge pull request #417 from koic/json_schema_2020_12_tool_schemas
Conform Tool Schemas to JSON Schema 2020-12 per SEP-2106
2026-06-24 13:39:16 +09:00
Koichi ITO
817b8f4d83
Merge pull request #425 from koic/feature_cancellation_for_client
Support client-side `notifications/cancelled` per MCP specification
2026-06-24 13:38:18 +09:00
Koichi ITO
b1a31ee143
Merge pull request #424 from modelcontextprotocol/dependabot/github_actions/actions/checkout-7
Bump actions/checkout from 6 to 7
2026-06-23 12:43:27 +09:00
Koichi ITO
a4cd7c8cde Support client-side notifications/cancelled per MCP specification
## Motivation and Context

The server-side half of MCP `notifications/cancelled` shipped earlier and lets handlers
observe cancellation via `server_context.cancelled?` / `raise_if_cancelled!`.
This PR delivers the client-side equivalent that was deferred at the time:
an `MCP::Client` user can now cancel a request they have already issued and have
the calling thread wake up, matching the Python SDK
(`anyio.CancelScope`) and TypeScript SDK (`AbortSignal`) ergonomics.

The recommended pattern is to pass an `MCP::Cancellation` token into the request method,
run the request on a worker thread, and call `cancellation.cancel(reason:)` from another thread.
The cancelling thread sends `notifications/cancelled` to the server, and the calling thread is
woken up with `MCP::CancelledError`:

```ruby
cancellation = MCP::Cancellation.new
Thread.new do
  client.call_tool(name: "slow_tool", arguments: {}, cancellation: cancellation)
rescue MCP::CancelledError
  # cleanup
end
cancellation.cancel(reason: "user pressed cancel")
```

For low-level use, `Client#cancel(request_id:, reason:)` sends the notification without managing
the calling thread, and `Client#generate_request_id` lets callers pre-allocate an id before kicking off
a request on another thread. The `request_id:` and `cancellation:` keywords are accepted by
every request method (`tools`, `list_tools`, `resources`, `list_resources`, `resource_templates`,
`list_resource_templates`, `prompts`, `list_prompts`, `call_tool`, `read_resource`, `get_prompt`,
`complete`, `ping`).

When `cancellation:` is supplied, the actual blocking `transport.send_request` runs on a worker thread;
the calling thread waits on a `Queue` woken either by the response or by the cancel signal
(whichever arrives first - the same race contract as the server-side `StreamableHTTPTransport#cancel_pending_request`).
On a normal completion the `on_cancel` hook is deregistered so a late cancel does not emit a stray `notifications/cancelled`.
The worker thread is *not* force-killed when a cancel wins the race; it stays blocked on the underlying I/O until
the transport actually returns (or the user closes it). For `Client::HTTP` the leak resolves as soon as
the server sends any response; for `Client::Stdio` the user may need to call `client.transport.close`
if the server stops responding entirely.

`Client::Stdio` and `Client::HTTP` gain `send_notification(notification:)` so `Client#cancel` can deliver
the JSON-RPC notification through the existing transport plumbing. Custom transports that do not implement
`send_notification` cause `Client#cancel` to raise `NoMethodError`.

Ref: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation

## How Has This Been Tested?

`test/mcp/client_test.rb` covers `Client#cancel` payload (with and without `reason`),
`Client#generate_request_id` returning distinct UUIDs, every request method threading `request_id:` through,
and the full `cancellation:` flow:

- Returns the response when no cancel happens (no behaviour regression for callers that do not pass a token).
- Pre-cancelled token raises `MCP::CancelledError` immediately and never reaches the transport
  (no stray request, no stray notification).
- Mid-flight cancel raises `MCP::CancelledError` carrying the supplied reason and sends `notifications/cancelled`
  through the transport.
- Late cancel after a normal completion does not emit a stray notification
  (the `on_cancel` hook is deregistered in the `ensure` block).

`test/mcp/client/stdio_test.rb` covers `send_notification` writing the JSON line through the spawned process
and returning `nil` without waiting for a response.

`test/mcp/client/http_test.rb` covers `send_notification` POSTing the body, tolerating HTTP 202 Accepted,
and surfacing Faraday errors as `RequestHandlerError`.

## Breaking Change

None. All new keywords (`request_id:`, `cancellation:`) on request methods are optional and default to `nil`.
Existing callers that do not pass them get the original synchronous behaviour. Custom transports that already
implement `send_request(request:)` continue to work; only callers of `Client#cancel` need a transport
that responds to `send_notification`, and the failure mode is a clear `NoMethodError` rather than silent breakage.
2026-06-23 12:39:53 +09:00
dependabot[bot]
da8e7e5363
Bump actions/checkout from 6 to 7
Bumps [actions/checkout](https://github.com/actions/checkout) from 6 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-22 20:13:56 +00:00
Koichi ITO
6bf0a069b5
Merge pull request #422 from yuki3738/add_audience_validation_to_annotations
Add `audience` role validation for `MCP::Annotations` per MCP specification
2026-06-22 02:37:17 +09:00
Yuki Minamiya
4c3268ccb1 Add audience role validation for MCP::Annotations per MCP specification
The MCP specification constrains `Annotations.audience` to an array of
`Role` values (`"user"` or `"assistant"`), but the Ruby SDK accepts any
value. The other official SDKs already enforce this (TypeScript, Python,
and PHP).

This follows the existing pattern in `MCP::Icon`, which validates its
constrained `theme` value in the constructor and raises `ArgumentError`.

Added tests in `test/mcp/annotations_test.rb`:

- valid `audience` (`["user"]`, `["assistant"]`, `["user", "assistant"]`,
  and an empty array) is accepted
- an unknown role, a mixed valid/invalid array, or a non-array `audience`
  raises `ArgumentError`

Existing tests used `["developers"]`, which is not a valid `Role`, and are
updated to `["user"]`.

The full unit suite and RuboCop pass locally.

Strictly speaking this is a breaking change: a caller that currently passes
an invalid `audience` (e.g. `["developers"]`) will now get an
`ArgumentError`. Such values already violate the MCP specification, and
`nil` / valid-role values are unaffected.
2026-06-22 01:13:17 +09:00
Koichi ITO
dc26613a07
Merge pull request #419 from koic/fix_syntax_error_on_ruby_2_7_0
Fix a `SyntaxError` on Ruby 2.7.0 caused by arguments forwarding syntax
2026-06-21 01:07:18 +09:00
Koichi ITO
db460e5f47
Merge pull request #420 from koic/release_0_21_0
Release 0.21.0
2026-06-20 22:15:29 +09:00
Koichi ITO
c4c73e05f5 Fix a SyntaxError on Ruby 2.7.0 caused by arguments forwarding syntax
## Motivation and Context

The gemspec already declares `required_ruby_version >= 2.7.0`, but `ServerContext` used
the `...` arguments forwarding syntax in `method_missing`. That syntax was added in Ruby 2.7.3,
so requiring the gem raised a `SyntaxError` on Ruby 2.7.0 through 2.7.2, and the library could not
be loaded at all.

RuboCop did not catch this because its Parser backend runs on Ruby 2.7.8, where the syntax is valid.
CI missed it too because the test matrix tested `2.7`, which resolves to the latest 2.7.x rather than
the declared minimum.

## How Has This Been Tested?

Forward arguments explicitly with `*args, **kwargs, &block` so the method loads on Ruby 2.7.0,
and pin the CI test matrix to 2.7.0 so the suite runs against the declared minimum instead of
the latest 2.7.x.

Running the suite on 2.7.0 also requires a `Hash.ruby2_keywords_hash?` shim in the test helper,
since mocha would otherwise raise a `NoMethodError` on that version.

## Breaking Changes

None.

Closes #418
2026-06-20 01:01:07 +09:00
Koichi ITO
49a08bf3be Release 0.21.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-06-20 01:00:18 +09:00
Koichi ITO
5ca8b6ebbb Conform Tool Schemas to JSON Schema 2020-12 per SEP-2106
## Motivation and Context

SEP-2106 (modelcontextprotocol/modelcontextprotocol#2106, merged for the 2026-07-28 spec release)
makes tool `inputSchema` and `outputSchema` conform to the full JSON Schema 2020-12 vocabulary:
an input schema keeps `type: "object"` at the root but may use any 2020-12 keyword below it;
an output schema may be ANY valid schema (object, array, primitive, or a root-level composition);
and `CallToolResult.structuredContent` widens from an object to any JSON value. The SEP also adds
resource bounds: `$ref` resolution is restricted (same-document only in the reference implementation) and
composition-heavy documents must be bounded to avoid excessive validation cost.

This follows the TypeScript SDK's reference implementation (typescript-sdk#2249; the Python SDK tracks
the same work in python-sdk#2792):

- `Tool::Schema` now validates against the JSON Schema 2020-12 metaschema rather than the draft-04 metaschema.
  The draft-04 pin was a stopgap from when the SDK used the `json-schema` gem, which did not support 2020-12;
  `json_schemer` does, so `$defs`/`$ref` and the rest of the 2020-12 vocabulary now resolve natively.
  This matches the dialect the SDK already advertises in emitted schemas and the Python SDK's behavior,
   whose `jsonschema.validate` selects the validator from the schema's `$schema`.
- `Tool::Schema` moves root-type defaulting into an overridable `apply_default_root_type!` hook.
  `InputSchema` keeps the historical `type: "object"` default; `OutputSchema` now applies it only
  when no root schema keyword (`type`, `$ref`, `oneOf`, `anyOf`, `allOf`, `not`, `if`, `const`, `enum`) is present.
  The previous unconditional default merged `type: "object"` into root combinators such as `{ oneOf: [...] }`,
  producing a wrong schema, so that case is a bug fix.
- `Tool::Schema` enforces the TypeScript SDK's schema bounds at construction time: only same-document
  `$ref`/`$dynamicRef`s (starting with `#`, so schema handling can never trigger network or file access),
  `MAX_SCHEMA_DEPTH = 64` nesting levels, and `MAX_SUBSCHEMA_COUNT = 10_000` subschema objects,
  all raising `ArgumentError` on violation.
- `Server#call_tool` mirrors non-object `structuredContent` into `content` as serialized JSON text
  when the tool provided no content blocks, so pre-SEP clients that only read `content` still receive the data.
  Object results and explicit content are untouched.

Resolves #377.

## How Has This Been Tested?

- `test/mcp/tool/output_schema_test.rb`: root-level `oneOf`, `$ref`+`$defs`, primitive, and `enum` schemas serialize
  without an injected `type` and validate results correctly; the `properties`-only shorthand still serializes
  with `type: "object"` (wire-format regression); explicit `type: "array"` keeps working.
- `test/mcp/tool/input_schema_test.rb`: an input schema using `$defs`, `$ref`, `oneOf`, `if`/`then`, and `allOf`
  keeps its object root and round-trips all keywords; a draft-04-only boolean `exclusiveMinimum` is rejected
  under the 2020-12 dialect while the numeric form is accepted.
- `test/mcp/tool/schema_test.rb`: depth and subschema-count bound violations raise `ArgumentError`;
  non-same-document `$ref`s (remote URI, sibling file) are rejected while `#/$defs/...` is accepted.
  The previous unbounded-depth caching test is replaced, since the depth bound now rejects such documents by design.
- `test/mcp/server_test.rb`: `tools/call` with array `structuredContent` and no content gains
  the serialized TextContent fallback; explicit content is not overwritten; object `structuredContent` gets no fallback.

`bundle exec rake` (tests, RuboCop, and conformance baseline, including the `json-schema-2020-12` server scenario) passes.

## Breaking Changes

Three narrow behavior changes, all intentional per the SEP:

- Runtime validation now uses the JSON Schema 2020-12 metaschema instead of draft-04.
  Schemas that rely on draft-04-only syntax are rejected at construction time. The practical case is the boolean
  `exclusiveMinimum`/`exclusiveMaximum` form (deprecated since draft-06), which must now be the numeric form;
  the Python SDK rejects it the same way. Other draft-04 spellings (`definitions`, `id`, `dependencies`) still validate,
  since 2020-12 tolerates unknown keywords.
- Schemas that exceed the new resource bounds (nesting deeper than 64, more than 10,000 subschema objects) or
  use a non-same-document `$ref`/`$dynamicRef` now raise `ArgumentError` at construction time.
  Previously such documents were accepted (external references were already never fetched, only ignored).
- An `OutputSchema` whose root declares a schema keyword other than `type` (e.g. `oneOf`) no longer has  `type: "object"`
  merged into it. The old output was an invalid hybrid schema, so no conforming consumer could have relied on it.
2026-06-19 21:36:55 +09:00
Koichi ITO
217542f812
Merge pull request #416 from koic/fix_a_build_error
Fix a build error in the Ruby 3.1 CI matrix
2026-06-19 21:30:36 +09:00
Koichi ITO
cfc9a699d6 Fix a build error in the Ruby 3.1 CI matrix
## Motivation and Context

This resolves the following build failure that occurs when using Ruby 3.1 with I18n 1.15.0:

```console
$ bundle exec rake
(snip)

/Users/koic/.rbenv/versions/3.1.5/lib/ruby/gems/3.1.0/gems/i18n-1.15.0/lib/i18n.rb:58:
in `config': undefined method `[]' for Fiber:Class (NoMethodError)

      current = Fiber[:i18n_config] || self.config = I18n::Config.new
                     ^^^^^^^^^^^^^^
        from /Users/koic/.rbenv/versions/3.1.5/lib/ruby/gems/3.1.0/gems/i18n-1.15.0/lib/i18n.rb:88:in `load_path'
```

https://github.com/modelcontextprotocol/ruby-sdk/actions/runs/27724973112/job/82025136923

According to the report in https://github.com/ruby-i18n/i18n/issues/735,
this issue has been fixed in I18n 1.15.1 and later.
However, the already released I18n 1.15.0 still triggers the build error.

While this could potentially be addressed in a better way on the I18n side,
this change updates the Gemfile to avoid using I18n 1.15.0, which is known to cause the issue.

## How Has This Been Tested?

The build error described above has been resolved.

## Breaking Changes

None.
2026-06-18 09:20:59 +09:00
Koichi ITO
c8e0cd9562
Merge pull request #415 from koic/stateless_session_isolation
Isolate Stateless Requests in Ephemeral Sessions per SEP-2567
2026-06-18 07:55:01 +09:00
Koichi ITO
aac41cdff8
Merge pull request #408 from koic/dcr_application_type
Set OIDC `application_type` on Dynamic Client Registration per SEP-837
2026-06-17 10:57:19 +09:00
Koichi ITO
60f0088877
Merge pull request #414 from koic/2025_03_26_backcompat
Fall Back to Legacy 2025-03-26 OAuth Discovery for Servers Without PRM
2026-06-17 10:49:00 +09:00
Koichi ITO
2c223dd2f0 Fall Back to Legacy 2025-03-26 OAuth Discovery for Servers Without PRM
## Motivation and Context

The MCP 2025-03-26 authorization spec predates Protected Resource Metadata:
the MCP server itself acted as the authorization base URL, its RFC 8414 metadata was fetched from
the server origin, and the spec's "Fallbacks for Servers without Metadata Discovery" section
required clients to use the default endpoints `/authorize`, `/token`, and `/register` relative to
the authorization base URL when no metadata was published. Both the TypeScript SDK
(`discoverOAuthServerInfo` falls back to the server base URL on PRM failure; `startAuthorization` /
`executeTokenRequest` / `registerClient` default the endpoint paths) and the Python SDK
(`build_oauth_authorization_server_metadata_discovery_urls(None, ...)` plus the same endpoint defaults)
keep this as client-side backwards compatibility, and the `auth/2025-03-26-oauth-metadata-backcompat` and
`auth/2025-03-26-oauth-endpoint-fallback` conformance scenarios exercise it.

The Ruby flow previously raised as soon as PRM discovery failed, so both scenarios were
expected conformance failures. This change adds the same fallback:

- `Flow#locate_authorization_server` first attempts PRM discovery; on any discovery failure
  (404s, network errors, malformed documents, matching the TypeScript and Python SDKs' broad fallback)
  the MCP server's origin becomes the legacy authorization base URL. The Communication Security check
  (HTTPS or loopback) still applies to that origin, and PRM documents that parse correctly keep
  their strict shape validation.
- `Flow#authorization_server_metadata` fetches RFC 8414 metadata from the base URL.
  On the legacy path the `issuer` byte-match is skipped: the 2025-03-26 spec predates that requirement,
  and a pre-PRM server may host its OAuth endpoints under a path prefix whose `issuer` legitimately differs
  from the discovery origin (neither reference SDK validates the issuer on this path). On the modern path
  the byte-match is unchanged.
- When even the metadata document is absent, synthetic metadata carrying the legacy spec's default endpoints
  is used, with PKCE S256 assumed (the legacy spec mandates PKCE; the TypeScript and Python SDKs hardcode S256
  on this path too). Endpoint HTTPS checks still apply.
- `run!` and `refresh!` share the new discovery helpers, and both 2025-03-26 scenarios are removed from
  `conformance/expected_failures.yml`.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/flow_test.rb`:

- the metadata-backcompat shape: no PRM, AS metadata at the server origin with `/oauth`-prefixed endpoints
  and a mismatched `issuer` completes the flow against those endpoints (no issuer error)
- the endpoint-fallback shape: no metadata at all registers, authorizes, and exchanges the code at `/register`,
  `/authorize`, and `/token` on the origin, still sending `code_challenge` (S256) and `code_verifier`
- a remote plain-http origin is rejected as the legacy authorization base
- strict-mode regression: with PRM present, a mismatched `issuer` still aborts the flow
- a malformed PRM (top-level JSON array) now selects the legacy path instead of leaking a `TypeError`,
  and surfaces a domain error when that path also dead-ends

Two existing tests that asserted PRM failure was terminal were updated to dead-end the legacy path explicitly,
preserving their original intent (single flow attempt, domain error type).

## Breaking Changes

None for spec-compliant 2025-06-18+ servers, whose PRM-based discovery and issuer validation are unchanged.
Servers that previously failed hard during PRM discovery now get one legacy discovery attempt before the flow errors,
which can only turn previously failing flows into working ones.
2026-06-16 17:48:18 +09:00
Koichi ITO
eb6ff5d805 Isolate Stateless Requests in Ephemeral Sessions per SEP-2567
## Motivation and Context

SEP-2567 (modelcontextprotocol/modelcontextprotocol#2567, merged for the 2026-07-28 spec release)
makes MCP sessionless: every Streamable HTTP POST must be fully self-contained,
with no protocol-level session state shared between requests.

`StreamableHTTPTransport` already implements the SEP's transport surface via
`stateless: true` (no `Mcp-Session-Id` issued or required, GET returns 405,
DELETE is a no-op, server-to-client requests raise), but its dispatch had a state leak:
stateless POSTs were handled with `session: nil`, so `Server#init` wrote `@client` and
`@client_capabilities` onto the shared `Server` instance.
Concurrent stateless requests could therefore observe another client's identity,
and the data persisted across requests, which is exactly what SEP-2567 forbids.
The TypeScript SDK's stateless prototypes (the closed typescript-sdk#2058/#2131/#2251 stack)
solve this with per-request dispatch; this change applies the equivalent fix within the existing architecture:

- Stateless `handle_initialization`, `handle_regular_request`, and `dispatch_notification` now
  run handlers against an ephemeral per-request `ServerSession` (with `session_id: nil`),
  so client info, logging level, and initialized state live only for the duration of that POST.
  Repeated `initialize` requests are naturally permitted because each POST gets a fresh,
  never-initialized session.
- `send_notification` in stateless mode now returns `false` (non-delivery) instead of raising.
  With ephemeral sessions in place, a tool calling `server_context.report_progress` or `notify_log_message`
  would otherwise route every call into the exception reporter; non-delivery matches how
  these helpers already degrade when no session exists. `send_request` (server-to-client requests) still raises,
  as those are genuinely unsupported without a stream.

Resolves #388.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb`:

- a stateless `initialize` POST leaves `Server#client_capabilities` and the server's `@client` untouched
  (the leak regression)
- repeated `initialize` POSTs both succeed with 200 and no `Mcp-Session-Id` header
- a tool calling `server_context.report_progress` under stateless mode returns its result normally and
  the exception reporter is never invoked
- the existing "stateless mode does not support server-sent events" test is updated to assert
  the new `false` return instead of the removed raise

All other existing stateless-mode tests pass unchanged.

## Breaking Changes

`StreamableHTTPTransport#send_notification` in stateless mode now returns `false` instead of raising `RuntimeError`.
The raise message was not a documented contract, broadcasting in stateless mode was always a non-deliverable operation,
and the boolean return matches the method's documented semantics in every other non-delivery case.
Default (session-oriented) mode is unchanged.
2026-06-16 11:13:15 +09:00
Koichi ITO
a0cd66287d
Merge pull request #413 from koic/document_tool_argument_symbol_keys
Document That Tool Arguments Arrive with Symbol Keys
2026-06-16 10:35:12 +09:00
Koichi ITO
2c295fe930 Document That Tool Arguments Arrive with Symbol Keys
## Motivation and Context

The transports parse incoming JSON with `symbolize_names: true`, so a tool receives every key,
at every nesting level, as a Ruby symbol. The dispatch in `call_tool_with_args` only runs
a shallow `transform_keys(&:to_sym)`, which is effectively a no-op given the deep parse upstream.
Nothing in the SDK exercised that delivered shape: the README and examples take flat or primitive arguments,
and the tool tests invoke `call` with Ruby keyword arguments, so none go through the JSON parse to dispatch path.
A tool that reads a nested object with string keys (`payload["subject"]`) therefore passes its tests and then
returns nil against a real client.

Ruby keyword arguments bind only on symbol keys, so the top-level keys must be symbols for
the ergonomic `def call(message:, ...)` API to work. Aligning fully with the JSON wire shape that the spec and
the Python and TypeScript SDKs use (string keys) is not possible without a breaking change to that API.
This change therefore documents the existing contract rather than altering behavior.

Closes #412

## How Has This Been Tested?

New regression tests in `test/mcp/server_test.rb`:

- `tools/call` through the full `handle_json` path delivers nested object arguments with symbol keys at every level,
  and string-key access on a nested value returns nil.
- A tool called under the JSON-round-tripped argument shape receives symbol keys, mirroring what a transport hands it at runtime.

## Breaking Changes

None. This is a documentation and test change with no behavior change.
The `lib/mcp/server.rb` edit is a clarifying comment on the existing key handling.

## Additional context

Making nested objects tolerant of both string and symbol keys (indifferent access) is a possible future improvement
that would remove the footgun and move closer to the other SDKs. It is intentionally left out of scope here and
can be designed separately, since it is a behavior and dependency decision rather than a documentation fix.
2026-06-16 03:09:55 +09:00
Koichi ITO
95cfe4993b
Merge pull request #409 from atesgoral/test-close-stdio-stderr-pipe
test: close stdio stderr pipe
2026-06-16 00:59:49 +09:00
Koichi ITO
acec71df74
Merge pull request #410 from yuki3738/add_priority_validation_to_annotations
Add range validation for `MCP::Annotations#priority` per MCP specification
2026-06-16 00:55:55 +09:00
Yuki Minamiya
c588582acc Add range validation for MCP::Annotations#priority per MCP specification
## Motivation and Context

The MCP specification constrains `Annotations.priority` to the 0–1 range
(`@minimum 0`, `@maximum 1`), but the Ruby SDK accepts any value. The other
official SDKs already enforce this (TypeScript, Python, and PHP).

This follows the existing pattern in `MCP::Icon`, which validates its
constrained `theme` value in the constructor and raises `ArgumentError`.

## How Has This Been Tested?

Added tests in `test/mcp/annotations_test.rb`:

- valid `priority` at the lower (0) and upper (1) bounds is accepted
- out-of-range `priority` (above 1, below 0) raises `ArgumentError`

The full unit suite and RuboCop pass locally.

## Breaking Changes

Strictly speaking yes: a caller that currently passes an out-of-range
`priority` (e.g. `priority: 99`) will now get an `ArgumentError`. Such values
already violate the MCP specification, and `nil` / in-range values are
unaffected.
2026-06-16 00:33:10 +09:00
Ates Goral
cd5226da2e test: close stdio stderr pipe 2026-06-15 10:30:14 +02:00
Koichi ITO
2f24cdfd48
Merge pull request #407 from atesgoral/rubocop-cleanup-existing-offenses
chore: require rubocop-minitest 0.39
2026-06-15 09:40:16 +09:00
Ates Goral
460adafb17 chore: require rubocop-minitest 0.39
Require rubocop-minitest 0.39.0 or newer so Minitest/AssertEmptyLiteral uses its newer default disabled state.
2026-06-14 17:46:38 +02:00
Koichi ITO
3093b3ee3f Set OIDC application_type on Dynamic Client Registration per SEP-837
## Motivation and Context

SEP-837 (modelcontextprotocol/modelcontextprotocol#837, merged for the 2026-07-28 spec release)
updates the authorization spec to require MCP clients to specify an appropriate OIDC `application_type`
(`"native"` vs `"web"`) during Dynamic Client Registration, so the authorization server can apply
the matching redirect URI policy and native and web clients do not collide on redirect URI validation rules.

This mirrors the approach taken by the TypeScript SDK (typescript-sdk#2266) and the Python SDK (python-sdk#2784):

- `MCP::Client::OAuth::Discovery.infer_application_type(redirect_uris)` returns `"native"` when every redirect URI
  is a native-app URI (a custom  non-http(s) scheme per RFC 8252 Section 7.1, or an http(s) URI with a loopback host
  per RFC 8252 Section 7.3) and `"web"` otherwise, including for nil, empty, or unparseable input.
  Loopback detection reuses the existing `loopback_host?` helper, so lookalike hosts such as `localhost.example.com`
  or `127.attacker.com` are not treated as native.
- `Flow#ensure_client_registered` now posts the metadata through the new `registration_client_metadata` helper,
  which merges the inferred `application_type` into the DCR request body only when the user did not set
  one explicitly (symbol or string key); an explicit value always wins.

Resolves #375.

## How Has This Been Tested?

New tests in `test/mcp/client/oauth/discovery_test.rb` cover the inference: loopback http URIs (IPv4, IPv6, `localhost`),
custom schemes, https URIs, mixed lists, the `localhost.example.com` lookalike, nil/empty input, and unparseable URIs.

New tests in `test/mcp/client/oauth/flow_test.rb` assert on the actual DCR request body via WebMock `assert_requested`:
loopback redirect URI registers `"application_type": "native"`, an HTTPS redirect URI registers `"web"`,
and an explicit `application_type` (symbol- or string-keyed) is never overridden.

## Breaking Changes

None. The DCR request body gains an `application_type` member only when the user has not specified one;
RFC 7591 requires authorization servers to accept and use known metadata fields, and OIDC-registration servers
already default this field to `"web"` when absent.
2026-06-15 00:09:39 +09:00
Koichi ITO
7f266d48ef
Merge pull request #405 from koic/capability_extensions
Support Capability Extensions per SEP-2133
2026-06-15 00:09:25 +09:00
Koichi ITO
23af99517c
Merge pull request #404 from koic/release_0_20_0
Release 0.20.0
2026-06-14 17:38:56 +09:00
Koichi ITO
2c62139154 Support Capability Extensions per SEP-2133
## Motivation and Context

SEP-2133 (modelcontextprotocol/modelcontextprotocol#2133, merged for
the 2026-07-28 spec release) establishes the extensions framework for MCP:
both `ClientCapabilities` and `ServerCapabilities` gain an optional `extensions`
member keyed by reverse-DNS extension identifiers
(e.g. `"io.modelcontextprotocol/tasks"`, `"com.example/feature"`), with arbitrary
extension-defined configuration objects as values and an empty object meaning
"supported with no settings". Official extensions such as MCP Apps (SEP-1865)
and the Tasks extension (SEP-2663) are layered on this field.

This mirrors the shape the TypeScript SDK merged (typescript-sdk#1630):
plain declaration and passthrough, no registrar API and no key-format validation
(the naming convention is documented instead).

- `MCP::Server::Capabilities` gains `support_extensions` (repeated calls merge),
  accepts an `:extensions` key in its constructor hash, and includes `extensions`
  in `to_h`. The class was previously dead code: it was never required and
  `Server.new` only took plain hashes. It is now required by `lib/mcp/server.rb`,
  and `Server.new(capabilities:)` accepts either a plain Hash (as before) or
  a `Capabilities` instance.
- Server-declared extensions appear in the `initialize` result;
  extensions the client declares during `initialize` were already stored verbatim and
  are readable via `Server#client_capabilities[:extensions]` and
  `ServerSession#client_capabilities[:extensions]` (now covered by tests).
- `MCP::Client#connect(capabilities:)` already passes capabilities through verbatim;
  its documentation now covers the `extensions` member.

Resolves #378.

## How Has This Been Tested?

- New `test/mcp/server/capabilities_test.rb` covers the previously untested
  `Capabilities` class: empty default, constructor round-trip, extensions via
  constructor and `support_extensions`, merge semantics, nil tolerance,
  and omission from `to_h` when never declared.
- New tests in `test/mcp/server_test.rb` assert that the `initialize` result
  carries declared extensions (from both a plain hash and a `Capabilities` instance)
  and that client-declared extensions are readable via `Server#client_capabilities`
  and `ServerSession#client_capabilities`.

## Breaking Changes

None. `extensions` is additive and appears on the wire only when declared;
servers constructed with plain capability hashes behave exactly as before.
2026-06-14 17:20:45 +09:00
Koichi ITO
4fb0049fd4 Release 0.20.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-06-14 16:58:51 +09:00
Koichi ITO
3a163ad096
Merge pull request #403 from yuki3738/add_annotations_field_to_resource
Add `annotations` field to `MCP::Resource` and `MCP::ResourceTemplate` per MCP specification
2026-06-14 16:52:25 +09:00
Koichi ITO
783eb6303f
Merge pull request #402 from koic/resource_not_found_error_data
Standardize Resource Not Found Errors on -32602 with URI Data per SEP-2164
2026-06-14 16:51:57 +09:00
Yuki Minamiya
64219be2c8 Add annotations field to MCP::Resource and MCP::ResourceTemplate per MCP specification
## Motivation and Context

The MCP specification defines an optional `annotations` field on both the
`Resource` and `ResourceTemplate` types, but the Ruby SDK is the only official
SDK that does not wire it up — TypeScript, Python, and PHP all implement it.
https://modelcontextprotocol.io/specification/2025-11-25/server/resources#annotations

The `MCP::Annotations` class already exists; this commit connects it. The field
accepts an `MCP::Annotations` instance rather than a raw hash, for consistency
with other typed fields and to get `lastModified` key normalization for free.

## How Has This Been Tested?

Added tests in `test/mcp/resource_test.rb` and
`test/mcp/resource_template_test.rb`:

- `#to_h` omits `annotations` when nil
- `#to_h` includes `annotations` when present (also asserting that
  `last_modified` is serialized as `lastModified`)

The full unit suite and RuboCop pass locally.

## Breaking Changes

None. `annotations:` is a new optional keyword argument defaulting to `nil`,
and it is omitted from `#to_h` output when not set.
2026-06-14 16:05:25 +09:00
Koichi ITO
d096b8a7a9 Standardize Resource Not Found Errors on -32602 with URI Data per SEP-2164
## Motivation and Context

SEP-2164 (modelcontextprotocol/modelcontextprotocol#2164, merged for the 2026-07-28 spec release)
standardizes the resource-not-found error on the JSON-RPC Invalid Params code (-32602),
dropping the legacy -32002 code, and both reference SDK implementations attach the requested URI
as structured error data (typescript-sdk#2267 throws `InvalidParams` with `data: { uri }`;
python-sdk#2344 adds a `ResourceNotFoundError` that maps to `code=-32602, data={"uri": ...}`).

The Ruby server already used -32602 (via `error_type: :invalid_params`) for its built-in not-found path
(`completion/complete` with an unknown `ref/resource` URI), but the response carried no structured data
and the generic "Invalid params" message, and there was no public error class for `resources_read_handler`
blocks to raise. The Ruby client never special-cased -32002, so nothing needed removal there.

- New public `MCP::Server::ResourceNotFoundError` (modeled on the `URLElicitationRequiredError` precedent):
  code -32602, message `"Resource not found: <uri>"`, and `data: { uri: <uri> }`.
  Custom `resources_read_handler` blocks raise it for unknown URIs; the README documents the pattern.
- The `completion/complete` `ref/resource` not-found path now raises this class,
  so its error response gains `data: { uri: }` and a descriptive message instead of
  the generic "Invalid params" text.
- The default `resources/read` behavior (returning empty contents for unknown URIs
  when no handler is registered) is intentionally unchanged; raising there would
  alter existing wire behavior.

Resolves #379.

## How Has This Been Tested?

New tests in `test/mcp/server_test.rb`:

- `resources/read` with a handler raising `ResourceNotFoundError` responds
  with code -32602, message `"Resource not found: file:///missing.txt"`,
  and `data: { uri: "file:///missing.txt" }`
- `completion/complete` with an unknown `ref/resource` URI carries the same code,
  message, and structured data

New test in `test/mcp/client_test.rb` asserts `Client#read_resource` surfaces
the -32602 code and the `data` hash unmodified through `Client::ServerError`
(regression: no special-casing swallows it).

The pre-existing completion error-code tests pass unchanged.
`bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

None at the JSON-RPC code level (-32602 before and after).
The `completion/complete` resource-not-found error response changes shape within
the error object: `message` becomes `"Resource not found: <uri>"` instead of
`"Invalid params"`, and `data` becomes `{ uri: <uri> }` instead of the message string.
Both members are advisory per JSON-RPC 2.0.
2026-06-14 01:03:23 +09:00
Koichi ITO
2e5162af8d
Merge pull request #373 from koic/add_logging_set_level_to_supported_methods_in_readme
[Doc] Add `logging/setLevel` to supported methods in README
2026-06-14 00:16:49 +09:00
Koichi ITO
8a709f6436
Merge pull request #372 from koic/clarify_server_context_hash
[Doc] Clarify `server_context` Hash requirement for `_meta` merging
2026-06-14 00:16:31 +09:00
Koichi ITO
6929d52472
Merge pull request #370 from koic/fix_exception_reporter_server_context
[Doc] Fix `server_context` description for Exception Reporting
2026-06-14 00:16:14 +09:00
Koichi ITO
3d7046ab1a
Merge pull request #392 from koic/fallback_missing_protocol_version_in_streamable_http_transport
Default missing `MCP-Protocol-Version` to 2025-03-26 in StreamableHTTPTransport
2026-06-14 00:15:55 +09:00
Koichi ITO
41dbe869be
Merge pull request #371 from koic/use_json_rpc_envelope_for_transport_errors
Use JSON-RPC error envelope for `StreamableHTTPTransport` errors
2026-06-13 20:32:17 +09:00
Koichi ITO
a5acf6bfe5
Merge pull request #397 from koic/otel_trace_context_meta
Support W3C Trace Context Propagation via `_meta` per SEP-414
2026-06-13 20:27:08 +09:00
Koichi ITO
8e41474f71
Merge pull request #395 from koic/rfc8414_well_known_suffix
Pin RFC 8414 Default Well-Known Suffix per SEP-2351
2026-06-13 20:23:10 +09:00
Koichi ITO
8c216484a8
Merge pull request #400 from koic/preserve_request_id_in_envelope_errors
Preserve the Request ID in Invalid Request Error Responses
2026-06-13 20:14:30 +09:00
Koichi ITO
39676bc93c
Merge pull request #369 from koic/switch_to_json_schemer
Speed Up `Tool::Schema` Validation by 5x to 100x
2026-06-13 20:13:00 +09:00
Koichi ITO
cf27c5dca6
Merge pull request #399 from koic/client_credentials_basic
Support OAuth `client_credentials` grant in OAuth client
2026-06-13 20:06:29 +09:00
Koichi ITO
81e34cb80c
Merge pull request #368 from koic/conformance_client_auth_scope_step_up
Re-run OAuth flow on 403 insufficient_scope (step-up)
2026-06-13 20:02:33 +09:00
Koichi ITO
b6372d8ac4
Merge pull request #394 from koic/release_0_19_0
Release 0.19.0
2026-06-13 19:54:54 +09:00
Koichi ITO
8f10f8e542 Release 0.19.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-06-13 02:31:22 +09:00
Koichi ITO
18761cf367 Preserve the Request ID in Invalid Request Error Responses
## Motivation and Context

Resolves #398.

`JsonRpcHandler` returned `"id": null` for JSON-RPC envelope errors
(wrong or missing `jsonrpc` version, non-string `method`) even when
the incoming payload carried a concrete, valid request id.
From the client's perspective the original request stayed pending forever,
since no response with the matching id ever arrived:

```
{"jsonrpc":"1.0","id":3,"method":"ping","params":{}}
=> {"jsonrpc":"2.0","id":null,"error":{"code":-32600,...}}
```

Per JSON-RPC 2.0 (Response object, `id`), the response id MUST be
the same as the request's id; null is reserved for requests whose id
could not be detected (e.g. Parse error). The envelope validation in
`process_request` runs after JSON parsing with the request hash in
hand, so the id is detectable - it was simply discarded by passing
the `:unknown_id` sentinel unconditionally.

The fix passes the request's id to `error_response` whenever
the request carries one. The existing guards keep every other case intact:
`error_response` already nils out ids that fail validation
(so a type-invalid or pattern-violating id still yields `"id": null`,
preserving the XSS-prevention policy on echoed ids), and the `:unknown_id`
sentinel is kept for requests without an id so an Invalid Request error
still produces a null-id response, matching the spec's own example.
Parse errors and non-object requests are unchanged (null is correct there),
and batch entries pick up the fix automatically since each entry goes through
`process_request`.

For reference, the TypeScript and Python SDKs currently respond with
`"id": null` in these cases as well, because both validate the whole
message against a schema (zod / pydantic) before extracting the id.
This change is driven by the JSON-RPC 2.0 requirement rather than
parity; the Ruby transport layer already echoes the request id where
recoverable (`invalid_request_response(request_id:)` in
`StreamableHTTPTransport`), and this closes the remaining gap in
`JsonRpcHandler`.

## How Has This Been Tested?

- Reproduced the three payloads from #398 before and after the fix;
  they now return `"id":3`, `"id":4`, and `"id":8` respectively
- New and updated unit tests covering: id preserved for wrong version,
  missing `jsonrpc`, numeric `method`, and `rpc.`-prefixed `method`;
  id preserved for an invalid entry inside a batch; null id kept for
  requests without an id, with an explicit null id, and with an id
  that fails validation

## Breaking Changes

None in the protocol sense - this aligns the error responses with
JSON-RPC 2.0. Clients that matched `"id": null` on these envelope
errors will now see the request's own id, which is what allows them
to correlate the error with the pending request.
2026-06-13 02:16:25 +09:00
Koichi ITO
2289db84f8 Support OAuth client_credentials grant in OAuth client
## Motivation and Context

The MCP authorization specification and SEP-1046 allow confidential clients to
obtain tokens through the OAuth 2.1 `client_credentials` grant: a machine-to-machine flow
with no user, no browser redirect, and no authorization code. The Ruby SDK
previously supported only the interactive authorization-code flow, so it could not
authenticate against a server that requires `client_credentials`. This makes
the `auth/client-credentials-basic` conformance scenario pass and is removed from
the expected failures list.

Following the TypeScript SDK (`ClientCredentialsProvider`) and the Python SDK
(`ClientCredentialsOAuthProvider`), the grant gets its own provider class rather than
overloading the authorization-code provider. The change adds:

- `MCP::Client::OAuth::ClientCredentialsProvider`, a dedicated provider
  for the grant. `client_id` and `client_secret` are mandatory
  (the grant is for confidential clients), `token_endpoint_auth_method` is
  `client_secret_basic` (default) or `client_secret_post` -- `none` is
  rejected because an unauthenticated `client_credentials` request is
  meaningless. It has no redirect arguments, so a credentials-only
  client never supplies the redirect URI / handlers that grant has no use for.
- `MCP::Client::OAuth::StorageBackedProvider`, an internal module that
  shares the token / client-information persistence between the two provider classes
  so `Flow` can treat any provider uniformly.
- `Provider#authorization_flow` (`:authorization_code`) and
  `ClientCredentialsProvider#authorization_flow` (`:client_credentials`).
  `Flow#run!` dispatches on this rather than inspecting
  `client_metadata[:grant_types]`, which is protocol metadata for
  the authorization server, not an SDK control signal.
- `run_client_credentials!` shares the same PRM / AS metadata discovery
  and Communication Security checks as the interactive flow, then
  exchanges `grant_type=client_credentials` at the token endpoint via
  the existing `post_to_token_endpoint` (which already applies
  `client_secret_basic`). There is no PKCE, redirect, or `offline_access`
  augmentation, because the grant does not issue a refresh token
  (OAuth 2.1 Section 4.3.3).
- `conformance/client.rb` builds a `ClientCredentialsProvider` for
  the `auth/client-credentials-*` scenarios, reusing the harness-injected
  `client_id` / `client_secret`.

## How Has This Been Tested?

New `ClientCredentialsProvider` tests cover: credentials are stored as
client information; `authorization_flow` is `:client_credentials`;
`client_secret_post` is accepted; missing `client_id` / `client_secret`
and `token_endpoint_auth_method: "none"` are rejected; and the token helpers
delegate to storage.

New `Flow` tests cover: a `client_credentials` provider exchanges
`grant_type=client_credentials` with HTTP Basic auth, saves the token,
and never contacts the authorization or registration endpoint;
the requested scope is taken from PRM `scopes_supported`; and a standard
`Provider` runs the authorization-code grant regardless of what its
`client_metadata[:grant_types]` lists. A `Provider` test asserts
`authorization_flow` is `:authorization_code`.

Conformance: `auth/client-credentials-basic` now passes 7/7 with no failures.

## Breaking Changes

None. `ClientCredentialsProvider` is a new class; the existing `Provider` keeps
its required `redirect_uri` / `redirect_handler` / `callback_handler` arguments
and its behaviour is unchanged. Existing interactive clients are unaffected.
2026-06-13 00:12:19 +09:00
Koichi ITO
b1818f25c8 Support W3C Trace Context Propagation via _meta per SEP-414
## Motivation and Context

SEP-414 (modelcontextprotocol/modelcontextprotocol#414, merged for
the 2026-07-28 spec release) documents OpenTelemetry trace context propagation
conventions for MCP: the un-prefixed `_meta` keys `traceparent`,
`tracestate`, and `baggage` are reserved (an explicit exception to
the reverse-DNS prefix rule) so trace context can flow between MCP clients and
servers per the W3C Trace Context and Baggage specifications.

This follows the TypeScript SDK's approach (typescript-sdk#2270):
guarantee `_meta` passthrough, export constants for the reserved key names,
and lock the behavior in with regression tests and documentation, without adding
an OpenTelemetry dependency (the Python SDK's python-sdk#2381 makes
`opentelemetry-api` a hard dependency instead, which conflicts with
this SDK's keep-dependencies-minimal policy):

- New `MCP::TraceContext` module exposing `TRACEPARENT_META_KEY`,
  `TRACESTATE_META_KEY`, `BAGGAGE_META_KEY`, and `META_KEYS`.
- The server side already passes incoming request `_meta` to tool and prompt
  handlers untouched via `server_context[:_meta]`; new regression tests pin
  that guarantee for the three reserved keys.
- Every `MCP::Client` request method (`call_tool`, `read_resource`,
  `get_prompt`, `complete`, `ping`, and the `list_*` methods) gains
  a `meta:` keyword so Ruby clients can inject trace context (or any other
  `_meta` entries) into outgoing requests; per SEP-414, trace context
  should flow on every request, not only tool calls. The caller's hash is
  never mutated. On `call_tool`, `progress_token` takes precedence over
  a `progressToken` entry in `meta`, and an empty merge result omits `_meta`
  entirely, preserving the existing wire format.
- README documents the convention and how to bridge the values to a tracing
  system such as the `opentelemetry-ruby` gems.

Scope is intentionally client-to-server: server-initiated requests
(`sampling/createMessage`, `roots/list`, `elicitation/create`) do not accept
`meta:` yet; propagating trace context on those is a separate follow-up.

Resolves #374.

## How Has This Been Tested?

- New `test/mcp/trace_context_test.rb` pins the exact reserved key names and
  the frozen `META_KEYS` list.
- New tests in `test/mcp/server_test.rb` assert that `tools/call` and
  `prompts/get` deliver `traceparent`, `tracestate`, and `baggage` (alongside
  `progressToken`) to handlers through `server_context[:_meta]` unchanged.
- New tests in `test/mcp/client_test.rb` cover the `meta:` keyword: the
  trace keys are sent in `_meta` on `call_tool` and `read_resource`,
  a table-driven test exercises the remaining request methods (`tools/list`,
  `resources/list`, `resources/templates/list`, `prompts/list`,
  `prompts/get`, `completion/complete`, `ping`), `progress_token` overrides
  a `progressToken` entry in `meta` without duplicating the key,
  the caller's `meta` hash is not mutated, and requests without `meta:`
  serialize exactly as before (wire-format regressions for both the empty `meta`
  hash and the no-params list request).

## Breaking Changes

None. `MCP::TraceContext` and the `meta:` keyword are purely additive, and
requests without `meta:` serialize exactly as before.
2026-06-12 14:36:24 +09:00
Koichi ITO
a407cea086 Re-run OAuth flow on 403 insufficient_scope (step-up)
## Motivation and Context

The MCP authorization specification (2025-11-25 scope-selection-strategy)
and RFC 6750 Section 3.1 describe OAuth 2.0 step-up authentication:
the client already holds a valid access token, but the server returns a 403
with `WWW-Authenticate: Bearer error="insufficient_scope", scope="..."`
to demand a higher-privileged scope for a specific operation.
The client is expected to run a fresh authorization request with
the escalated scope and retry.

Until now the Ruby SDK only ran the OAuth flow on 401 responses.
A 403 surfaced unchanged as a `RequestHandlerError` and the operation
that needed the escalated scope failed permanently, even with a valid token
in storage. This lined up with the `auth/scope-step-up` conformance
scenario being listed in `conformance/expected_failures.yml`.

The change adds:

- `MCP::Client::HTTP#send_request` recognises a 403 carrying
  an `insufficient_scope` Bearer challenge as a step-up signal,
  re-runs a full authorization request with the scope from the challenge,
  and retries the original request. Retries are capped at
  one per `send_request` call so a server that repeatedly demands more
  scope cannot loop the transport.
- `run_step_up_flow!` deliberately bypasses the refresh-token path that
  `run_oauth_flow!` uses on 401. Refreshing would re-issue the same
  scope set the existing token already has and the server already
  rejected. Only a fresh `authorization_code` grant with the escalated
  scope can succeed.
- A plain 403 with no `insufficient_scope` challenge continues to
  surface as `RequestHandlerError` with `error_type: :forbidden`.
- `conformance/client.rb` invokes a tool for the `auth/scope-step-up`
  scenario; the scenario's authorization middleware only requires
  the escalated scope on `tools/call`, so the previous `tools/list`-only
  client could never trigger the second authorization.
- `auth/scope-step-up` is removed from `conformance/expected_failures.yml`.

Resolves #383.

## How Has This Been Tested?

New `HTTPOAuthTest` cases cover: the 403 insufficient_scope path
re-authorizes with the escalated scope from the challenge and retries
the original request with the new bearer token; a plain 403 without
the `insufficient_scope` challenge is surfaced as
`error_type: :forbidden` with no OAuth side effects; repeated
`insufficient_scope` responses retry at most once and then surface the 403;
a provider with a saved `refresh_token` still goes through
the full authorization request rather than exchanging the refresh token,
because the existing scope set is precisely what was rejected.

Conformance: `auth/scope-step-up` now passes 22/22 with no warnings.
`bundle exec rake test`, `bundle exec rake rubocop`, and
`bundle exec rake conformance` are all green.

## Breaking Changes

None. Behaviour on 401 is unchanged. A 403 without the `insufficient_scope`
Bearer challenge still raises the same `RequestHandlerError` as before.
The new retry only fires when both the WWW-Authenticate header signals step-up
and the transport was constructed with an OAuth provider.
2026-06-12 11:59:02 +09:00
Koichi ITO
9193745291
Merge pull request #396 from baxter2/extract_fetch_all_pages
Extract `MCP::Client` pagination loop into `fetch_all_pages`
2026-06-11 17:01:33 +09:00
baxter2
a290fe281a Extract MCP::Client pagination loop into fetch_all_pages
`#tools`, `#resources`, `#resource_templates`, and `#prompts` each repeated
the same loop to follow `next_cursor` and collect every page, differing only
in the `list_*` method called and the items field read from each page. Move
that loop into a single private `fetch_all_pages` helper so the four methods
are one-liners and the cursor-cycle guard lives in one place.

Behavior is unchanged; the existing `MCP::Client` list tests cover it.
2026-06-11 17:50:59 +10:00
Koichi ITO
2a26ad2030 Pin RFC 8414 Default Well-Known Suffix per SEP-2351
## Motivation and Context

SEP-2351 (modelcontextprotocol/modelcontextprotocol#2351, merged for the 2026-07-28 spec release)
makes explicit that MCP uses the default `oauth-authorization-server` well-known URI suffix from
RFC 8414 Section 3.1 and defines no application-specific suffix.

`MCP::Client::OAuth::Discovery.authorization_server_metadata_urls` already conforms:
it probes the RFC 8414 default suffix first (path-inserted form for path issuers) and
otherwise uses only the OpenID Connect Discovery `openid-configuration` suffix.
Neither the Python SDK nor the TypeScript SDK needed a behavior change for this SEP either;
their tracking issues (python-sdk#2799, typescript-sdk#2256) remain documentation-level.

This change documents the SEP-2351 guarantee in the discovery helper and locks the behavior
in with regression tests so a future refactor cannot silently introduce a non-default suffix.

Resolves #384.

## How Has This Been Tested?

New regression tests in `test/mcp/client/oauth/discovery_test.rb`:

- the first probed candidate for a root issuer is exactly `/.well-known/oauth-authorization-server`
- every generated candidate uses only the `oauth-authorization-server` or `openid-configuration` suffix
- the RFC 8414 path-inserted `oauth-authorization-server` candidate comes first for issuers with a path component
- an issuer URL with a trailing slash is treated as a root issuer

## Breaking Changes

None. Documentation and regression tests only; no behavior change.
2026-06-10 17:48:28 +09:00
Koichi ITO
ac07f8f3a7
Merge pull request #393 from yuki3738/add_size_field_to_resource
Add `size` field to `MCP::Resource` per MCP specification
2026-06-08 01:24:39 +09:00
Yuki Minamiya
91ff179d78 Add size field to MCP::Resource per MCP specification
## Motivation and Context

The MCP specification defines an optional `size` field on the `Resource`
type, added in spec revision 2025-06-18 and retained in 2025-11-25:
https://modelcontextprotocol.io/specification/2025-11-25/server/resources

> The size of the raw resource content, in bytes (i.e., before base64
> encoding or any tokenization), if known. This can be used by Hosts to
> display file sizes and estimate context window usage.

`MCP::Resource` was missing this field, so servers had no way to declare a
resource's byte size. Without it, hosts cannot show file sizes or estimate
context window usage before reading the resource contents.

This aligns the Ruby SDK with the spec, matching the TypeScript SDK
(modelcontextprotocol/typescript-sdk#1574).

## How Has This Been Tested?

Added tests in `test/mcp/resource_test.rb`:

- `#to_h` omits `size` when nil
- `#to_h` includes `size` when present
- `#to_h` includes `size` when zero (distinguishes an unset size from a
  0-byte resource)

The full unit suite and RuboCop pass locally.

## Breaking Changes

None. `size:` is a new optional keyword argument defaulting to `nil`, and it
is omitted from `#to_h` output when not set, so existing callers are unaffected.
2026-06-07 21:10:41 +09:00
Koichi ITO
4322ec0886 Default missing MCP-Protocol-Version to 2025-03-26 in StreamableHTTPTransport
## Motivation and Context

MCP 2025-11-25 (basic/transports#protocol-version-header) specifies:

> For backwards compatibility, if the server does not receive an
> `MCP-Protocol-Version` header, and has no other way to identify the
> version - for example, by relying on the protocol version negotiated
> during initialization - the server SHOULD assume protocol version `2025-03-26`.

PR #347 satisfied only the MUST requirement (reject invalid/unsupported
values with 400). The SHOULD requirement to default a missing header to
`2025-03-26` was deferred to this follow-up.

This change brings the Ruby SDK in line with the Python SDK
(`src/mcp/server/streamable_http.py`), which falls back to
`DEFAULT_NEGOTIATED_VERSION` and then revalidates against the supported list.

## Behavior

A new constant `MCP::Configuration::DEFAULT_NEGOTIATED_PROTOCOL_VERSION`
holds `"2025-03-26"`. `validate_protocol_version_header` now substitutes
this value when the `MCP-Protocol-Version` header is absent, then runs
the same supported-version check. Because `"2025-03-26"` is currently in
`SUPPORTED_STABLE_PROTOCOL_VERSIONS`, missing headers continue to pass
through as before. Once `"2025-03-26"` is dropped from the supported
list in a future change, missing headers will start returning 400 with
a message naming the defaulted value.

## How Has This Been Tested?

Existing test `POST request without MCP-Protocol-Version header
succeeds` continues to pass (observable behavior unchanged today).
Added a focused regression test that stubs the supported-version list
to exclude `"2025-03-26"` and verifies that a header-less request is
rejected with the defaulted value reported in the error message;
this exercises the fallback branch directly.

## Breaking Changes

None today. The fallback is future-proofing: when `"2025-03-26"` is
eventually dropped, header-less requests will start returning 400.
That is the intended spec-driven behavior.
2026-06-07 10:18:33 +09:00
Koichi ITO
8d123fb8f2 [Doc] Clarify server_context Hash requirement for _meta merging
## Motivation and Context

The README documents that request-level `_meta` becomes available to tools
and prompts under `server_context[:_meta]`.
However, `Server#server_context_with_meta` only merges `_meta` when
`server_context` is a `Hash` (or `nil`, in which case a new `{ _meta: ... }` hash
is synthesized). When a non-`Hash` value is assigned to `server_context`, `_meta`
is silently dropped and tools will not see it under `server_context[:_meta]`.

This adds a note clarifying that `server_context` must be kept as a `Hash`
if tools need access to `_meta`.

## How Has This Been Tested?

Documentation-only change, no behavioral modification.

## Breaking Changes

None.
2026-06-05 01:35:34 +09:00
Koichi ITO
f5507cc5ae [Doc] Add logging/setLevel to supported methods in README
Follow-up to #103.
2026-06-05 01:18:03 +09:00
Koichi ITO
c91702899d Use JSON-RPC error envelope for StreamableHTTPTransport errors
## Motivation and Context

PR #347 introduced a single JSON-RPC error envelope response for
unsupported `MCP-Protocol-Version` headers, while the rest of the
transport-level error responses (Accept, Content-Type, Invalid JSON,
session management, method not allowed, internal server error) still
returned plain JSON of the form `{ "error": "..." }`. The Python SDK
(`src/mcp/server/streamable_http.py`) and TypeScript SDK
(`packages/server/src/server/streamableHttp.ts`) consistently use
a JSON-RPC error envelope for all transport-level errors.
Unify the Ruby SDK with them.

## Behavior

All transport-level error responses now return a JSON-RPC error envelope:

```json
{
  "jsonrpc": "2.0",
  "id": null,
  "error": {
    "code": -32600,
    "message": "..."
  }
}
```

Affected helpers in `lib/mcp/server/transports/streamable_http_transport.rb`:

- `validate_content_type` (HTTP 415)
- `not_acceptable_response` (HTTP 406)
- `parse_request_body` error (HTTP 400, `PARSE_ERROR` `-32700`)
- `method_not_allowed_response` (HTTP 405)
- `missing_session_id_response` (HTTP 400)
- `session_not_found_response` (HTTP 404)
- `session_already_connected_response` (HTTP 409)
- Internal server error fallback in `handle_post` (HTTP 500, `INTERNAL_ERROR` `-32603`)
- `validate_protocol_version_header` (HTTP 400, dedup with shared helper)

A new private helper `json_rpc_error_response(status:, code:, message:)`
centralizes the envelope construction.

The "Invalid JSON" message wording is updated to "Parse error: Invalid JSON"
to match the JSON-RPC 2.0 `PARSE_ERROR` semantics.

## How Has This Been Tested?

Updated all affected tests in `test/mcp/server/transports/streamable_http_transport_test.rb` to
assert the new envelope shape (`body["error"]["message"]` instead of `body["error"]`).

## Breaking Changes

Clients that parsed the previous plain `{"error": "..."}` shape will need to read
`body["error"]["message"]` (or `body["error"]["code"]`).
The HTTP status codes are unchanged, only the response body structure changed.
2026-06-04 10:52:14 +09:00
Koichi ITO
8c91130451 [Doc] Fix server_context description for Exception Reporting
## Motivation and Context

The README's Exception Reporting section claimed that `server_context` includes
`{ tool_name: "name", arguments: { ... } }` for tool calls. This matched
the implementation in 0.3.0 through 0.5.0, but the `{ tool_name:, arguments: }`
context was removed in 0.5.1 when exception reporting was consolidated into
the centralized `{ request: request }` path. The README was never updated to reflect this.

`Server#report_exception` is now only called with `{ request: request }`
(from `handle_request`) or `{ notification: "..." }` (from notification delivery rescues),
and tool call failures flow through the `{ request: ... }` path after being wrapped in
a `RequestHandlerError`.

The stale description misled users into expecting `tool_name` and `arguments`
in their exception reporter callbacks.

## How Has This Been Tested?

Documentation-only change. No behavioral modification.

## Breaking Changes

None.
2026-06-03 11:32:05 +09:00
Koichi ITO
9d4dcbf1a4 Speed Up Tool::Schema Validation by 5x to 100x
## Motivation and Context

`MCP::Tool::Schema` previously used the pure-Ruby `json-schema` gem for
both construction-time metaschema validation and runtime argument /
result validation. For deep schemas this cost ~32-100ms per
construction (see issue #364).

`json_schemer` (https://rubygems.org/gems/json_schemer, v2.5.0) is
an actively maintained alternative that is much faster on this workload.
Switching reduces cold-start warming pressure in horizontally scaled
multi-tenant deployments (the scenario raised in #364) and brings
runtime data validation down to sub-millisecond per call once
the per-instance schemer is memoized.

The implementation preserves the legacy behavior of the `json-schema`
based code. Metaschema is pinned to draft-04 (`meta_schema:` option);
the `$schema` dialect URI is still emitted in `to_h` as 2020-12
but runtime validation continues to use draft-04, exactly as before.
Moving the runtime validator itself to 2020-12 is out of scope for
this PR and warrants its own discussion. `format` keywords are not enforced
(`format: false` option), matching what `json-schema`'s draft-04 path did.
Malformed schemas (e.g. an invalid `pattern` regex) continue to
surface as `ArgumentError, "Invalid JSON Schema: ..."`;
the `RegexpError` `json_schemer` raises during construction is wrapped.
`Symbol` values in argument data are coerced to strings inside
the internal `stringify` helper so they validate against `type: "string"`
the same way they did before.

The public `Schema#schema` accessor is dropped. It was a refactor
artifact from #198 (the consolidation of `InputSchema`'s
`properties` / `required` readers into a single hash) with no callers
in `lib/`; tests that needed the merged hash now read it through
`to_h`. The accessor's only remaining role would have been to expose
a mutation path that could desynchronize the memoized `@schemer`,
which this change removes.

Runtime dependency delta: drops `json-schema` (and `addressable`),
adds `json_schemer`, `hana`, `regexp_parser`, and `simpleidn`. Each added
gem is a single-purpose library tied to JSON Schema spec compliance.

Closes #364.

## How Has This Been Tested?

Side-by-side benchmark on representative schemas (simple, with `$ref` /
`additionalProperties`, nested, depth 20, depth 40):
construction-time metaschema validation is 4.7x to ~100x faster;
runtime data validation with the memoized schemer is sub-millisecond
across all sizes.

Four existing tests had their stub targets or message assertions updated
to track the new validator while preserving the original test intent.
The "unexpected errors bubble up" tests in `input_schema_test.rb`
and `output_schema_test.rb` now stub `JSONSchemer::Schema#validate`
instead of `JSON::Validator.fully_validate`. The cache tests in
`schema_test.rb` now stub `JSONSchemer::Schema#validate_schema`.
The two "detailed error message" tests in `tool_test.rb` switched from
asserting `json-schema`'s exact wording to format-agnostic substrings
(`"properties/count/minimum"`, `"number"`). The "required arguments are
converted to strings" test in `input_schema_test.rb` now reads the result
through `to_h[:required]` instead of the removed `schema` accessor.

Regression tests added for the legacy-behavior preservations above:
`format` keyword is not enforced, invalid `pattern` raises `ArgumentError`
(not `RegexpError`), and `Symbol` values validate against `type: "string"`.

## Breaking Changes

`Schema#schema` is no longer a public method. The accessor had no callers
outside the test suite, but anyone reading the internal representation
directly (rather than through `to_h`) will need to switch.
`Schema` / `InputSchema` / `OutputSchema` otherwise keep
their constructor signatures, `to_h` output, `ValidationError` /
`ArgumentError` raise points, and the `$schema` dialect emission.
The validator error message wording inside `ArgumentError` and
`ValidationError` now comes from `json_schemer` and still includes
the JSON pointer path and a description of the mismatch.
2026-06-01 21:47:30 +09:00
Koichi ITO
cf44475ce9
Merge pull request #365 from koic/conformance_client_auth_offline_access_scope
Request offline_access scope when supported (SEP-2207)
2026-06-01 01:09:01 +09:00
Koichi ITO
60416c9ac0
Merge pull request #361 from koic/conformance_client_auth__basic_cimd
Support Client ID Metadata Documents in OAuth client
2026-05-31 03:13:16 +09:00
Koichi ITO
3ff237a02c
Merge pull request #367 from koic/release_0_18_0
Release 0.18.0
2026-05-30 18:28:32 +09:00
Koichi ITO
39882919b8 Release 0.18.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-05-30 03:19:18 +09:00
Koichi ITO
fdca6f5a2f Request offline_access scope when supported (SEP-2207)
## Motivation and Context

SEP-2207 describes how an OAuth client obtains refresh tokens: it
declares the `refresh_token` grant type in its client metadata and
requests the `offline_access` scope, but only when the authorization
server advertises `offline_access` in its metadata `scopes_supported`.
Requesting `offline_access` when the server does not list it is forbidden.

The Ruby SDK already supports the refresh grant (`Flow#refresh!`) but never
requested `offline_access`, so it could not obtain a refresh token from a server
that gates it behind that scope. This aligns the SDK with the Python and TypeScript SDKs
and makes the `auth/offline-access-scope` conformance scenario pass
(previously it reported one warning, `sep-2207-client-metadata-grant-types`,
and was listed in the expected-failures baseline).

The change adds:

- `Flow#augment_scope_with_offline_access`, called from `run!` after
  `resolve_scope`, appends `offline_access` to the requested scope when
  both the client opted into refresh tokens (its registered
  `grant_types` include `refresh_token`) and the authorization server
  advertises `offline_access` in its metadata `scopes_supported`.
  Already-present `offline_access` is not duplicated. Gating on the server
  advertisement keeps the SDK from ever requesting the scope where it is not supported.
- `conformance/client.rb` declares `refresh_token` in `grant_types`, an honest reflection
  of the SDK's refresh support, which clears the SEP-2207 grant-types warning.
- `auth/offline-access-scope` is removed from `conformance/expected_failures.yml`.

## How Has This Been Tested?

New `Flow` tests cover: `offline_access` is requested when the server advertises it
and the client declared the `refresh_token` grant; `offline_access` is NOT requested
when the client did not declare the grant; `offline_access` is NOT requested
when the server does not advertise it (even with the grant declared);
and `offline_access` is not duplicated when it is already part of the resolved scope.

Conformance: `auth/offline-access-scope` now passes 14/14 with no warnings,
and `auth/offline-access-not-supported` still passes 13/13 (no regression).
`bundle exec rake test`, `bundle exec rake rubocop`, and `bundle exec rake conformance`
are all green.

## Breaking Changes

None. `offline_access` is appended only when the client's own `grant_types` opt
into refresh tokens and the authorization server advertises the scope, so existing clients
that do neither see no change in the scope they request.
2026-05-29 13:14:14 +09:00
Koichi ITO
f6e43d971e
Merge pull request #363 from koic/cache-tool-schema-validation
Cache `Tool::Schema` Validation to Avoid Re-validating Identical Schemas
2026-05-28 00:41:59 +09:00
Koichi ITO
5c8b132dcd Cache Tool::Schema Validation to Avoid Re-validating Identical Schemas
## Motivation and Context

`MCP::Tool::Schema#initialize` validated every instance against the draft-04 metaschema
via `JSON::Validator.fully_validate`, costing ~32ms for deep schemas (up to ~100ms).
When schemas are built dynamically and repeatedly, this work is wasted because
the result depends only on the schema content.

This caches successful validations by a content digest, so an identical schema is validated
once and subsequent constructions skip the traversal (~100ms to ~0.1ms on a cache hit).
The cache is bounded and thread-safe. It supersedes the `validate: false` escape hatch proposed
in #362, which would have added permanent public interface and allowed invalid schemas
to reach clients.

Python and TypeScript SDKs do not metaschema-validate schema definitions, so this cost is specific
to the Ruby SDK; caching reduces it without weakening the default or changing validation semantics.

## How Has This Been Tested?

Added regression tests in `test/mcp/tool/schema_test.rb`: identical schemas validate only once,
distinct schemas validate separately, a cache hit still yields a usable and correctly validated schema,
invalid schemas raise on every construction and are not cached, a schema at the normalization depth limit
is cached without a nesting error, and `ValidationCache` evicts the oldest entry beyond its max size.
The full suite (`rake test`) and `rake rubocop` pass.

## Breaking Changes

None. Validation safety is preserved: every distinct schema is still validated, and invalid schemas
continue to raise. The initializer signature and validation semantics are unchanged.
2026-05-27 12:38:28 +09:00
Koichi ITO
355c904899 Support Client ID Metadata Documents in OAuth client
## Motivation and Context

The MCP 2025-11-25 authorization specification and `draft-ietf-oauth-client-id-metadata-document-00` define
Client ID Metadata Documents (CIMD): a client publishes its OAuth metadata at an HTTPS URL and uses that URL
as the OAuth `client_id` instead of going through Dynamic Client Registration. The Python and TypeScript SDKs
already implement this; the Ruby SDK now reaches parity.

The change adds:

- `MCP::Client::OAuth::Provider` accepts an optional `client_id_metadata_document_url:` keyword.
- A new `Discovery.client_id_metadata_document_url?` validator enforces structural requirements.
  Spec-required: `https` scheme, a non-root path, and no fragment, userinfo, or `.`/`..` segments
  (including the percent-encoded form `%2E`). Stricter than the draft as an SDK policy: query strings
  are also rejected, because different encodings of the same query would yield distinct `client_id` strings for
  the same logical document. The loopback `http` carve-out used for discovery URLs does not extend to CIMD URLs,
  since the value is sent verbatim to the authorization server as the OAuth `client_id` and travels off-loopback.
  Validation failures raise `Provider::InvalidClientIDMetadataDocumentURLError`.
- `Flow#ensure_client_registered` routes through CIMD only when the authorization server advertises
  `client_id_metadata_document_supported` as JSON `boolean true`; truthy non-boolean values
  (string `"true"`, `"false"`, etc.) fall back to DCR, matching the gating in the Python and TypeScript SDKs.
- The CIMD `client_id` is NOT persisted to storage. AS support is re-read on every flow so a server
  that later drops CIMD support stops receiving the stale URL. Pre-registered `client_information`
  continues to win over CIMD when both are available.
- `Flow#refresh!` reconstructs the CIMD `client_id` from live AS metadata when refreshing tokens obtained via CIMD.
  When support has been withdrawn and no other identity is stored, it raises a clear `AuthorizationError` rather than
  sending a `client_id` the authorization server no longer recognises.
- The Provider docstring and README OAuth section explain that DCR `client_metadata` and the JSON document served at
  the CIMD URL are separate artifacts: DCR metadata MUST NOT include `client_id`, while the CIMD document MUST include
  `client_id` set to the URL, `client_name`, and `redirect_uris` covering `redirect_uri`.
- `auth/basic-cimd` is removed from `conformance/expected_failures.yml`.

## How Has This Been Tested?

`Discovery` tests cover: https with path accepted; non-https rejected (http, ftp, file); root and empty path rejected;
fragment, query, and userinfo rejected; dot segments rejected including the percent-encoded form `%2E`; nil, empty,
and malformed inputs rejected.

`Provider` tests cover: the default `nil`; rejection of http URLs (loopback included); non-https schemes;
root and empty path; fragment; query; userinfo; and dot segments.

`Flow#run!` tests cover: skip DCR when the authorization server advertises CIMD and the provider has a URL;
fall back to DCR when the authorization server does not advertise support; fall back to DCR when the value is
the string `"false"` or `"true"`; pre-registered `client_information` wins over CIMD; the CIMD `client_id` is not
persisted to storage; a second flow against an authorization server that has dropped CIMD support recovers via DCR.

`Flow#refresh!` tests cover: refresh reconstructs the CIMD `client_id` without a stored `client_information`;
refresh raises when the authorization server no longer advertises CIMD support; stored `client_information`
takes precedence over the CIMD URL during refresh.

Conformance: `auth/basic-cimd` now passes 12/12 with no warnings. `bundle exec rake test`, `bundle exec rake rubocop`,
and `bundle exec rake conformance` are all green.

## Breaking Changes

None. The `client_id_metadata_document_url:` keyword is purely opt-in and defaults to `nil`.
When the keyword is omitted, the DCR flow is unchanged. Existing OAuth users see no behaviour change.
The CIMD path is only entered when both the user explicitly configures a URL and the authorization server
advertises support via `client_id_metadata_document_supported: true`.
2026-05-26 18:56:03 +09:00
Koichi ITO
fd2fd27625
Merge pull request #338 from atesgoral/warn-stdio-implicit-connect
Warn on implicit stdio initialization
2026-05-26 15:03:28 +09:00
Koichi ITO
c4c1f2bbc0
Merge pull request #360 from yuki3738/fix_typo_for_client_method_references
[Doc] Fix typos in MCP::Client method references
2026-05-25 03:20:04 +09:00
Yuki Minamiya
a28a343741 [Doc] Fix typos in MCP::Client method references
The methods are defined as singular `call_tool` and `read_resource`,
not plural `call_tools` and `read_resources`:
dd7daca/lib/mcp/client.rb (L315)
dd7daca/lib/mcp/client.rb (L331)
2026-05-25 03:01:23 +09:00
Ates Goral
b6462feef0 feat: warn on implicit stdio initialization 2026-05-23 12:07:28 -04:00
Koichi ITO
dd7dacae47
Merge pull request #359 from koic/case_insensitive_accept_header
Fix case-sensitive Accept header comparison
2026-05-24 00:00:43 +09:00
Koichi ITO
9b89620257 Fix case-sensitive Accept header comparison
## Motivation and Context

RFC 9110 defines media type comparison as case-insensitive,
but `parse_accept_header` compared types without normalizing case.
This caused `Application/JSON` or `TEXT/Event-Stream` to be rejected
with 406 Not Acceptable.

## How Has This Been Tested?

Added tests for mixed-case Accept headers:

- `Accept: Application/JSON, Text/Event-Stream` succeeds for POST
- `Accept: TEXT/EVENT-STREAM` succeeds for GET SSE

## Breaking Changes

None. This is a bug fix bringing behavior into conformance with RFC 9110.
2026-05-23 21:36:27 +09:00
Koichi ITO
aee8a0bfb6
Merge pull request #358 from koic/ping_server_to_client
Support server-to-client `ping` per MCP specification
2026-05-23 02:26:45 +09:00
Koichi ITO
40749855e6
Merge pull request #357 from koic/refactor_handle_delete_to_use_helper_methods
Refactor `handle_delete` to use `extract_session_id`
2026-05-23 02:26:16 +09:00
Koichi ITO
ac7598a13d Support server-to-client ping per MCP specification
## Motivation and Context

The MCP specification defines `ping` as a bidirectional utility: either party may issue it.
https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/ping

The previous PR added `MCP::Client#ping`. This PR adds the symmetric server-side send capability,
`ServerSession#ping`.

This aligns the Ruby SDK with the Python SDK (`ServerSession.send_ping`) and
the TypeScript SDK (`Server.ping()`), both of which expose a server-initiated ping.
In practice this enables a Ruby MCP server to health-check non-Ruby clients
(e.g., Claude Desktop, the Python or TypeScript SDK client) during long-running tool operations.

Scope is intentionally server-only: this PR does not add client-side inbound request dispatch,
which is a larger refactor outside the ping utility. A Ruby `MCP::Client` therefore still cannot receive
a server-initiated ping; that gap is tracked as a separate follow-up.

## How Has This Been Tested?

New file `test/mcp/server_session_ping_test.rb` covers:

- success (empty `result` returned)
- `related_request_id` propagated through the transport when a session ID is set
- `ValidationError` when the transport returns `nil`
- `ValidationError` when the transport returns a non-Hash `result`
- transport-level errors propagate unchanged
- ping succeeds without any client capability declaration (per spec, ping has no capability gate)

`test/mcp/server_context_test.rb` adds two tests for `ServerContext#ping` delegation
(happy path and `NoMethodError` when the session lacks `#ping`).

The existing server-side `ping` handler tests continue to pass unchanged.

## Breaking Changes

None. `MCP::ServerContext#ping` and `MCP::Server::ValidationError` are purely additive.
2026-05-22 11:28:51 +09:00
Koichi ITO
999f8b3f39 Refactor handle_delete to use extract_session_id
## Motivation and Context

`handle_post` and `handle_get` already use this helper, but
`handle_delete` inlined `request.env["HTTP_MCP_SESSION_ID"]`.
This aligns all three handlers consistently.

## How Has This Been Tested?

It has passed existing tests.

## Breaking Changes

None.
2026-05-21 15:42:51 +09:00
Koichi ITO
d17cc51c20
Merge pull request #355 from koic/release_0_17_0
Release 0.17.0
2026-05-20 12:45:12 +09:00
Koichi ITO
2efd0c32e1 Release 0.17.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-05-20 12:31:59 +09:00
Koichi ITO
2832bc0984
Merge pull request #353 from koic/add_oauth_2_1_client_support_for_mcp_authorization_flow
Add OAuth 2.1 client support for MCP authorization flow
2026-05-19 11:45:52 +09:00
Koichi ITO
7db22f4d5b
Reject duplicate initialize requests (#350)
## Motivation and Context

The Ruby SDK accepted duplicate `initialize` requests after a session was already initialized.
On stdio, a second `initialize` silently overwrote the per-session `clientInfo` and `clientCapabilities`
(including with an older `protocolVersion`). On Streamable HTTP, every `initialize` minted a fresh
`Mcp-Session-Id` and `ServerSession`, abandoning the originally negotiated session.

MCP specification (`2025-06-18` / `2025-11-25` lifecycle) states that the initialization phase
MUST be the first interaction between client and server;
re-initialization on an established session is not part of the defined lifecycle.
TypeScript SDK rejects duplicate `initialize` on a live session with HTTP 400 + JSON-RPC `-32600`
("Invalid Request: Server already initialized"), and Python SDK does not mint a new session
on duplicate `initialize`. The Ruby SDK was the outlier; this change aligns it with the TypeScript SDK.

- `ServerSession` tracks an `@initialized` flag, exposed via `initialized?` and
  set by `mark_initialized!` after a successful `initialize` response.
- `Server#init` raises `RequestHandlerError(error_type: :invalid_request)` when
  the session is already initialized, which the existing error mapping converts
  to JSON-RPC `-32600 Invalid Request`.
- `StreamableHTTPTransport#handle_post` short-circuits at the transport layer:
  duplicate `initialize` against a live session returns HTTP 400 + JSON-RPC
  `-32600`; a stale or expired `Mcp-Session-Id` returns 404 (evicting the expired entry
  instead of misreporting it as a duplicate).
- `handle_initialization` evicts the registered session and omits the `Mcp-Session-Id`
  header when the first `initialize` fails before `mark_initialized!` is reached,
  so retries do not collide with an orphaned ID.
- Non-Hash JSON-RPC POST bodies (e.g. batched arrays, which are not supported in `2025-11-25`)
  are explicitly rejected with HTTP 400 + JSON-RPC `-32600` rather than falling through to
  an unparseable Rack response.

## How Has This Been Tested?

- Server tests: a second `initialize` on the same `ServerSession` returns
  `code: -32600` and the original `clientInfo` is preserved.
- Streamable HTTP tests: duplicate `initialize` with a live `Mcp-Session-Id`
  returns HTTP 400 + `-32600` and the original session remains usable for
  subsequent `ping`; stale `Mcp-Session-Id` returns 404; an idle-expired
  session is evicted on duplicate `initialize` and returns 404; a failed
  `initialize` (invalid `jsonrpc` envelope) does not leak `Mcp-Session-Id` and
  leaves `@sessions` empty; an array body is rejected with HTTP 400 + `-32600`.
- Stdio tests: a second `initialize` on the same stdio session returns
  `code: -32600` and the original `clientInfo` is preserved.

## Breaking Changes

Clients that previously sent `initialize` more than once on the same session
now receive a JSON-RPC error with `code: -32600` for the second and later requests
instead of silently overwriting session state (stdio) or being re-issued
a new `Mcp-Session-Id` (Streamable HTTP). Clients that follow the MCP specification
(single `initialize` per session) are unaffected.

Additionally, non-Hash JSON-RPC POST bodies on Streamable HTTP now return
HTTP 400 + JSON-RPC `-32600` rather than falling through to a broken Rack response.
The previous behavior produced an unparseable response, so this is unlikely to
affect any working client.

Closes #349.
2026-05-18 00:00:23 -04:00
Koichi ITO
9caba3085d
Merge pull request #354 from koic/reject_non_hash_post_body_in_streamable_http_transport
Reject non-Hash JSON-RPC bodies in `StreamableHTTPTransport`
2026-05-18 09:23:57 +09:00
Koichi ITO
993dbf514e
Merge pull request #352 from koic/document_initialize_protocol_version_authority
Document `initialize` body `protocolVersion` is authoritative on Streamable HTTP
2026-05-18 09:23:22 +09:00
Koichi ITO
f62d813625 Reject non-Hash JSON-RPC bodies in StreamableHTTPTransport
## Motivation and Context

MCP 2025-11-25 does not support JSON-RPC batch (batch support was removed in 2025-06-18),
so request bodies are expected to be a single JSON-RPC message object. The previous code path:

```ruby
body = parse_request_body(body_string)
return body unless body.is_a?(Hash)
```

returned the parsed JSON value as if it were a Rack response when
the body was a JSON array (former batch shape), a string, a number,
or any other non-Hash JSON value. This produced a malformed Rack response
instead of a proper HTTP 400.

This was a pre-existing bug exposed during follow-up review of #347
(`MCP-Protocol-Version` header validation), which surfaced it but did not fix
the broken response shape for non-Hash bodies sent with a valid header.

### Behavior

- `parse_request_body` now raises a private `InvalidJsonError` on parse
  failure instead of returning a Rack response tuple. The overloaded
  return type and the `parse_error_tuple?` discriminator are gone.
- `handle_post` rescues `InvalidJsonError` and returns the same plain
  JSON 400 response as before (`{"error":"Invalid JSON"}`), so parse
  error handling is observably unchanged.
- Non-Hash parsed bodies (arrays, strings, numbers, booleans, null) now
  return HTTP 400 with a plain JSON body explaining that the body must
  be a single JSON-RPC message object, instead of producing a malformed
  Rack response.

The error response shape stays in the existing plain JSON style for
consistency with `validate_content_type`, `not_acceptable_response`,
and the other transport-level error helpers. Unifying all of these to
a JSON-RPC error envelope (matching the Python and TypeScript SDKs) is
deferred to a separate follow-up.

### SDK Comparison

- Python SDK (`src/mcp/server/streamable_http.py`): Already rejects
  non-Hash bodies (Array, primitive) with HTTP 400. Uses a JSON-RPC
  error envelope with `INVALID_PARAMS`.
- TypeScript SDK (`packages/server/src/server/streamableHttp.ts`):
  As of `main`, still processes JSON arrays as JSON-RPC batches and
  has not yet caught up with the 2025-06-18 batch removal. Primitives
  fail schema validation and return 400 with a JSON-RPC error envelope.

This change brings the Ruby SDK in line with the current MCP spec
(no batch). The Ruby SDK is now closer to the spec than the TypeScript
SDK's `main` branch on this specific point.

## How Has This Been Tested?

Existing regression test `test "handles POST request with invalid
JSON"` continues to pass unchanged (plain JSON response preserved).
Added new regression tests:

- POST with a JSON array body returns 400 with a clear error message
- POST with a non-object JSON body (e.g. `"foo"`) returns 400

`bundle exec rake test` and `bundle exec rake rubocop` both pass.

## Breaking Changes

None for compliant clients sending single JSON-RPC message objects.
Clients that were sending JSON arrays (batch requests, no longer
supported as of MCP 2025-11-25) or other non-object bodies will now
receive a proper HTTP 400 with a JSON error body instead of
the previous malformed Rack response; no client could have relied on
the broken pre-existing behavior.
2026-05-18 00:56:28 +09:00
Koichi ITO
5766069923 Add OAuth 2.1 client support for MCP authorization flow
## Motivation and Context

The MCP Authorization spec (2025-11-25) requires clients to support
Protected Resource Metadata discovery (RFC 9728), Authorization
Server Metadata discovery (RFC 8414), Dynamic Client Registration,
and OAuth 2.1 Authorization Code grant with PKCE (S256). The Ruby SDK
previously had no client-side OAuth support: the HTTP transport raised
`RequestHandlerError` on a 401 with no recovery, and 21 `auth/*` scenarios
were listed as known failures in `conformance/expected_failures.yml`.

This aligns the Ruby SDK with the Python and TypeScript SDKs,
both of which expose a pluggable OAuth client provider that drives
the full discovery + DCR + authorization + token exchange flow.
`MCP::Client::OAuth::Provider` mirrors that surface: callers supply
`client_metadata`, a `redirect_uri`, and pluggable `redirect_handler`
/ `callback_handler` hooks plus a token/client information storage.
`MCP::Client::OAuth::InMemoryStorage` is provided as a default.

`MCP::Client::HTTP` accepts a new optional `oauth:` keyword. When present,
the transport attaches `Authorization: Bearer` to every request,
and on a 401 parses `WWW-Authenticate` for the `resource_metadata` URL
and `scope` challenge, drives the discovery + DCR + authorization code flow
through the provider, and retries the failed request once with the acquired token.

Spec compliance details:

- The `WWW-Authenticate` parser handles multiple challenges
  (e.g. `Basic ..., Bearer ...` or `Bearer ..., DPoP ...`), extracting only
  the parameters that belong to the Bearer challenge.
- The PRM `resource` value is required to cover the MCP server URL
  (same scheme/host/port, with the PRM path as a prefix of the server path)
  before the flow continues, preventing redirection of issued tokens to a different audience.
- Both authorization and token requests always include a `resource`
  parameter (RFC 8707), defaulting to a canonicalized form of
  the MCP server URL when PRM does not advertise one.
- `client_secret_basic`, `client_secret_post`, and `none` token endpoint
  authentication methods are supported. When pre-registered client information
  specifies no `token_endpoint_auth_method`, the transport defaults to
  `client_secret_basic` per RFC 6749 §2.3.1 an dthe TS/Python SDK convention.
  Pre-registered client credentials supplied via `Storage#save_client_information`
  with either string or symbol keys are honored, skipping DCR.
- Scope resolution follows the spec order: the `WWW-Authenticate` challenge scope wins first,
  then PRM `scopes_supported`, and `Provider#scope` is the last-resort fallback only
  if neither is supplied (the provider-supplied scope must not pre-empt server-advertised scope).
- Token endpoint error responses (RFC 6749 §5.2) are parsed: a 4x with
  `error: "invalid_grant"` raises `Flow::InvalidGrantError`,
  so `MCP::Client::HTTP` can discard the stored refresh token only when
  the AS truly says it is dead. Generic `AuthorizationError`
  (5xx, network failures, other error codes) leaves the refresh token
  intact, so a transient AS outage does not force interactive reauth
  on the next attempt.
- The OAuth `state` parameter is compared via
  `OpenSSL.fixed_length_secure_compare` (with a `bytesize` guard) to
  prevent timing-based discovery of the expected value.
- The 401 retry guard is a request-scoped local variable, so an MCP server
  that keeps returning 401 is surfaced as an error after one
  retry rather than triggering an infinite re-authorization loop.

## How Has This Been Tested?

Unit tests cover PKCE generation, multi-challenge `WWW-Authenticate` parsing,
PRM and Authorization Server metadata URL builders, the full Flow orchestrator
(success path, state mismatch, missing PKCE support, skipping DCR for both string
and symbol-keyed preregistered client information, `client_secret_basic`
token endpoint authentication, PRM `resource` mismatch rejection, fallback to
the server URL when PRM omits `resource`, scope resolution preferring PRM
`scopes_supported` over `Provider#scope`, default `client_secret_basic` for
confidential clients without an explicit `token_endpoint_auth_method`,
and the new `InvalidGrantError` vs generic `AuthorizationError` split for
token endpoint rejections), and the HTTP transport behavior
(401 recovery + retry, no-provider fallthrough, no infinite loop on repeated 401,
no infinite loop on flow failure, refresh-token retention on transient 5xx from
the token endpoint).

Conformance: `bundle exec rake conformance` newly passes 16 `auth/*`
scenarios beyond the existing baseline, including
`auth/metadata-default`, `metadata-var{1,2,3}`,
`scope-from-www-authenticate`, `scope-from-scopes-supported`,
`scope-omitted-when-undefined`, `scope-retry-limit`,
`token-endpoint-auth-{basic,post,none}`, `pre-registration`,
`resource-mismatch`, and `offline-access-not-supported`. Remaining
`auth/*` scenarios stay in `expected_failures.yml`.
`bundle exec rake test rubocop` is clean.

## Breaking Changes

None. `MCP::Client::HTTP#initialize` accepts a new optional `oauth:`
keyword that defaults to `nil`, preserving existing behavior. When unset,
the transport raises `MCP::Client::RequestHandlerError` on a 401 exactly as before.
2026-05-17 00:48:41 +09:00
Koichi ITO
711f064088 Document initialize body protocolVersion is authoritative on Streamable HTTP
## Motivation and Context

When an `initialize` POST carries an `MCP-Protocol-Version` HTTP header that disagrees with
`params.protocolVersion` in the JSON-RPC body, the Streamable HTTP server accepts the request
and negotiates using the body value. The behavior was already encoded in `handle_post`
(the header check is skipped on `initialize`) but it was not stated in the code and there was
no regression test for the specific mismatch case.

MCP 2025-06-18 / 2025-11-25 only requires `MCP-Protocol-Version` on requests subsequent to
`initialize`, and the spec does not require the header and body to agree on the initial `initialize`.
All official MCP SDKs (TypeScript, Python, Rust, Java, Go, PHP) accept the mismatch and
treat the JSON-RPC body as authoritative.

## How Has This Been Tested?

Streamable HTTP tests: two new regression tests confirm that on an `initialize` POST
with a supported but mismatched `MCP-Protocol-Version` header, the server returns
HTTP 200 and the response's `result.protocolVersion` matches the JSON-RPC body value,
in both mismatch directions (header older / body newer, and header newer / body older).

## Breaking Changes

None. The behavior is unchanged: `initialize` requests with a mismatched `MCP-Protocol-Version` header
are still accepted, and the JSON-RPC body `params.protocolVersion` continues to drive negotiation.
This commit only adds an explanatory comment and regression tests.

Closes #351.
2026-05-17 00:03:49 +09:00
Koichi ITO
d6b5392831
Merge pull request #347 from koic/validate_mcp-protocol-version_header_in_streamable_http_transport
Validate `MCP-Protocol-Version` header in StreamableHTTPTransport
2026-05-15 00:45:51 +09:00
Koichi ITO
e35841afe8
Merge pull request #348 from koic/release_0_16_0
Release 0.16.0
2026-05-14 15:58:56 +09:00
Koichi ITO
c7b059cb91 Release 0.16.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-05-14 12:02:17 +09:00
Koichi ITO
9c2e438d4a Validate MCP-Protocol-Version header in StreamableHTTPTransport
## Motivation and Context

MCP 2025-11-25 (basic/transports#protocol-version-header) requires servers
to respond with `400 Bad Request` when receiving a request with an invalid
or unsupported `MCP-Protocol-Version` header:

> If the server receives a request with an invalid or unsupported
> `MCP-Protocol-Version`, it MUST respond with `400 Bad Request`.

The Ruby SDK was not reading the header at all, accepting any value
(including malformed strings like `not-a-version` and unsupported versions
like `1900-01-01`) and dispatching requests normally with HTTP 200.

## Behavior

`StreamableHTTPTransport` now validates the `MCP-Protocol-Version` header
on POST (non-initialize), GET, and DELETE requests. Missing headers are
accepted as before; the spec SHOULD requirement to default to `2025-03-26`
is intentionally left for a follow-up. The `initialize` POST is exempt
because the client does not know the negotiated version until the response
arrives, matching the Python (`src/mcp/server/streamable_http.py`) and
TypeScript (`packages/server/src/server/streamableHttp.ts`) SDKs.

The error response uses a JSON-RPC envelope with `code: -32600`
(`INVALID_REQUEST`) to match the Python SDK shape:

```json
{
  "jsonrpc": "2.0",
  "id": null,
  "error": {
    "code": -32600,
    "message": "Bad Request: Unsupported protocol version: <value>. Supported versions: ..."
  }
}
```

Validation order is session then protocol version, matching the Python and
TypeScript SDKs.

`handle_post` was reorganized so that non-Hash request bodies (e.g., JSON
arrays, which MCP 2025-11-25 no longer supports as batches) also pass
through the header check. The pre-existing broken response for Array
bodies sent with a valid header is unchanged and is tracked as a separate
follow-up.

## How Has This Been Tested?

Added regression tests covering:

- POST `initialize` ignores the header (bypass)
- POST non-initialize with unsupported / malformed / valid / missing values
- POST array body with unsupported value returns 400
- GET with unsupported / missing values
- DELETE with unsupported value in both stateful and stateless modes
- DELETE validates session before protocol version

`bundle exec rake test` and `bundle exec rake rubocop` both pass.

## Breaking Changes

Strictly additive for compliant clients. Third-party clients sending stale
or malformed `MCP-Protocol-Version` values will now receive `400` instead
of `200`, which is the intended spec behavior.

Fixes #346.
2026-05-14 01:03:21 +09:00
Koichi ITO
9d2fdd02ed
Merge pull request #342 from koic/json_schema_2020_12
Advertise JSON Schema 2020-12 dialect on emitted tool schemas
2026-05-13 10:38:26 +09:00
Koichi ITO
075ae28655
Merge pull request #344 from atesgoral/feature/output-schema-validation
feat: add opt-in tool output validation
2026-05-13 10:37:16 +09:00
Ates Goral
407b064140 feat: add opt-in tool output validation 2026-05-12 16:20:43 -04:00
Koichi ITO
d1e0afa158
Merge pull request #343 from atesgoral/fix/client-output-schema
fix: preserve client tool output schemas
2026-05-13 01:21:37 +09:00
Ates Goral
f67cc745c3 fix: preserve client tool output schemas 2026-05-11 21:44:26 -04:00
Koichi ITO
5153c399a9
Merge pull request #341 from atesgoral/dark-mode
Add dark mode support to docs
2026-05-12 01:17:34 +09:00
Ates Goral
5f94073503 docs: add dark mode support 2026-05-11 08:46:40 -04:00
Koichi ITO
1fc698bb8e Advertise JSON Schema 2020-12 dialect on emitted tool schemas
## Motivation and Context

MCP 2025-11-25 (SEP-1613) establishes JSON Schema 2020-12 as the default dialect
for MCP schema definitions.
 https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1613

The Ruby SDK was emitting tool input and output schemas with no `$schema` field,
leaving the dialect implicit and inconsistent with the TypeScript SDK
(`packages/core/src/util/standardSchema.ts`, which emits with `target: 'draft-2020-12'`)
and the Python SDK (which preserves `$schema` in its types and conformance fixtures).

`Tool::Schema#to_h` now includes `"$schema": "https://json-schema.org/draft/2020-12/schema"`
unless the user supplied a different `$schema` value, so clients see the canonical dialect URI
on the wire.

Runtime metaschema and argument validation remain on draft-04 because the `json-schema` gem
does not yet support 2020-12. Switching the runtime validator is left as a separate change
because it requires either replacing the gem or waiting for upstream 2020-12 support.

## How Has This Been Tested?

Updated `Tool::Schema#to_h` expectations across `input_schema_test`, `output_schema_test`,
`tool_test`, and the `tools/list` server tests to reflect the new `$schema` field.
Added focused regression tests:

- `to_h` preserves a user-supplied `$schema` URI rather than overwriting it
  (covered for both symbol-keyed input and the string-keyed Hash form that
  goes through the initializer's `symbolize_names` normalization)
- `validate_arguments` / `validate_result` continue to work when the user supplies
  a 2020-12 `$schema` URI on the schema (the validator strips the unknown top-level
  dialect URI before invoking the draft-04 validator, instead of raising `JSON::Schema::SchemaError`)
- `tools/list` JSON-RPC response includes the 2020-12 `$schema` on both `inputSchema`
  and `outputSchema` (transport-boundary assertion)

`bundle exec rake test` and `bundle exec rake rubocop` both pass.

## Breaking Changes

Additive change. Tolerant consumers of the `tools/list` payload are unaffected.
Consumers that strictly assert hash equality on the emitted `inputSchema` / `outputSchema`
need to account for the new `$schema` key, but no schema semantics change.

Schemas using 2020-12-only keywords (e.g. `prefixItems`, nested `$schema` on subschemas)
are still rejected by the draft-04 metaschema validator, as before.
Lifting that restriction depends on adopting a 2020-12-capable validator and is out of scope
for this change.
2026-05-11 13:44:30 +09:00
Koichi ITO
9090cb6ee3
Merge pull request #340 from koic/use_server_tools_instead_of_instance_variable_get
Use `Server#tools` instead of `instance_variable_get`
2026-05-10 23:34:35 +09:00
Koichi ITO
e47607defa
Merge pull request #293 from koic/conformance_client
Support running MCP client conformance tests against the Ruby SDK
2026-05-10 23:34:17 +09:00
Koichi ITO
25f3f9a33a Use Server#tools instead of instance_variable_get
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/301#discussion_r3046699277.

`Server#tools` method can be used instead of a hack like `instance_variable_get(:@tools)`.
2026-05-10 14:54:34 +09:00
Koichi ITO
811c56ae80
Merge pull request #339 from koic/remove_useless_condition_in_examples
Remove useless condition in example
2026-05-09 12:25:20 +09:00
Koichi ITO
9603b2fe93 Support running MCP client conformance tests against the Ruby SDK
## Motivation and Context

PR #248 introduced server conformance testing using `@modelcontextprotocol/conformance`.
This extends coverage to the client side so that `MCP::Client` behavior can also be validated against
the MCP specification.

### Scope

Client conformance is driven by the conformance runner, which spawns test servers for each scenario
and invokes `conformance/client.rb` against them. The client script delegates the MCP initialize
handshake to `MCP::Client#connect` and executes scenario-specific operations (for example listing
tools or calling a tool).

### Usage

Run all conformance tests (server + client):

```console
bundle exec rake conformance
```

Run a single client scenario:

```console
bundle exec rake conformance SCENARIO=initialize
```

List available scenarios:

```console
bundle exec rake conformance_list
```

## How Has This Been Tested?

Ran `bundle exec rake conformance` locally.

- Server conformance: 40 passed, 0 failed.
- Client conformance: 3 passed, 54 failed (all 54 listed in `expected_failures.yml`).

## Breaking Change

No. This change only adds test infrastructure under `conformance/` and does not modify SDK behavior.
2026-05-08 15:11:28 +09:00
Koichi ITO
d18698890a
Merge pull request #301 from amorde/define-tool-output-schema
Fix missing output_schema argument in 'define_tool' API
2026-05-07 11:56:29 +09:00
Koichi ITO
ebc656966a
Merge pull request #337 from koic/release_0_15_0
Release 0.15.0
2026-05-05 08:22:40 +09:00
Koichi ITO
32b6c9b646 Release 0.15.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.

It would be best to make the usage from #336 available sooner rather than later.
2026-05-05 08:14:35 +09:00
Koichi ITO
be8a5df160
Merge pull request #336 from koic/add_connect_to_stdio_client
Add client-level connect handshake to stdio transport
2026-05-04 22:27:57 +09:00
Koichi ITO
46b738e945 Add client-level connect handshake to stdio transport
## Motivation and Context

This commit implements Phase 1 of 3 for #334.

The MCP specification requires an `initialize` request followed by
a `notifications/initialized` notification before any other interaction.
PR #327 added `MCP::Client#connect` and `MCP::Client::HTTP#connect`
to expose this handshake explicitly for the HTTP transport,
but stdio remained on its private `initialize_session` lazy-init path,
inconsistent with the Python SDK (`ClientSession.initialize()`) and
TypeScript SDK (`Client.connect(transport)`),
both of which require an explicit handshake call regardless of transport.

The implicit init path on the first `send_request` is
preserved as a non-breaking compatibility shim. Public API added on `Stdio`:

- `connect(client_info:, protocol_version:, capabilities:)` performs the
  handshake, validates the negotiated `protocolVersion` against
  `MCP::Configuration::SUPPORTED_STABLE_PROTOCOL_VERSIONS`,
  caches the `InitializeResult`, and is idempotent.
- `connected?` reports handshake completion.
- `server_info` exposes the cached `InitializeResult`.

Documentation and examples are updated so new users learn the explicit pattern
from the start.

## How Has This Been Tested?

Fifteen regression tests cover: explicit handshake, `server_info` caching,
idempotence, custom keyword arguments, JSON-RPC error response, missing
or non-Hash `result`, unsupported protocol version with state rollback,
state rollback when the `notifications/initialized` write fails,
retry after a failed handshake, and the `connected?` / `server_info` lifecycle.

The pre-existing stdio tests pass without modification, verifying that
the implicit-init compatibility path still works.

## Breaking Changes

None for the typical "implicit init via `client.tools` / `client.call_tool`" usage.
Existing stdio clients keep working unchanged.

Three observable behavior changes for code that inspects transport state directly:

- `Client#connected?` for a never-initialized stdio client returns `false`
  (previously fell through to a `true` default via the `respond_to?` fallback).
- `Client#server_info` for stdio returns the cached `InitializeResult`
  after the handshake (previously always `nil` via the fallback).
- The implicit handshake path now validates the server's negotiated
  protocol version, raising `RequestHandlerError` for unsupported versions.
  Production servers that return one of the supported versions are unaffected;
  this closes a pre-existing spec-conformance gap on stdio.
2026-05-03 15:57:22 +09:00
Koichi ITO
3d9437736b
Merge pull request #332 from koic/feature_cancellation
Support `notifications/cancelled` per MCP specification
2026-05-03 15:56:55 +09:00
Koichi ITO
704d362a12 Remove useless condition in example
## Motivation and Context

The example files `examples/http_client.rb` and `examples/streamable_http_client.rb` are
intended to be run as standalone scripts and are not designed to be reused as modules (e.g., via `require`).
The `if __FILE__ == $PROGRAM_NAME` guard therefore serves no purpose and is removed.

## How Has This Been Tested?

Manually verified that each example script can still be executed directly
(`ruby examples/http_client.rb`, `ruby examples/streamable_http_client.rb`).
No automated tests cover files under `examples/`.

## Breaking Changes

None. The files under `examples/` are standalone scripts and are not part of the gem's public API.
2026-05-03 15:55:13 +09:00
Koichi ITO
a97e391353 Support notifications/cancelled per MCP specification
## Motivation and Context

The MCP specification defines `notifications/cancelled` so either party can stop
a previously-issued in-flight request. The Ruby SDK declared the method constant
but had no receive logic, no in-flight tracking, and no way for handlers to participate
in cancellation; cancellation notifications fell through to the unsupported-method path.

This PR implements the **server-side** half of the spec. The server stops processing
the targeted request cooperatively and suppresses its JSON-RPC response, matching
the Python SDK's anyio `CancelScope` and the TypeScript SDK's `RequestHandlerExtra.signal`.
Cancellation is observable by every user-overridable request handler:

- `Tool.call` (tools/call)
- prompt templates (prompts/get)
- blocks registered via `resources_read_handler` / `completion_handler` /
  `resources_subscribe_handler` / `resources_unsubscribe_handler` / `define_custom_method`

Each handler opts in by declaring a `server_context:` keyword and polls `server_context.cancelled?`
or calls `server_context.raise_if_cancelled!` (raising `MCP::CancelledError`) inside long-running work.
Handlers that keep their existing `|params|` (or `|args|`) signature continue to work unchanged.

On `StreamableHTTPTransport`, cancelling a parent `tools/call` automatically cancels n
ested server-to-client requests (`sampling/createMessage`, `elicitation/create`);
the nested `send_request` raises `MCP::CancelledError` and a cancel notification is routed to
the peer on the parent's POST response stream. `StdioTransport` is single-threaded and blocks on `$stdin.gets`,
so it deliberately does not propagate nested cancellation.
Tools running on stdio still observe cancellation between calls via `server_context.cancelled?`.

The design is cooperative-only (no `Thread#raise`) because preemptive cancellation is unsafe
across Rack adapters and arbitrary handler code. The `initialize` request is never cancellable,
satisfying the spec rule that it MUST NOT be cancelled. Unknown / completed / duplicate cancel notifications
are silently ignored per the spec.

`MCP::Client#cancel` (an equivalent that aborts the calling thread's synchronous wait) is deferred to a follow-up PR.

Ref: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation

## How Has This Been Tested?

`test/mcp/cancellation_test.rb` covers the `MCP::Cancellation` token contract.

`test/mcp/server_cancellation_test.rb` covers end-to-end cancellation:

- A handler spins on `cancelled?` in a background thread; the test sends `notifications/cancelled`
  and asserts the handler observed cancellation and the JSON-RPC response was suppressed.
  Each user-overridable handler type (tool, prompt template, resources/read, completion, custom method)
  has its own regression test.
- `initialize` is not cancellable; unknown / duplicate / late-after-completion cancels are silently ignored.
- The `reason` propagates into the `cancellation_reason` instrumentation field.
- Custom transports implementing only the abstract `(method, params = nil)` contract keep working;
  the new kwargs (`session_id:`, `related_request_id:`, `parent_cancellation:`, `server_session:`)
  are silently dropped when the transport's signature does not declare them.

`StreamableHTTPTransport` tests cover nested cancellation, hook deregistration after normal completion
(so a late parent cancel does not emit a stray `notifications/cancelled`), and the first-writer-wins race
when a real response and a cancel arrive concurrently.

## Breaking Change

None. `MCP::ServerContext#initialize` gains an optional `cancellation:` keyword (defaults to `nil`),
and `StreamableHTTPTransport#send_request` / `#send_notification` gain optional cancellation kwargs.
The abstract `Transport` base class and `StdioTransport` keep their existing `(method, params = nil)` signatures,
and custom transports following those signatures continue to work. `StreamableHTTPTransport` now dispatches
client-originated notifications through `ServerSession#handle_json` before returning 202;
previously these were accepted without dispatch, but the existing handlers for `notifications/initialized`
and `notifications/progress` were already no-ops, so no user-visible effect is expected.
Adding `server_context:` to a handler block is strictly opt-in.
2026-05-03 04:02:22 +09:00
Koichi ITO
541200ffcd
Merge pull request #335 from atesgoral/ag/use-sdk-streamable-http-client-example
Update Streamable HTTP client example to use MCP::Client
2026-05-03 00:24:30 +09:00
Ates Goral
933cf94a09 Update Streamable HTTP client example to use SDK client 2026-05-02 10:09:17 -04:00
Koichi ITO
0c46dcd0ab
Merge pull request #327 from atesgoral/ag/client-connect-handshake
Add client-level connect for initialize handshake
2026-05-02 15:40:55 +09:00
Ates Goral
ddfbfad81e Add client-level connect for initialize handshake 2026-05-01 20:17:45 -04:00
Koichi ITO
38d952adce
Merge pull request #333 from koic/tool_validation_error
Return tool argument validation failures as tool execution errors
2026-05-02 01:09:26 +09:00
Koichi ITO
48d4fb9272 Return tool argument validation failures as tool execution errors
## Motivation and Context

MCP 2025-11-25 (SEP-1303) clarifies that input validation errors for `tools/call`
should be returned as Tool Execution Errors (`{ content: [...], isError: true }`)
rather than as JSON-RPC `-32602` protocol errors, so models can observe
the validation message and self-correct on a follow-up call.
https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1303

This is a clarification rather than a brand-new requirement: the 2024-11-05, 2025-03-26,
and 2025-06-18 specifications all defined two error categories with overlapping language
("Invalid arguments" listed under Protocol Errors *and* "Invalid input data" listed under
Tool Execution Errors), leaving the routing of JSON-Schema validation failures ambiguous.
The Ruby SDK had selected the "Protocol Errors / Invalid arguments" interpretation,
while the TypeScript SDK (`packages/server/src/server/mcp.ts`, which wraps
`validateToolInput` errors via `createToolError`) and Python SDK's FastMCP
(which routes through the generic `is_error=True` path) had selected the other.
SEP-1303 in 2025-11-25 disambiguates this by replacing the bullets with
"Malformed requests (requests that fail to satisfy CallToolRequest schema)"
under Protocol Errors and "Input validation errors (e.g., date in wrong format,
value out of range)" under Tool Execution Errors, and explicitly states that the latter
"contain actionable feedback that language models can use to self-correct".

`tool_not_found` continues to be returned as a JSON-RPC `-32602` protocol error since
the spec change only covers input validation.

## How Has This Been Tested?

Updated existing tests that previously asserted `-32602` and "Invalid arguments" /
"Missing required arguments" in the JSON-RPC error data to instead
assert `result[:isError] == true` with the same text in the `content` block.
Added new regression tests covering:

- Instrumentation still records `:missing_required_arguments` and
  `:invalid_schema` on the new non-raising path
- Nested schema validation failure (deep arrays of objects with
  required fields) returns a tool execution error rather than a
  protocol error
- `tool_not_found` continues to return JSON-RPC `-32602` (regression
  guard against accidentally widening the change)

`bundle exec rake test` and `bundle exec rake rubocop` both pass.

## Breaking Changes

Yes. Clients that detect tool argument validation errors via `error.code == -32602`
will need to switch to inspecting `result.isError == true` and reading `result.content[].text`.

Note that the Ruby SDK's previous behavior was a defensible reading of the 2024-11-05 /
2025-03-26 / 2025-06-18 spec wording. The 2025-11-25 disambiguation is what makes
the previous behavior non-conforming; the TypeScript and Python SDKs already shipped
the new behavior.
2026-05-01 03:18:29 +09:00
Koichi ITO
2ad3d21492
Merge pull request #331 from koic/remove_obsolete_transport_module
Remove obsolete `MCP::Transports` module
2026-04-29 00:20:50 +09:00
Koichi ITO
82f85611f3
Merge pull request #330 from koic/fix_typo_for_read_resources
[Doc] Fix a typo in README.md
2026-04-28 12:22:43 +09:00
Koichi ITO
ceea440ca5 Remove obsolete MCP::Transports module
## Motivation and Context

`lib/mcp/transports/stdio.rb` was a deprecated shim that redirected users
from `MCP::Transports::StdioTransport` to `MCP::Server::Transports::StdioTransport`.
It has been 10 months since the migration path was introduced, providing sufficient time
for users to update their code.

## How Has This Been Tested?

All tests pass (`rake test`), and no code in the repository references `MCP::Transports`
or `mcp/transports/stdio`.

## Breaking Changes

`require "mcp/transports/stdio"` and `MCP::Transports::StdioTransport` are removed.
Use `require "mcp/server/transports/stdio_transport"` and `MCP::Server::Transports::StdioTransport` instead.
2026-04-26 15:54:07 +09:00
Koichi ITO
07fb0a8e56 [Doc] Fix a typo in README.md
The method name in the client feature list was `MCP::Client#read_resources` (plural),
but the actual method is `MCP::Client#read_resource` (singular).
2026-04-25 11:23:30 +09:00
Koichi ITO
27ff7e4bd1
Merge pull request #329 from koic/release_0_14_0
Release 0.14.0
2026-04-24 14:44:19 +09:00
Koichi ITO
b03ec40d23 Release 0.14.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-04-24 11:27:41 +09:00
Koichi ITO
a89047af60
Merge pull request #328 from koic/support_json_response_mode
Support JSON response mode for `StreamableHTTPTransport`
2026-04-23 14:05:50 +09:00
Koichi ITO
017b0bb4c9 Support JSON response mode for StreamableHTTPTransport
## Motivation and Context

The MCP Streamable HTTP specification allows servers to return POST responses as either
`text/event-stream` (SSE) or `application/json`:

> If the input is a JSON-RPC request, the server MUST either return `Content-Type: text/event-stream`,
> to initiate an SSE stream, or `Content-Type: application/json`, to return one JSON object.

See: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server

The TypeScript and Python SDKs support a configurable JSON response mode
via `enableJsonResponse` / `is_json_response_enabled`.

JSON response mode is suitable for simple tool servers that do not need server-initiated requests.
It avoids SSE framing overhead and returns a single JSON object for the POST response.

## Behavior

- POST responses use `Content-Type: application/json` and return a single JSON object.
- The POST `Accept` header requirement is relaxed to `application/json` only
  (matching the Python SDK's lenient behavior).
- Request-scoped notifications (`progress`, `log`) cannot ride along with the single-object response
  and are silently dropped.
- Session-scoped standalone notifications (`resources/updated`, `elicitation/complete`)
  and broadcast notifications (`tools/list_changed`, etc.) continue to flow to clients connected
  to the GET SSE stream.
- All server-to-client requests (`sampling/createMessage`, `roots/list`, `elicitation/create`)
  raise an error in JSON response mode.
- Combines with `stateless: true` for simple single-response servers without session tracking.

## How Has This Been Tested?

Added tests for JSON response mode:

- POST request returns `application/json` response
- Accept header validation requires only `application/json`
- Returns 406 when Accept header is missing
- Accepts wildcard `*/*` in Accept header
- Request-scoped notifications (progress, log) during tool execution are silently dropped
- Request-scoped notifications do not leak to GET SSE even when connected
- Session-scoped standalone notifications are delivered via GET SSE
- Broadcast notifications are delivered via GET SSE
- `send_request` raises for `sampling/createMessage`, `roots/list`, `elicitation/create`
- Combined with `stateless: true`: POST returns JSON without a session ID, GET returns 405

## Breaking Changes

None. JSON response mode is opt-in via `enable_json_response: true`.
The default behavior (SSE responses) is unchanged.
2026-04-22 08:30:28 +09:00
Koichi ITO
a2706cc7ef
Merge pull request #326 from atesgoral/ag/client-session-termination
Add HTTP client close for explicit session termination
2026-04-21 10:05:45 +09:00
Ates Goral
ff3a42f3fb Add HTTP client close for explicit session termination
Per MCP spec, clients that no longer need a session SHOULD send an HTTP
DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
terminate it. Servers MAY respond with 405 Method Not Allowed when they
don't support client-initiated termination.

`MCP::Client::HTTP#close` sends the DELETE with session headers, clears
local session state regardless of outcome, and is a no-op when no
session has been established.

https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management
2026-04-20 13:58:41 -04:00
Koichi ITO
0770e27c67
Merge pull request #325 from atesgoral/ag/client-session-tracking
Track Mcp-Session-Id and protocol version in HTTP client
2026-04-21 00:11:27 +09:00
Ates Goral
07226b7cf1 Track Mcp-Session-Id and protocol version in HTTP client
Per the Streamable HTTP spec, if the server returns an Mcp-Session-Id
header during `initialize`, the client MUST include it on subsequent
requests. Capture the session ID and protocol version from the
`initialize` response and attach them automatically on subsequent
POSTs.

Per the Protocol Version Header section of the spec, the client MUST
also include `MCP-Protocol-Version` on all subsequent requests so the
server can respond based on the negotiated protocol version.

Map 404 responses to a new `SessionExpiredError` (a subclass of
`RequestHandlerError` for backward compatibility) and clear local
session state so callers can start a fresh session with a new
`initialize` request, as required by the spec.

- https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management
- https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#protocol-version-header

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 00:23:07 -04:00
Koichi ITO
baa093dfd5
Merge pull request #324 from koic/ping_client_to_server
Support `ping` client API per MCP specification
2026-04-20 12:15:21 +09:00
Koichi ITO
cbe81453fd
Merge pull request #323 from atesgoral/ag/client-202-accepted
Handle 202 Accepted response in HTTP client
2026-04-20 11:16:09 +09:00
Ates Goral
cfc42dbfe7 Handle 202 Accepted response in HTTP client
Per the Streamable HTTP spec, a server returns 202 Accepted with no
body as the ACK for a JSON-RPC notification or response. The client
previously errored on 202 because it fell through Content-Type
dispatch. Short-circuit to return nil before Content-Type handling so
fire-and-forget messages (e.g. notifications/initialized) no longer
raise.

https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 14:06:07 -04:00
Koichi ITO
5c0fee309f
Merge pull request #322 from atesgoral/ag/client-sse-parser
Parse SSE responses in HTTP client via event_stream_parser
2026-04-20 00:58:59 +09:00
Ates Goral
b832933f9f Parse SSE responses in HTTP client via event_stream_parser
The Streamable HTTP spec allows servers to respond with either
`application/json` or `text/event-stream`. The client previously
rejected the latter. Add SSE parsing via the optional
`event_stream_parser` gem (users add it to their Gemfile when their
server uses SSE), dispatch on the response Content-Type, and scan the
event stream for the first JSON-RPC response message.

Document the new optional dependency in both the README's HTTP
Transport Layer section and docs/building-clients.md.

No other Streamable HTTP features (202 handling, session IDs,
`connect`, DELETE termination) are included here; those will land in
follow-up PRs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-19 11:54:03 -04:00
Koichi ITO
493321ca46 Support ping client API per MCP specification
## Motivation and Context

The MCP specification defines the `ping` utility for verifying that the peer of
a connection is still responsive. The Ruby SDK server side already replies to
incoming `ping` requests with an empty result, but `MCP::Client` had no public API
to send a `ping` request. Users had to build the JSON-RPC payload themselves and
call the transport directly.

This adds a client-side counterpart to the existing server handler and aligns
the Ruby SDK in spirit with the Python and TypeScript SDKs, which expose
`ClientSession.send_ping` and `Client.ping` respectively. Those SDKs validate
the response envelope via type schemas (`EmptyResult` / `EmptyResultSchema`) and raise
their validation library's generic exception (Pydantic's `ValidationError` / Zod's `ZodError`).
The Ruby client applies a Hash type check on `result`
(matching Python's behavior of requiring a dict while allowing arbitrary contents)
and raises a new `MCP::Client::ValidationError` for malformed responses,
keeping `MCP::Client::ServerError` reserved for JSON-RPC error responses.

## How Has This Been Tested?

Client tests cover:

- request structure (method is `ping`, no `params`)
- empty result on success
- `ServerError` on JSON-RPC error response
- `ValidationError` on a response missing `result`
- `ValidationError` on a `result` of the wrong type (e.g., String)
- propagation of transport-level errors raised by `transport.send_request`

The existing server-side `ping` handler tests continue to pass unchanged.

## Breaking Changes

None. `MCP::Client#ping` and `MCP::Client::ValidationError` are purely additive.
The server-side `ping` handler behavior is unchanged.
2026-04-19 23:14:50 +09:00
Koichi ITO
2edba778f0
Merge pull request #313 from koic/support_resource_subscription
Support resource subscriptions per MCP specification
2026-04-19 16:38:39 +09:00
Koichi ITO
d80fba4fbc Support resource subscriptions per MCP specification
## Motivation and Context

The MCP specification defines `resources/subscribe`, `resources/unsubscribe`,
and `notifications/resources/updated` for clients to monitor resource changes:
https://modelcontextprotocol.io/specification/2025-03-26/server/resources#subscriptions

The Ruby SDK had stub (no-op) handlers but provided no way for server developers to
customize subscription behavior or send update notifications.

Following the Python SDK approach, the SDK does not track subscription state internally.
Server developers register handler blocks and manage their own subscription state,
allowing flexibility for different subscription semantics
(per-session tracking, persistence, debouncing, etc.).

Three methods are added:

- `Server#resources_subscribe_handler`: registers a handler for
  `resources/subscribe` requests
- `Server#resources_unsubscribe_handler`: registers a handler for
  `resources/unsubscribe` requests
- `ServerSession#notify_resources_updated`: sends a
  `notifications/resources/updated` notification to the subscribing client

`ServerContext#notify_resources_updated` is also added so that tool handlers
can send the notification scoped to the originating session.

## How Has This Been Tested?

All tests pass (`rake test`), RuboCop is clean. New tests cover custom handler registration
for `resources/subscribe` and `resources/unsubscribe`, session-scoped `notify_resources_updated` notifications,
error handling, and `ServerContext` delegation.

## Breaking Changes

None.
2026-04-19 03:48:46 +09:00
Koichi ITO
e73c444aad
Merge pull request #320 from koic/feature_pagination
Support pagination per MCP specification
2026-04-19 03:24:22 +09:00
Koichi ITO
b97b922a36 Support pagination per MCP specification
## Motivation and Context

The MCP specification defines cursor-based pagination for list operations that
may return large result sets:
https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/pagination

Pagination allows servers to yield results in smaller chunks rather than all at once,
which is especially important when connecting to external services over the internet.

The Ruby SDK previously returned complete arrays for all list endpoints
(`tools/list`, `resources/list`, `prompts/list`, `resources/templates/list`)
without pagination support. This adds cursor-based pagination.

### Server-side

A new `MCP::Server::Pagination` module is introduced (mixed into `MCP::Server`)
that provides the `paginate` helper for slicing a collection by cursor and
a `cursor_from` helper that extracts the cursor from the request params
while rejecting non-Hash inputs with `-32602 Invalid params` per the specification.

`MCP::Server.new` accepts a new `page_size:` keyword argument.
When `nil` (the default), all items are returned in a single response,
preserving the existing behavior. When set to a positive integer,
list responses include a `nextCursor` field if more pages are available.

`Server#page_size=` is a validating setter that rejects anything other than
`nil` or a positive `Integer`, raising `ArgumentError` on invalid inputs.
The constructor routes through the setter, so both `Server.new(page_size: 0)`
and `server.page_size = -1` raise.

Cursors are string tokens carrying a zero-based offset, treated as opaque by
clients. Cursor inputs are validated to be strings per the MCP spec;
invalid cursors (non-string, non-numeric, negative, or out-of-range) raise
`RequestHandlerError` with error code `-32602 (Invalid params)` per the spec.

### Client-side: two complementary APIs

The SDK exposes two API shapes for listing, each serving a different use case:

1. **Single-page with cursor** (`client.list_tools(cursor:)`,
   `list_resources`, `list_resource_templates`, `list_prompts`): each call issues
   one JSON-RPC request and returns a result object (`MCP::Client::ListToolsResult` etc.)
   carrying the page items and an optional `next_cursor`.
   These methods match the single-page-with-cursor convention used by the Python SDK
   (`session.list_tools(params=PaginatedRequestParams(cursor=...))`)
   and the TypeScript SDK (`client.listTools({ cursor })`). The method name and
   the `cursor` parameter name are identical across the three SDKs,
   so pagination code translates directly between languages.

2. **Whole-collection** (`client.tools`, `client.resources`, `client.resource_templates`,
   `client.prompts`): auto-iterates through all pages and returns a plain array of items,
   guaranteeing the full collection regardless of the server's `page_size` setting.
   The auto-pagination loop tracks previously seen cursors in a set and exits if the server
   revisits any of them, guarding against both immediate repeats and multi-cursor cycles
   (e.g. `A -> B -> A`). This mirrors Rust SDK's `list_all_*` convenience methods,
   though the Ruby names are preserved from the pre-pagination 0.13.0 API for backward compatibility.
   Future rename to `list_all_*` is left as a TODO in the source.

Result classes are `Struct`s named to mirror Python SDK's `ListToolsResult` /
`ListPromptsResult` / etc. to align naming with other SDKs. Each struct exposes
its page items (e.g. `result.tools`), an optional `next_cursor` for continuation,
and an optional `meta` field mirroring the MCP `Result` type's `_meta` response field
so servers that decorate list responses do not lose metadata through the client.

### Ruby-specific ergonomics

`Server.new(page_size:)` and the `Pagination` module are Ruby-specific.
The Python and TypeScript SDKs do not expose a built-in `page_size` helper;
developers there re-implement cursor slicing inside each handler.
In Ruby, setting `page_size:` on the server is enough for the SDK to handle
the slicing across the four built-in list endpoints.

### README

A Pagination section documents both the server-side `page_size:` option and
the client-side iteration patterns, including an explicit note that each `list_*` call
is a single JSON-RPC round trip whose response size depends on the server's `page_size`,
and that `client.tools` / `.resources` / `.resource_templates` / `.prompts` return
the complete collection when needed.

## How Has This Been Tested?

- Added tests for the `Pagination` module (`test/mcp/server/pagination_test.rb`),
  server-side pagination (`test/mcp/server_test.rb`), and client-side pagination
  (`test/mcp/client_test.rb`).
- Added and existing tests pass. `rake rubocop` is clean and `rake conformance` passes.

## Breaking Changes

None. This is a new feature addition. Existing code continues to work unchanged:
`page_size` defaults to `nil` on the server (returns all items, no `nextCursor`),
and the client's existing `tools` / `resources` / `resource_templates` / `prompts` methods
continue to return complete arrays by transparently iterating through pages.
2026-04-18 18:23:30 +09:00
Koichi ITO
7b5533c809
Merge pull request #315 from koic/support_roots
Add `roots/list` and `notifications/roots/list_changed` support
2026-04-18 02:06:32 +09:00
Koichi ITO
ecaeefb606
Merge pull request #319 from koic/update_homepage_url_in_gemspec
Update homepage URL in gemspec
2026-04-18 00:44:17 +09:00
Koichi ITO
52f8384e9d
Merge pull request #314 from koic/remove_redundant_respond_to_flush
Remove redundant `respond_to?(:flush)` guard in `StreamableHTTPTransport`
2026-04-18 00:43:42 +09:00
Koichi ITO
8ccdb5a540 Update homepage URL in gemspec
Follow-up to #317.

This PR updates the homepage URL to https://ruby.sdk.modelcontextprotocol.io
and makes it consistent with the link on the SDK page:
https://modelcontextprotocol.io/docs/sdk
2026-04-17 02:10:47 +09:00
Koichi ITO
dab6a4bf99
Merge pull request #318 from koic/release_0_13_0
Release 0.13.0
2026-04-16 10:16:11 +09:00
Koichi ITO
954078d90c Release 0.13.0
New features and changes have landed, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.

In particular, releasing "Make `StreamableHTTPTransport` a Rack application"
soon would help keep it consistent with the README.md for Rails integration.
2026-04-16 03:45:51 +09:00
Koichi ITO
eb3c948d0d
Merge pull request #317 from koic/update_homepage
[Doc] Update homepage with just-the-docs theme
2026-04-16 03:05:36 +09:00
Koichi ITO
63f0ca6360
Merge pull request #316 from koic/restructure_readme_usage_section
[Doc] Restructure README Usage section to align heading granularity
2026-04-16 03:05:02 +09:00
Koichi ITO
0c5432b027 [Doc] Update homepage with just-the-docs theme
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/181.

The landing page at https://ruby.sdk.modelcontextprotocol.io previously only listed version links
to RubyDoc.info. Add multi-page documentation using the just-the-docs Jekyll theme with
sidebar navigation, search, and code highlighting.
Pages: Introduction, Installation, Building Servers, and Building Clients.

This PR introduces a basic set of pages. Additional content can be added incrementally in future updates.
2026-04-15 22:48:15 +09:00
Koichi ITO
acdf85f039 [Doc] Restructure README Usage section to align heading granularity
Group the Rails (mount) and Rails (controller) examples under a new
`Streamable HTTP Transport` heading so they sit one level below the
transport-type headings instead of alongside `Stdio Transport`.

Also move the single-process and sticky-sessions caveat up to the
`Streamable HTTP Transport` section since it applies to both Rails
integration styles rather than only the controller approach.
2026-04-15 14:51:12 +09:00
Koichi ITO
66d0722e41
Merge pull request #263 from koic/make_streamable_http_transport_a_standard_rack_app
Make `StreamableHTTPTransport` a Rack application
2026-04-15 11:01:40 +09:00
Koichi ITO
eeb130171d Add roots/list and notifications/roots/list_changed support
## Motivation and Context

MCP spec (2025-11-25) defines Roots as a mechanism for clients to expose filesystem boundaries
(directories and files) to servers:
https://modelcontextprotocol.io/specification/2025-11-25/client/roots

This enables servers to understand which parts of the filesystem they can operate on.

This adds support for the two roots protocol interactions:

- `roots/list` -- server-to-client request to retrieve the client's filesystem roots
- `notifications/roots/list_changed` -- client-to-server notification when roots change

`roots/list` is a one-to-one request between a server and a specific client,
so `list_roots` is exposed only at the session level
(`ServerSession#list_roots`), matching the Python SDK approach and aligning with PR #311 for sampling.

`Server#on_roots_list_changed` registers a callback for the client notification,
which is server-wide and does not require session scoping.

Also fixes `notifications/roots/list_changed` capability checking: as a client-originated notification,
it should not require server-side capability declaration.

## How Has This Been Tested?

New test file `test/mcp/server_roots_test.rb` with 8 test cases covering session-scoped `list_roots`,
capability validation and fallback, `on_roots_list_changed` callback registration, and client capability storage.
Updated `test/mcp/methods_test.rb` to reflect the corrected capability checks. All tests pass (`rake test`),
RuboCop is clean.

## Breaking Changes

None.
2026-04-15 02:39:14 +09:00
Koichi ITO
7a3259d4da
Merge pull request #311 from koic/remove_server_sampling_direct_call
Remove `Server#create_sampling_message` direct call
2026-04-15 02:33:26 +09:00
Koichi ITO
3b1777adb3
Merge pull request #312 from koic/support_elicitation
Support `elicitation/create` per MCP specification
2026-04-15 02:22:55 +09:00
Koichi ITO
1ddd26b10b Remove redundant respond_to?(:flush) guard in StreamableHTTPTransport
## Motivation and Context

The stream object always responds to flush, so the conditional check is unnecessary.

## How Has This Been Tested?

All existing tests are passing.

## Breaking Changes

None.
2026-04-14 10:14:58 +09:00
Koichi ITO
985fd03ecb Support elicitation/create per MCP specification
## Motivation and Context

The MCP specification (2025-11-25) defines elicitation as a server-to-client
request mechanism that allows servers to request user input during tool execution:
https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation

This aligns with the Python SDK, which also exposes separate methods for form and URL mode elicitation.
Three methods are added following the Python SDK's API design:

- `create_form_elicitation`: collects structured data via JSON Schema
- `create_url_elicitation`: directs users to external URLs for sensitive
  interactions (OAuth, credentials, etc.)
- `notify_elicitation_complete`: notifies the client that a URL mode
  interaction has completed

`URLElicitationRequiredError` (error code `-32042`) is defined as a subclass of `RequestHandlerError`
with its own `error_code` and `error_data` attributes. `JsonRpcHandler#handle_request_error` is
extended to check for these attributes so that MCP-specific error codes can be propagated without
embedding MCP knowledge in the generic JSON-RPC layer.

## How Has This Been Tested?

- Unit tests for `ServerSession` form/URL mode, capability checks, nil
  capabilities, notification, and `URLElicitationRequiredError`
- `ServerContext` delegation tests for all three elicitation methods
- `JsonRpcHandler` tests for custom error code and fallback behavior
- `Methods` capability test for `NOTIFICATIONS_ELICITATION_COMPLETE`
- Conformance tests pass (40/40), including `tools-call-elicitation`,
  `elicitation-sep1034-defaults`, and `elicitation-sep1330-enums`
- All tests pass (`rake test`), RuboCop is clean
- Verified form mode elicitation end-to-end with a sample MCP server
  running in Claude Code

## Breaking Changes

None. This is a new feature addition.
2026-04-13 15:21:45 +09:00
Koichi ITO
f41272f2a0
Merge pull request #309 from koic/add_around_request_hook_for_request_instrumentation
Add `around_request` hook for request instrumentation
2026-04-13 01:15:19 +09:00
Koichi ITO
a235572777 Remove Server#create_sampling_message direct call
## Motivation and Context

Sampling is a one-to-one request/response interaction between a server and a specific client.
`Server#create_sampling_message` does not scope requests to a specific session, which could
lead to unintended broadcasts on multi-client transports. `ServerSession#create_sampling_message`
should be used instead, as it routes the request to the correct client session.

This aligns with the Python SDK, which also exposes sampling only at the session level.

## How Has This Been Tested?

Existing tests updated to call `ServerSession#create_sampling_message` instead of
`Server#create_sampling_message`. All tests pass (`rake test`), RuboCop is clean,
and conformance tests pass.

## Breaking Changes

`Server#create_sampling_message` is removed without a deprecation warning.
The sampling feature was released recently and the method was not intended
to be the primary API for this feature.
2026-04-12 17:05:46 +09:00
Koichi ITO
88248fc4c7
Merge pull request #310 from koic/add_meta_field_support
Add `_meta` field to resource, content, and result classes
2026-04-12 00:45:20 +09:00
Koichi ITO
ff8e6b897d
Merge pull request #307 from koic/release_0_12_0
Release 0.12.0
2026-04-11 15:30:07 +09:00
Koichi ITO
0ad9a89d97 Add _meta field to resource, content, and result classes
## Motivation and Context

MCP 2025-11-25 spec defines a `_meta` general field on many types,
but the Ruby SDK only exposed it on `Tool` and `Prompt`.
To attach metadata (e.g. MCP Apps CSP hints on resource contents),
consumers had to subclass existing classes and override `to_h`.

Add a `meta:` keyword argument and `_meta` serialization to:

- `Resource::Contents`, `Resource::TextContents`, `Resource::BlobContents`
- `Resource`, `ResourceTemplate`
- `Content::Text`, `Content::Image`, `Content::Audio`, `Content::EmbeddedResource`
- `Tool::Response` (`CallToolResult`)
- `Prompt::Result` (`GetPromptResult`)

This aligns the Ruby SDK with the Python and TypeScript SDKs, which both expose `_meta` on these types.

Resolves #308.

## How Has This Been Tested?

Added unit tests for each updated class covering two patterns: `_meta` present
(asserts the value is reflected in `to_h[:_meta]`) and `_meta` omitted
(asserts no `:_meta` key in `to_h`, i.e., `.compact` behavior).
All existing tests continue to pass, and `rake rubocop` is clean.

## Breaking Changes

None. All new `meta:` parameters are optional keyword arguments defaulting to `nil`.
The `to_h` output stays backward-compatible because `nil` values are removed by the existing `.compact` call,
so existing callers require no changes.
2026-04-11 15:08:55 +09:00
Koichi ITO
fab6f81261 Add around_request hook for request instrumentation
## Motivation and Context

`instrumentation_callback` fires after request execution, making it impossible to wrap
requests with Application Performance Monitoring (APM) spans (e.g. Datadog tracing).
This adds `around_request`, which wraps request handling and allows executing code
before and after each request.

For example, to wrap requests with a Datadog trace:

```ruby
MCP.configure do |config|
  config.around_request = ->(data, &request_handler) {
    Datadog::Tracing.trace("mcp.#{data[:method]}") do
      request_handler.call
    end
  }
end
```

`instrumentation_callback` is soft-deprecated in favor of `around_request`.

## How Has This Been Tested?

Added tests for `around_request` in configuration, instrumentation,
and server test files. All existing tests continue to pass.

## Breaking Changes

`around_request` itself is optional and defaults to a pass-through,
and `instrumentation_callback` continues to work as before.

However, `instrument_call` now accepts a `server_context:` keyword and its block is invoked
without arguments (previously `yield block` passed the block Proc as an argument).
This affects anyone mixing `MCP::Instrumentation` into their own classes,
though the public `Server` API is unchanged.

Resolves #302.
2026-04-11 13:54:47 +09:00
Koichi ITO
27c71bb293 Release 0.12.0
New features and fixes have been added, making it a good time to cut a release.
Further feature proposals can be incorporated in future releases.
2026-04-11 05:06:30 +09:00
Koichi ITO
a05d941edd
Merge pull request #306 from koic/support_customizing_faraday_client_in_mcp_client_http
Support customizing the Faraday client in `MCP::Client::HTTP`
2026-04-10 13:42:41 +09:00
Koichi ITO
17334c2e8b
Merge pull request #304 from koic/validate_post_content_type
Validate Content-Type on POST requests
2026-04-10 11:26:13 +09:00
Koichi ITO
af99a303e1 Make StreamableHTTPTransport a Rack application
## Motivation and Context

Add `call(env)` to `StreamableHTTPTransport`, making it a Rack application
that works with `mount`, `run`, and Rack middleware.

Refactor examples to use Rack middleware classes for MCP logging instead of proc wrappers,
demonstrating idiomatic Rack composition with the new `run(transport)` pattern.

Update README.md with mount and controller integration patterns.

Closes #59, #60

## How Has This Been Tested?

Added tests for `call(env)` as a Rack app. All tests pass.

## Breaking Change

No breaking changes. All existing APIs are preserved:

- `StreamableHTTPTransport.new(server)` continues to work as before.
- `handle_request(request)` is unchanged. The new `call(env)` is a purely additive public method.
2026-04-10 04:55:25 +09:00
Koichi ITO
89281cac57
Merge pull request #305 from koic/auto_set_server_transport
Auto-set `server.transport` in `Transport#initialize`
2026-04-10 04:51:44 +09:00
Koichi ITO
de38804ed7 Auto-set server.transport in Transport#initialize
## Motivation and Context

Transport subclasses (StreamableHTTPTransport, StdioTransport) already
receive the server in their constructor, but users must manually call
`server.transport = transport` after creating a transport instance.
This is boilerplate that can be eliminated by setting the connection
automatically in `Transport#initialize`.

## How Has This Been Tested?

All existing tests pass. Redundant `server.transport = transport` lines
were removed from tests, examples, README.md, and conformance server.

## Breaking Changes

None. Existing code that manually sets `server.transport = transport`
continues to work (idempotent assignment).
2026-04-09 12:08:55 +09:00
Koichi ITO
f7952e8aaf Support customizing the Faraday client in MCP::Client::HTTP
## Motivation and Context

`MCP::Client::HTTP` builds its Faraday connection internally in a private `client` method
with no way to customize the middleware stack or adapter.
Users who need observability (request/response recording, failure logging) or
a different HTTP adapter must override a private method, coupling to an internal API.

This accepts an optional block in `MCP::Client::HTTP.new` that yields the Faraday builder
after default middleware is configured, allowing users to add custom middleware or swap
the HTTP adapter.

## How Has This Been Tested?

Added a test that verifies custom headers set via the block are included in requests.
All existing tests continue to pass.

## Breaking Changes

None. The block argument is optional, so existing code is unaffected.

Resolves #303
2026-04-09 05:08:49 +09:00
Koichi ITO
81e81c359e Validate Content-Type on POST requests
## Motivation and Context

The MCP Streamable HTTP specification requires POST request bodies to
be JSON-RPC messages with `Content-Type: application/json`. The Ruby
SDK did not validate Content-Type, accepting requests with any or no
Content-Type. The Python SDK validates this and returns 415
Unsupported Media Type for non-JSON Content-Types.

## How Has This Been Tested?

Added tests for Content-Type validation:

- POST without Content-Type returns 415
- POST with `Content-Type: text/plain` returns 415
- POST with `Content-Type: application/json; charset=utf-8` succeeds

## Breaking Changes

POST requests without `Content-Type: application/json` now return
415 Unsupported Media Type. This is a spec compliance fix.
2026-04-08 19:40:55 +09:00
Koichi ITO
2822e00b62
Merge pull request #299 from koic/update_rails_controller_example_in_readme
[Doc] Update Rails controller example in README.md
2026-04-07 11:37:51 +09:00
Koichi ITO
0762879abe
Merge pull request #297 from koic/sticky_session_for_multi_server
[Doc] Note sticky session requirement for multi-instance deployments
2026-04-07 11:37:33 +09:00
Koichi ITO
ffd5b7bdd3
Merge pull request #295 from koic/update_sampling_example
[Doc] Restructure sampling section to lead with tool usage
2026-04-07 11:36:53 +09:00
Eric Amorde
f6c95a0c97 Fix missing output_schema argument in 'define_tool' API 2026-04-06 14:45:56 -07:00
Koichi ITO
ba79d53c97
Merge pull request #296 from koic/rename_session_stream_key
Rename `session[:stream]` to `session[:get_sse_stream]`
2026-04-06 03:30:22 +09:00
Koichi ITO
17604beff9 [Doc] Update Rails controller example in README.md
The following two points have been updated:

## 1. Use ActionController::API in README controller example

`ActionController::Base` includes CSRF protection which rejects POST requests
without an authenticity token. MCP clients do not send CSRF tokens,
so the controller example should inherit from `ActionController::API` instead.

## 2. Use `stateless: true` for `StreamableHTTPTransport.new`

The controller creates a new transport per request,
so the session stored on the previous transport is lost.
Without `stateless: true`, the second request with `Mcp-Session-Id`
returns 404 because the new transport has an empty session map.

To share sessions via `Mcp-Session-Id` across requests, there are two approaches.
One is persisting the transport in a class variable. The other is mounting
the transport as a Rack app via https://github.com/modelcontextprotocol/ruby-sdk/pull/263.

Both approaches maintain sessions, so features that depend on `server_context`
within the SDK (Progress, Sampling) work correctly. However, per-request
user-specific context such as `server_context: { user_id: current_user.id }`
cannot be passed since the server is shared across all requests.
2026-04-06 03:22:59 +09:00
Koichi ITO
1b45c4382b [Doc] Note sticky session requirement for multi-instance deployments
## Motivation and Context

PR #290 documented that `StreamableHTTPTransport` requires a single-process server.
However, when running multiple server instances behind a load balancer, requests for
the same session must be routed to the same instance since session state is stored in memory.

This adds a note about using sticky sessions (session affinity) based on the `Mcp-Session-Id` header.

## How Has This Been Tested?

Documentation-only change.

## Breaking Changes

None.
2026-04-06 03:20:46 +09:00
Koichi ITO
3f43b1feac [Doc] Restructure sampling section to lead with tool usage
Sampling is primarily used within tool execution via `server_context.create_sampling_message`,
but the documentation led with the less common direct `Server#create_sampling_message` usage.
This ordering could mislead readers into thinking direct usage is the recommended approach.
2026-04-06 03:17:18 +09:00
Koichi ITO
2a1c9b7ac9
Merge pull request #298 from koic/doc_restructure
[Doc] Reorganize README to surface key information earlier
2026-04-06 03:04:42 +09:00
Koichi ITO
f23d1b5088
Merge pull request #300 from koic/release_0_11_0
Release 0.11.0
2026-04-06 03:04:25 +09:00
Koichi ITO
46f6c20cf3 Release 0.11.0
New features and fixes have been added, and it seems like a good time to cut a release.
Subsequent feature proposals can continue to be incorporated into future releases.
2026-04-06 02:35:49 +09:00
Koichi ITO
f9096347bc [Doc] Move stdio before Rails Controller in Usage
For Usage, stdio is easier to try first than a Rails controller.
Moved stdio to the top and placed Rails Controller after it.

Only sections were moved. No content was changed.
2026-04-05 13:29:47 +09:00
Koichi ITO
63f51bbc26 [Doc] Move Usage to the top of the README.md
Users are more likely to want to see Usage first, rather than a feature introduction like Sampling.
Sampling has been moved below Resource Templates so that Usage appears at the top.

Only sections were moved. No content was changed.
2026-04-05 13:29:47 +09:00
Koichi ITO
ee4a7bb4df [Doc] Move Custom methods to the bottom of the README
Custom methods are an advanced feature and may not be appropriate for the top of the README.md.
Move them to the bottom of the page.

Only sections were reorganized with headings. No content was changed.
2026-04-05 13:29:30 +09:00
Koichi ITO
65069ed1cc Rename session[:stream] to session[:get_sse_stream]
Follow-up to #294.

The generic `:stream` key does not convey that it refers to the GET SSE stream,
making it harder to distinguish from `session[:post_request_streams]` introduced in #294.
2026-04-05 03:51:55 +09:00
Koichi ITO
40b048b8f4
Merge pull request #294 from koic/post_response_sse_stream
Support POST response SSE streams for server-to-client messages
2026-04-05 02:56:19 +09:00
Koichi ITO
8278ca6586 Support POST response SSE streams for server-to-client messages
## Motivation and Context

The MCP Streamable HTTP specification defines that servers can return POST responses
as SSE streams and send server-to-client JSON-RPC requests and notifications through them:

> If the input is a JSON-RPC request, the server MUST either return
> `Content-Type: text/event-stream`, to initiate an SSE stream, or
> `Content-Type: application/json`, to return one JSON object.

If the server initiates an SSE stream:

> The server MAY send JSON-RPC requests and notifications before
> sending the JSON-RPC response. These messages SHOULD relate to the
> originating client request.

See: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server

Previously, when a GET SSE stream was connected, the Ruby SDK sent POST response bodies through
the GET stream and returned a 202 HTTP status for the POST itself. When no GET SSE stream was
connected, the SDK correctly returned `application/json` responses. The 202 behavior with GET SSE
was non-compliant with the specification, which requires POST requests to return `text/event-stream`
or `application/json`. Additionally, since GET SSE is optional per the specification, clients that
did not establish a GET SSE connection could not receive server-to-client messages (e.g.,
`sampling/createMessage`, log notifications) during request processing.

With this change, `handle_regular_request` always returns the POST response as an SSE stream for stateful sessions.
Each POST response stream is stored in `session[:post_request_streams]` keyed by `related_request_id` (the JSON-RPC request ID),
enabling correct routing when multiple POST requests are processed concurrently on the same session.
Server-to-client messages with a `related_request_id` are routed to the originating POST response stream only;
when `related_request_id` is nil, the GET SSE stream is used.

The TypeScript and Python SDKs already support this pattern.

### Internal Changes

`JsonRpcHandler.handle` and `JsonRpcHandler.handle_json` now pass both `method_name` and `request_id` to the method finder block.
This allows `Server#handle_request` to receive `related_request_id` directly from the protocol layer.
Without this, `related_request_id` would need to be relayed as a keyword argument through `Server#handle_json`,
`ServerSession#handle_json`, and `dispatch_handle_json`, unnecessarily exposing it on public method signatures.
This follows the same design as the TypeScript and Python SDKs, where the protocol layer extracts the request ID
and propagates it to the handler context.

## How Has This Been Tested?

Added tests for POST response stream:

- `send_request` via POST response stream (sampling with and without GET SSE)
- `send_notification` via POST response stream (logging without GET SSE)
- `progress` notification via POST response stream (without GET SSE)
- POST request returns SSE response even with GET SSE connected
- Session-scoped notifications (log, progress) are sent to POST
  response stream, not GET SSE stream
- `active_stream` does not fall back to GET SSE when
  `related_request_id` is given but request stream is missing

Updated existing tests to handle SSE response format where applicable.

## Breaking Changes (spec compliance fix)

POST responses for JSON-RPC requests in stateful sessions now return `Content-Type: text/event-stream`
instead of being sent through the GET SSE stream with a 202 HTTP status. Clients that relied on receiving responses
via the GET SSE stream will need to read the POST response body instead. This is a spec compliance fix:
the MCP specification requires POST requests to return `text/event-stream` or `application/json`,
not 202 with the response on a separate GET stream.
2026-04-04 19:20:31 +09:00
Koichi ITO
0d700d7d7d
Merge pull request #282 from koic/support_sampling
Support `sampling/createMessage` per MCP specification
2026-04-04 06:46:34 +09:00
Koichi ITO
da5f9225ac Support sampling/createMessage per MCP specification
## Motivation and Context

The MCP specification defines `sampling/createMessage` to request LLM completions from the client.
The Ruby SDK did not yet support server-to-client requests,
so the server had no way to ask the client to sample an LLM.
This caused the `tools-call-sampling` conformance test to fail.

This adds `Server#create_sampling_message` to send a `sampling/createMessage` request
to the client via the transport layer. The method validates that the client declared
the `sampling` capability during initialization, and optionally checks the
`sampling.tools` capability when tools or tool_choice parameters are provided.

On the transport side, `Transport#send_request` is introduced as an abstract method,
with implementations in both `StdioTransport` and `StreamableHTTPTransport`.
Each transport assigns a unique request ID, sends the JSON-RPC request to the client,
and blocks until the client responds.

Client capabilities are stored per session via `ServerSession`, so validation is scoped
to the originating client. `ServerSession#create_sampling_message` uses
`build_sampling_params` for capability validation and sends the request directly through
the transport with the session ID, following the same pattern as `notify_progress`.

`Server#create_sampling_message` is the public API for single-client transports
(e.g., StdioTransport).

For multi-client transports (e.g., StreamableHTTPTransport),
`ServerSession#create_sampling_message` must be used to route requests to the correct client.
Tools using `server_context.create_sampling_message` automatically route to the correct session
regardless of transport.

`StreamableHTTPTransport#send_request` requires `session_id` to prevent broadcasting sampling requests
to all connected clients. Missing or invalid session IDs raise explicit errors instead of silently failing.

The `include_context` parameter is soft-deprecated in the MCP specification but is included
for compatibility with existing clients that declare the `sampling.context` capability.
Python and TypeScript SDKs also retain this parameter.

Ref: https://modelcontextprotocol.io/specification/latest/server/utilities/sampling

## How Has This Been Tested?

Added comprehensive tests in `test/mcp/server_sampling_test.rb` covering required and optional parameters,
capability validation, error handling, nil-param omission, per-session capability isolation,
and HTTP init capability scoping.

Added transport tests in `test/mcp/server/transports/stdio_transport_test.rb` and
`test/mcp/server/transports/streamable_http_transport_test.rb` for `send_request` round-trip behavior,
error responses, stateless mode rejection, missing session_id, invalid session_id, and no-active-stream error.

Conformance: `tools-call-sampling` is removed from expected failures. The conformance server's `TestSampling`
tool now calls `server_context.create_sampling_message` instead of returning a stub error.

This aligns the Ruby SDK with the MCP specification and other SDK implementations.

## Breaking Changes

None for end users.
`Transport#send_request` is a new abstract method. `ServerSession#create_sampling_message` is a new method.
2026-04-04 05:55:27 +09:00
Koichi ITO
6f94d64ece
Merge pull request #290 from koic/thread_model_requirement
[Doc] Clarify that `StreamableHTTPTransport` requires a single-process server
2026-04-04 05:51:58 +09:00
Koichi ITO
5285277892
Merge pull request #291 from koic/improvement_close_streams_outside_mutex
Close streams outside mutex in session cleanup
2026-04-04 05:50:16 +09:00
Koichi ITO
66428ace04 Close streams outside mutex in session cleanup
## Motivation and Context

`cleanup_session_unsafe` was closing streams inside the mutex, which could block all session
operations if `stream.close` is slow or blocks (e.g., waiting for network I/O).
The original `reap_expired_sessions` avoided this by closing streams outside the mutex,
but the other 6 call sites of `cleanup_session_unsafe` did not, creating an inconsistency.

This change separates stream closing from session deletion. `cleanup_session_unsafe`
now only removes the session from `@sessions` and returns it.
All callers close streams outside the mutex via `close_stream_safely`,
ensuring consistent behavior and preventing mutex contention from blocking I/O.

## How Has This Been Tested?

Added tests that verify streams are closed outside the mutex by using `Mutex#try_lock`
inside mock stream close callbacks:

- `reap_expired_sessions closes stream outside mutex`
- `send_notification closes stream outside mutex on write error`

## Breaking Changes

None. This is an internal improvement with no change to public API behavior.
2026-04-04 03:46:00 +09:00
Koichi ITO
9ebb42a536 [Doc] Clarify that StreamableHTTPTransport requires a single-process server
## Motivation and Context

`StreamableHTTPTransport` stores session and SSE stream state in memory using
instance variables (`@sessions`, `@mutex`). This design requires all HTTP requests
to be handled within the same process to share state.

Process-based servers like Unicorn fork separate worker processes that do not share memory,
which breaks session management and SSE connections.
This requirement is not obvious from the current documentation.

## How Has This Been Tested?

Documentation-only change.

## Breaking Changes

None.
2026-04-04 02:08:01 +09:00
Koichi ITO
c563036f88
Merge pull request #289 from koic/feature_completion_complete
Support `completion/complete` per MCP specification
2026-04-04 01:39:03 +09:00
Koichi ITO
52371a31be
Merge pull request #286 from koic/use_rescue_standard_error_for_stream_close
Use `rescue StandardError` for stream close
2026-04-04 01:32:27 +09:00
Koichi ITO
6bada5fb05
Merge pull request #283 from koic/add_claude_md
Add CLAUDE.md referencing AGENTS.md
2026-04-04 01:32:00 +09:00
Koichi ITO
295dd781ae
Merge pull request #288 from koic/add_extra_rdoc_files_to_gemspec
Add `extra_rdoc_files` to gemspec
2026-04-04 01:31:38 +09:00
Koichi ITO
88e1f9a840 Support completion/complete per MCP specification
## Motivation and Context

The MCP specification defines `completion/complete` for providing autocompletion
suggestions for prompt arguments and resource template URIs.
The Ruby SDK previously had only a no-op handler that returned empty results,
with no way for users to define custom completion logic.

This aligns the Ruby SDK with the Python and TypeScript SDKs,
both of which support user-defined completion handlers.

## How Has This Been Tested?

Server tests cover: default handler, custom handler for `ref/prompt` and `ref/resource`,
context argument passing, 100-item truncation, and error responses for nonexistent prompts,
nonexistent resource templates, and invalid ref types.

Client tests cover: request structure, context parameter inclusion,
and fallback when result is missing.

## Breaking Changes

None. The existing default no-op handler behavior is preserved.
The `completion_handler` method is purely additive. The only behavioral change
is that `completion/complete` requests now validate that the referenced prompt
or resource template exists before calling the handler,
returning an `invalid_params` error for unknown references.
2026-04-03 01:35:07 +09:00
Koichi ITO
17e9603474 Add extra_rdoc_files to gemspec
This makes `LICENSE` and `README.md` available to RDoc documentation.
The files remain included in the gem package because `Gem::Specification#files`
automatically merges `extra_rdoc_files`.
2026-04-03 00:38:24 +09:00
Koichi ITO
d3f400f525 Use rescue StandardError for stream close
## Motivation and Context

Replace bare `rescue` with explicit `rescue StandardError` in stream cleanup to clarify intent,
with a comment explaining why.
In Ruby, `rescue` without an exception class is equivalent to `rescue StandardError`,
so this is a readability improvement with no behavior change.

## How Has This Been Tested?

Existing tests pass.

## Breaking Changes

None.
2026-04-02 03:48:56 +09:00
Koichi ITO
6669601b5d
Merge pull request #285 from sqrlington/fix/revert-error-handling-to-protocol-errors
Fix: return protocol errors for invalid arguments and server errors
2026-04-02 03:37:46 +09:00
Sarah Pickett
8dd0379f16
fix: return protocol errors for invalid arguments and server errors
Per the MCP spec, invalid arguments and server errors are protocol
errors (JSON-RPC error responses), not tool execution errors
(isError: true). PR #165 moved all error cases to isError: true,
and PR #231 only restored protocol errors for unknown tools.

This fixes the remaining two cases: invalid arguments (-32602) and
server errors (-32603).

Ref: https://modelcontextprotocol.io/specification/2024-11-05/server/tools#error-handling
2026-04-01 14:22:56 -04:00
Koichi ITO
0141d487fc Add CLAUDE.md referencing AGENTS.md
CLAUDE.md delegates to AGENTS.md via the `@AGENTS.md` directive,
avoiding duplication of project guidelines.
2026-04-01 01:03:43 +09:00
Koichi ITO
56319902dd
Merge pull request #280 from koic/fix_stdio_test_thread_race
Join server threads before closing IO pipes in stdio client tests
2026-03-31 15:51:32 +09:00
Koichi ITO
11f2e05945
Merge pull request #281 from koic/client_raise_on_error_response
Fix client methods silently swallowing JSON-RPC error responses
2026-03-31 15:14:47 +09:00
Koichi ITO
eacf51ec94
Merge pull request #279 from koic/refactor__use_symbolize_names
Use `symbolize_names: true` in `JSON.parse` calls
2026-03-31 15:14:01 +09:00
Koichi ITO
590feb13a5 Fix client methods silently swallowing JSON-RPC error responses
## Motivation and Context

Client methods (`tools`, `resources`, `resource_templates`, `prompts`, `read_resource`, `get_prompt`, `call_tool`)
silently swallowed JSON-RPC error responses by falling back to empty defaults. This did not conform to JSON-RPC 2.0,
which clearly distinguishes error responses from success responses.
Both the Python SDK (`MCPError`) and TypeScript SDK (`ProtocolError`) raise exceptions on error responses.
The Ruby SDK was the only one silently discarding them.

Introduces a common `request` method that handles JSON-RPC request construction and error checking in one place,
replacing the duplicated `transport.send_request` calls across all client methods.

## How Has This Been Tested?

Added tests for each affected method verifying that `ServerError` is raised with the correct `code`, `message`,
and `data` attributes.

## Breaking Changes

The previous behavior of silently returning empty defaults on server errors did not conform to JSON-RPC 2.0.
Error responses should be surfaced to callers, not swallowed.
Callers that relied on the silent fallback behavior will need to rescue `MCP::Client::ServerError`.
2026-03-31 12:51:11 +09:00
Koichi ITO
760346818e Join server threads before closing IO pipes in stdio client tests
Background threads simulating server responses could race with the `ensure` block
that closes IO pipes, intermittently producing this warning depending on thread scheduling:

```console
#<Thread:0x00007fb69290cbd0 test/mcp/client/stdio_test.rb:28 run>
terminated with exception (report_on_exception is true):
test/mcp/client/stdio_test.rb:55:in `write': stream closed in another thread (IOError)
```

Store each background thread in a `server_thread` variable and call `server_thread&.join(1)`
at the top of each `ensure` block to wait for the thread to finish before closing pipes.
2026-03-31 04:34:21 +09:00
Koichi ITO
3a68937bb7 Use symbolize_names: true in JSON.parse calls
Replace custom `deep_transform_keys` in `Tool::Schema` and
string key access in `StreamableHTTPTransport` with
the `symbolize_names: true` option of `JSON.parse`.

This aligns `StreamableHTTPTransport` with `StdioTransport`,
which already uses `symbolize_names: true`.
2026-03-31 04:15:42 +09:00
Koichi ITO
6b415e2f54
Merge pull request #278 from koic/cname_ruby_sdk_modelcontextprotocol_io
[Doc] Add CNAME file to preserve custom domain across deployments
2026-03-31 00:16:53 +09:00
Koichi ITO
5c51f7dde8 [Doc] Add CNAME file to preserve custom domain across deployments
Accessing https://ruby.sdk.modelcontextprotocol.io/ is expected to show
the content of https://modelcontextprotocol.github.io/ruby-sdk/,
but it currently does not. This change fixes that issue.

The `generate-gh-pages.sh` script cleans all files from the gh-pages branch root
before copying from `docs/`. This removes the CNAME file that GitHub Pages uses for
the custom domain, causing `ruby.sdk.modelcontextprotocol.io` to break on every release.
https://github.com/modelcontextprotocol/ruby-sdk/blob/v0.10.0/bin/generate-gh-pages.sh#L91-L93

By placing the CNAME file in `docs/`, it will be automatically copied to `gh-pages` during each deployment.
https://github.com/modelcontextprotocol/ruby-sdk/blob/v0.10.0/bin/generate-gh-pages.sh#L95-L97

The following is a PR related to the configuration of ruby.sdk.modelcontextprotocol.io.

- https://github.com/modelcontextprotocol/ruby-sdk/pull/181
- https://github.com/modelcontextprotocol/dns/pull/14
- https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2486
2026-03-30 13:27:58 +09:00
Koichi ITO
03a78f9344
Merge pull request #277 from koic/release_0_10_0
Release 0.10.0
2026-03-30 11:26:59 +09:00
Koichi ITO
73b018c1e1 Release 0.10.0
This release focuses primarily on changes related to the internal session architecture.
It also removes some publicly exposed methods that are effectively obsolete.
2026-03-30 06:13:16 +09:00
Koichi ITO
f0186d08b0
Merge pull request #268 from koic/security__missing_session_expiry_controls
Support session expiry controls for `StreamableHTTPTransport`
2026-03-30 05:46:07 +09:00
Koichi ITO
9f3435aeb6
Merge pull request #276 from koic/remove_notify_progress_broadcast
Remove `Server#notify_progress` broadcast API
2026-03-29 15:35:17 +09:00
Koichi ITO
b89f6e315d Remove Server#notify_progress broadcast API
## Motivation and Context

`Server#notify_progress` broadcasts progress notifications to all connected clients.
Progress notifications are tied to a specific request's `progressToken` and have no
meaningful broadcast use case. Neither the Python SDK nor the TypeScript SDK provides
a server-level progress broadcast capability.

The MCP specification requires that progress notifications only reference tokens
provided in an active request:

> Progress notifications MUST only reference tokens that:
> - Were provided in an active request
> - Are associated with an in-progress operation

Ref: https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/progress

Broadcasting progress to all clients does not comply with this requirement,
since clients that did not originate the request have no matching `progressToken`.

The introduction of `ServerSession` for per-connection state (#275) made
this removal possible: `Progress` and `ServerContext` now use `notification_target:`
(a `ServerSession`) to route notifications to the originating session only.

### Changes

- Removed `Server#notify_progress` entirely. The method is no longer needed as
  `notification_target` in `call_tool_with_args` now passes `session` directly
  (nil when no session is available, in which case `Progress#report` and
  `ServerContext#notify_log_message` are no-ops).
- Removed `ServerContext#notify_progress` as well. Progress notifications should
  only be sent via `server_context.report_progress`, which enforces the correct
  `progressToken` from the originating request.
- Added nil guards to `Progress#report` and `ServerContext#notify_log_message`
  for when no session is available.
- Rewrote progress tests to use `ServerSession#handle` instead of
  `Server#handle`, reflecting that progress notifications are always session-scoped.
- Removed 4 tests that called `server.notify_progress` directly as a public broadcast API.
- Removed `notify_progress` from the README.md notification methods list.
- Removed the "Server-Side: Direct `notify_progress` Usage" section from the README.md.

Progress notifications should be sent via `server_context.report_progress` inside tool handlers,
which automatically scopes them to the originating client session.

## Breaking Changes

Progress notifications are scoped to a specific request via `progressToken` per the MCP specification,
so the broadcast behavior of `Server#notify_progress` was a spec violation.
This is treated as a bug fix and is made without a deprecation period.
This aligns the Ruby SDK with the Python and TypeScript SDKs, neither of which provides
a server-level progress broadcast API.

`Server#notify_progress` and `ServerContext#notify_progress` are no longer available.
Users should use `server_context.report_progress` inside tool handlers instead, which
provides session-scoped delivery with the correct `progressToken`.

This feature was only recently introduced in mcp 0.9.0:
https://github.com/modelcontextprotocol/ruby-sdk/releases/tag/v0.9.0

So an early release should help limit its impact on adoption.
2026-03-29 15:11:28 +09:00
Koichi ITO
49fc501abc Support session expiry controls for StreamableHTTPTransport
## Motivation and Context

The MCP specification recommends expiring session IDs to reduce session hijacking risks:
https://modelcontextprotocol.io/specification/latest/basic/security_best_practices#session-hijacking

Several other SDKs (Go, C#, PHP, Python) already implement session expiry controls, but
the Ruby SDK did not. Sessions persisted indefinitely unless explicitly deleted or
a stream error occurred, leaving abandoned sessions to accumulate in memory.

This adds a `session_idle_timeout:` option to `StreamableHTTPTransport#initialize`. When
set, sessions that receive no HTTP requests for the specified duration (in seconds) are
automatically expired. Expired sessions return 404 on subsequent requests (GET and POST),
matching the MCP specification's behavior for terminated sessions. Each request resets
the idle timer, so actively used sessions are not interrupted.

A background reaper thread periodically cleans up expired sessions to handle orphaned
sessions that receive no further requests. The reaper only starts when
`session_idle_timeout` is configured.

The default is `nil` (no expiry) for backward compatibility, consistent with the Python
SDK's approach. The Python SDK recommends 1800 seconds (30 minutes) for most deployments:
https://github.com/modelcontextprotocol/python-sdk/pull/2022

Resolves #265.

## How Has This Been Tested?

Added tests for session expiry, idle timeout reset, reaper thread lifecycle, input
validation, and default behavior in `streamable_http_transport_test.rb`. All existing
tests continue to pass.

## Breaking Change

None. The default value of `session_idle_timeout` is `nil`, which preserves the existing
behavior of sessions never expiring. The new `last_active_at` field in the internal
session hash is not part of the public API. Existing code that instantiates
`StreamableHTTPTransport.new(server)` or
`StreamableHTTPTransport.new(server, stateless: true)` continues to work without changes.
2026-03-29 12:34:58 +09:00
Koichi ITO
8969edf4b9
Merge pull request #274 from koic/reject_missing_session_id
Reject POST requests without session ID in stateful mode
2026-03-29 12:34:00 +09:00
Koichi ITO
0cc8a300b8
Merge pull request #275 from koic/introduce_server_sessoin_for_per_connection_state
Introduce `ServerSession` for per-connection state
2026-03-29 11:46:24 +09:00
Koichi ITO
719e5e7fee Introduce ServerSession for per-connection state
## Motivation and Context

The Ruby SDK uses a 1-Server-to-many-sessions model where session-specific state
(`@client`, `@logging_message_notification`) is stored on the shared `Server` instance.
This causes the last client to connect to overwrite state for all sessions,
and requires `session_id` to be threaded through method signatures for session-scoped notifications.

The Python SDK avoids this by creating a `ServerSession` per connection that wraps a shared `Server`.
Each session holds its own state and naturally scopes notifications through its own stream.

### Changes

- Added `MCP::ServerSession` class holding per-session state: client info,
  logging configuration, and a `transport` reference for session-scoped
  notification delivery.
- `StreamableHTTPTransport#handle_initialization` creates a `ServerSession`
  per `initialize` request and stores it in the session hash.
- `handle_regular_request` routes requests through the session's
  `ServerSession` instead of the shared `Server` directly.
- `Server#handle` and `Server#handle_json` accept an optional `session:`
  keyword (`ServerSession` instance).
- `Server#init` stores client info on the session when available.
- `Server#configure_logging_level` stores logging config on the session.
- `ServerContext` and `Progress` accept a `notification_target:` which
  can be either a `ServerSession` (session-scoped) or a `Server` (broadcast).
  No `session_id:` parameter needed.
- `ServerContext#notify_progress` and `#notify_log_message` delegate to
  the `notification_target` without `session_id` threading.
- `StdioTransport` creates a single `ServerSession` on `open`,
  making the session model transparent across both transports.

### Design Decision

This follows the Python SDK's "shared `Server` + per-connection `Session`" pattern.
The `Server` holds configuration (tools, prompts, resources, handlers).
Each `ServerSession` holds per-connection state (client info, logging level, stream writer).
Notifications from `ServerSession` go only to that session's stream.

## How Has This Been Tested?

All existing tests pass. All conformance tests pass. Added tests verifying:

- Session-scoped log notification is sent only to the originating session.
- Session-scoped progress notification is sent only to the originating session.
- Each session stores its own client info independently.
- Each session stores its own logging level independently.
- `StdioTransport#open` creates a `ServerSession` and stores client info on it.

## Breaking Change

None for end users.

The public API (`Server.new`, `define_tool`,`server_context.report_progress`,
`server_context.notify_log_message`, etc.) is unchanged. The following internal API
changes affect only SDK internals:

- `ServerContext.new` now requires `notification_target:` instead of just`progress:`.
- `Progress.new` now takes `notification_target:` instead of `server:`.
- `Server#handle` and `Server#handle_json` accept an optional `session:` keyword.
2026-03-29 08:04:56 +09:00
Koichi ITO
234d134029
Merge pull request #269 from koic/align_stdio_casing_with_spec
[Doc] Align stdio with specification
2026-03-28 07:18:09 +09:00
Koichi ITO
88d9bed69d Reject POST requests without session ID in stateful mode
Per the MCP specification (Streamable HTTP > Session Management):

> Servers that require a session ID SHOULD respond to requests without an `Mcp-Session-Id` header
> (other than initialization) with HTTP 400 Bad Request.

https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management

Previously, non-initialize POST requests without `Mcp-Session-Id` in stateful mode were processed
with HTTP 200 (for regular requests) or HTTP 202 (for notifications/responses).

This change adds an explicit check in `handle_post` to return HTTP 400 Bad Request when the session
ID is missing in stateful mode for all non-initialize requests, aligning with the specification.
2026-03-28 03:07:42 +09:00
Koichi ITO
a9e45148f6
Merge pull request #270 from koic/remove_undocumented_handler_override_methods
Remove undocumented handler override methods
2026-03-28 00:24:04 +09:00
Koichi ITO
3fc7bcd268
Merge pull request #272 from koic/release_0_9_2
Release 0.9.2
2026-03-27 12:29:19 +09:00
Koichi ITO
8fbc2b4631 Release 0.9.2 2026-03-27 12:10:53 +09:00
Koichi ITO
6b092797c9
Merge pull request #273 from koic/use_accessor_in_server_context_with_meta
Use accessor method in `server_context_with_meta` instead of ivar
2026-03-27 12:08:43 +09:00
Koichi ITO
a2575b24e5 Use accessor method in server_context_with_meta instead of ivar
## Motivation and Context

`server_context_with_meta` reads `@server_context` (the instance variable)
directly instead of calling the `server_context` accessor method.
This prevents subclasses from overriding `server_context`. Ffor example,
to provide thread-local context in multi-threaded servers like Puma.

Fixes #271.

## How Has This Been Tested?

Added a regression test and passed.

## Breaking Changes

None. This restores the expected behavior of `attr_accessor :server_context`.
2026-03-27 12:01:33 +09:00
Paul Carleton
e189d7852a
Merge commit from fork
Reject duplicate SSE connections with 409 to prevent stream hijacking
2026-03-26 13:17:27 +00:00
Koichi ITO
805e020d40 Remove undocumented handler override methods
## Motivation and Context

The following public methods allow replacing the SDK's built-in request handlers:

- `tools_call_handler`
- `tools_list_handler`
- `resources_list_handler`
- `resources_templates_list_handler`
- `prompts_list_handler`
- `prompts_get_handler`

These were introduced in Internal Release 0.2.0 (6004f42) as part
of "allow setting handlers on Server", before declarative APIs (`define_tool`, `Prompt` class, `Resource` class) were
fully established.

Now that those declarative APIs exist, these handler overrides are redundant: none are documented in the README.md,
and no usage exists outside of the SDK's own tests.

These handler overrides also create architectural problems. Since custom handlers cannot receive session context,
they would not work correctly with a per-session architecture, such as session-scoped notifications.

### Changes

- Removed `tools_call_handler`, `tools_list_handler`, `resources_list_handler`,
`resources_templates_list_handler`, `prompts_list_handler`, and `prompts_get_handler`
from `Server`.
- Removed the associated tests.
- Retained `resources_read_handler` (documented in the README.md and actively used
in examples and conformance server, because resource reading is application-specific).

## Breaking Change

The following methods are removed without a deprecation period:
`tools_call_handler`, `tools_list_handler`, `resources_list_handler`,
`resources_templates_list_handler`, `prompts_list_handler`,
`prompts_get_handler`.

These were never documented in the README.md and have no known usage
outside of the SDK's own tests. As a result, little to no impact on
users is expected, and a deprecation warning would have no practical
audience. Users who relied on these should use `define_tool`,
prompt/resource registration, or `resources_read_handler` instead.
2026-03-26 12:14:11 +09:00
Koichi ITO
b3125d4605 [Doc] Align stdio with specification
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/262#discussion_r2957734483.
2026-03-26 04:05:05 +09:00
Koichi ITO
db40143402 Reject duplicate SSE connections with 409 to prevent stream hijacking
An attacker who obtains a valid session ID could issue a GET request to
establish a new SSE stream, silently replacing the victim's stream. All
subsequent server-to-client messages (tool responses, notifications)
would then be delivered to the attacker instead of the legitimate client,
with no indication to the victim.

The fix mirrors the Python SDK's approach: when a GET request arrives for
a session that already has an active SSE stream, respond with HTTP 409
Conflict ("Only one SSE stream is allowed per session") and leave the
existing connection intact. Additionally, `store_stream_for_session`
checks for an existing stream under the mutex before storing a new one,
closing the TOCTOU window between the HTTP-level check and the deferred
stream assignment.

Note: exploiting this requires prior knowledge of the session ID
(a `SecureRandom.uuid`), so the practical severity is low in typical local
MCP deployments. The change is still worthwhile as defense-in-depth,
especially for multi-user or network-exposed server deployments.
2026-03-24 19:24:45 +09:00
Koichi ITO
3b1fc72fb5
Merge pull request #267 from koic/release_0_9_1
Release 0.9.1
2026-03-23 22:23:11 +09:00
Koichi ITO
f29259c0b1 Release 0.9.1
This release includes a bug fix that did not make it into v0.9.0.
It also simplifies the example in https://github.com/modelcontextprotocol/quickstart-resources/pull/121.
2026-03-23 09:45:14 +09:00
Koichi ITO
ccddd87e96
Merge pull request #266 from koic/allow_client_call_tool_to_accept_a_tool_name
Allow `Client#call_tool` to accept a tool name
2026-03-23 09:11:32 +09:00
Koichi ITO
73070f1fd7 Allow Client#call_tool to accept a tool name
## Motivation and Context

`Client#call_tool` previously required an `MCP::Client::Tool` object to call a tool.
This made the API harder to use compared to other MCP SDK implementations,
which accept a tool name string directly:

- Python SDK: `session.call_tool(name, arguments)` accepts a name string.
  https://github.com/modelcontextprotocol/python-sdk/blob/v1.26.0/src/mcp/client/session.py#L370
- TypeScript SDK: `client.callTool({ name, arguments })` accepts a name string.
  ccb78f2/packages/client/src/client/client.ts (L834)

## How Has This Been Tested?

Updated existing tests and added new tests.

## Breaking Change

No. This change adds a `name:` parameter so callers can pass a tool name string
directly without looking up a `Tool` object first. The existing `tool:` parameter
continues to work for backward compatibility.
2026-03-23 00:43:59 +09:00
Koichi ITO
1b8e45fef3
Merge pull request #261 from koic/return_404_for_invalid_session_id_in_handle_delete
Return 404 for invalid session ID in `handle_delete`
2026-03-21 00:42:55 +09:00
Koichi ITO
910d3ca0ec
Merge pull request #264 from koic/release_0_9_0
Release 0.9.0
2026-03-20 18:31:22 +09:00
Koichi ITO
12922a6448 Release 0.9.0
Some new features and fixes have been added, and it seems like a good time to cut a release.
Subsequent feature proposals can continue to be incorporated into future releases.
2026-03-20 11:02:56 +09:00
Koichi ITO
09b4e30da6
Merge pull request #262 from koic/stdio_client_transport
Add `MCP::Client::Stdio` transport
2026-03-20 07:56:02 +09:00
Koichi ITO
abc7d6c7ea Return 404 for invalid session ID in handle_delete
## Motivation and Context

The MCP specification requires that when a server receives a request containing
a session ID that is no longer valid, it MUST respond with HTTP 404 Not Found.
`handle_delete` was unconditionally calling `cleanup_session` and returning 200
even for nonexistent session IDs.

Ref: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management

> The server MAY terminate the session at any time, after which it MUST respond
> to requests containing that session ID with HTTP 404 Not Found.

## How Has This Been Tested?

Added tests for DELETE with invalid session ID, and lifecycle tests for
delete-then-POST and delete-then-DELETE scenarios.

## Breaking Change

DELETE requests with an invalid session ID now return HTTP 404 "Session not found"
instead of HTTP 200.

However, this change is considered a bug fix because it brings the behavior into
compliance with the MCP specification.
2026-03-19 14:52:13 +09:00
Koichi ITO
21eef8df9a Add MCP::Client::Stdio transport
## Motivation and Context

The `MCP::Client` currently only supports HTTP transport (`MCP::Client::HTTP`).
To achieve parity with other MCP SDKs (Python, TypeScript, C#) which provide
stdio client transports for spawning and communicating with server subprocesses,
the Ruby SDK needs a stdio client transport.
https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#stdio

This enables building MCP clients that launch server processes and communicate
via stdin/stdout using newline-delimited JSON-RPC 2.0 messages.

## How Has This Been Tested?

Added tests for process spawning, protocol initialization handshake,
notification handling, error handling, and transport close lifecycle.

## Additional context

Enabled the `Lint/IncompatibleIoSelectWithFiberScheduler` cop in `.rubocop.yml`
to detect accidental use of `IO.select` instead of `IO#wait_readable`.
2026-03-19 12:41:27 +09:00
Koichi ITO
283c7a43e4
Merge pull request #260 from koic/use_missing_session_id_response_helper_in_handle_delete
Use `missing_session_id_response` method in `handle_delete`
2026-03-18 12:47:40 +09:00
Koichi ITO
75d03f334e Use missing_session_id_response method in handle_delete
## Motivation and Context

`handle_delete` had an inline error response for "Missing session ID" that
was identical to the existing `missing_session_id_response` helper method.
`handle_get` already uses this helper for the same purpose.

## How Has This Been Tested?

All existing tests pass. The behavior is unchanged.

## Breaking Change

None.
2026-03-18 12:17:23 +09:00
Koichi ITO
f4aab5cdf0
Merge pull request #258 from koic/use_mutex_protected_session_exists_predicate
Use mutex-protected `session_exists?` in `handle_regular_request`
2026-03-18 11:53:33 +09:00
Koichi ITO
be1bbc25c1 Use mutex-protected session_exists? in handle_regular_request
## Motivation and Context

`handle_regular_request` was checking `@sessions.key?(session_id)` directly
without holding `@mutex`, while concurrent threads could modify `@sessions`
via `cleanup_session` or `handle_delete`. This created a TOCTOU race where
the check could pass but the session could be deleted before subsequent use.

The class already provides a mutex-protected `session_exists?` helper, and
`handle_get` already uses it. This change makes `handle_regular_request`
consistent with `handle_get`.

## How Has This Been Tested?

Added a test that verifies `handle_regular_request` delegates to the
mutex-protected `session_exists?` helper instead of accessing
`@sessions` directly.

All existing tests pass.

## Breaking Change

None.
2026-03-18 04:31:08 +09:00
Koichi ITO
8823bd34ef
Merge pull request #257 from koic/return_404_for_invalid_session_id
Return 404 for invalid session ID in `handle_regular_request`
2026-03-18 04:26:57 +09:00
Koichi ITO
cf1d578433 Return 404 for invalid session ID in handle_regular_request
## Motivation and Context

The MCP specification requires that when a server receives a request containing
a session ID that is no longer valid, it MUST respond with HTTP 404 Not Found.
The `handle_get` path already returned 404 correctly, but `handle_regular_request`
(the POST path) was returning 400 "Invalid session ID" instead.

Ref: https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management

> The server MAY terminate the session at any time, after which it MUST respond
> to requests containing that session ID with HTTP 404 Not Found.

## How Has This Been Tested?

Added a test for POST requests with an invalid session ID, verifying that the
response is 404 with "Session not found" error message. All existing tests pass.

## Breaking Change

POST requests with an invalid session ID now return HTTP 404 "Session not found"
instead of HTTP 400 "Invalid session ID". Clients that match on the 400 status
code or the old error message will need to be updated.

However, this change is considered a bug fix because it brings the behavior into compliance with
the MCP specification.
2026-03-17 02:29:30 +09:00
Koichi ITO
6e35d13479
Merge pull request #256 from koic/remove_dead_code_in_handle_regular_request
Remove dead code in `handle_regular_request`
2026-03-17 01:04:32 +09:00
Koichi ITO
628e5203d5
Merge pull request #255 from koic/use_autoload_to_defer_loading_of_unused_subsystems
Use `autoload` to defer loading of unused subsystems
2026-03-16 00:06:27 +09:00
Koichi ITO
95200b5467
Merge pull request #253 from koic/support_cors_and_accept_wildcard_for_browser_based_mcp_clients
Support CORS and Accept wildcard for browser-based MCP clients
2026-03-15 15:31:42 +09:00
Koichi ITO
9d9a1347d9 Remove dead code in handle_regular_request
Notifications never reach `handle_regular_request` because `handle_post`
checks `notification?(body)` first and returns 202 via `handle_accepted`.
Since only notifications cause `handle_json` to return `nil`, `response`
is always non-`nil` here.
2026-03-13 18:26:33 +09:00
Koichi ITO
0c729d0a2d Use autoload to defer loading of unused subsystems
## Motivation and Context

`lib/mcp.rb` currently declares all `require_relative` statements in one place.
As a result, Server and Client are both loaded, the stdio and Streamable HTTP
transports are both loaded, and Tool, Prompt, and Resource are all loaded,
regardless of which components are actually used.

These components are selected by the user depending on their use case,
so loading everything upfront is unnecessary.

Using `autoload` for selected constants defers loading until the constant
is actually referenced, so only the subsystems required by the user are loaded.

## How Has This Been Tested?

All existing tests pass unchanged.

## Breaking Change

None. This change only defers loading of unused components.
2026-03-12 14:08:27 +09:00
Koichi ITO
a2514a0ef2
Merge pull request #254 from koic/support_progress_notification_per_mcp_spec
Support progress notifications per MCP specification
2026-03-12 12:26:39 +09:00
Koichi ITO
066f49b7a7
Merge pull request #239 from koic/reduce_release_package_size
Reduce release package size
2026-03-11 02:24:30 +09:00
Koichi ITO
bbe637612b Support progress notifications per MCP specification
## Motivation and Context

The MCP specification defines `notifications/progress` for reporting incremental progress
during long-running tool operations. The Ruby SDK did not yet support this, so tools had no way to
send progress updates to clients. This caused the `tools-call-with-progress` conformance test to fail.

This adds an `MCP::ServerContext` wrapper that provides a `report_progress` method on
`server_context`. Tools call `server_context.report_progress(value, total:, message:)` to send
notifications back to the client. The method is a no-op when no `progressToken` was provided,
so tools can call it unconditionally without checking for a token.

This design is consistent with the TypeScript and Python SDKs, which provide progress
reporting through a context object rather than a separate parameter.

On the client side, `Client#call_tool` now accepts a `progress_token:` parameter that sets
`_meta.progressToken` in the request.

Ref: https://modelcontextprotocol.io/specification/latest/server/utilities/progress

## How Has This Been Tested?

Added comprehensive tests in `test/mcp/server_progress_test.rb` covering `notify_progress`,
tool integration with progress, block-defined tools, `**kwargs` tools, and no-op behavior
without a token.

Added client tests for `progress_token:` parameter inclusion and omission.

Added `test/mcp/server_context_test.rb` test for non-Hash `server_context` preservation
when `_meta` is present.

Conformance: `tools-call-with-progress` removed from expected failures.

## Breaking Change

`server_context` is now always an `MCP::ServerContext` instance when passed to tools,
even if the server has no context configured. Code that checks `server_context ?` to
detect a nil context will need to be updated, as `ServerContext` is always truthy.
`ServerContext` delegates method calls to the underlying context object via
`method_missing`, so `server_context[:key]` and other accessor patterns continue to work.

In practice, this is unlikely to affect users. A tool that declares `server_context:`
is opting in to use the context; if the server has no context configured, that is a
server configuration issue rather than something the tool should handle with a nil check.
2026-03-10 01:49:09 +09:00
Koichi ITO
e5d3b2c135 Support CORS and Accept wildcard for browser-based MCP clients
## Summary

When using browser-based MCP clients such as MCP Inspector, connections to
the example HTTP server failed due to two issues:

1. CORS preflight (OPTIONS) requests returned 405 Method Not Allowed,
causing browsers to block all cross-origin requests.
2. `Accept: */*` (commonly sent by browsers and fetch API) returned 406 Not Acceptable
because the transport required the Accept header to explicitly list `application/json`
and `text/event-stream`.

Add `rack-cors` middleware to the example HTTP servers so that preflight requests are handled correctly
and `Mcp-Session-Id` is exposed to browser clients. Also fix `validate_accept_header` in `StreamableHTTPTransport`
to treat `*/*` as satisfying all required Accept types.

Fixes #141.

## Repro Steps

### 1. Start the example server (Terminal 1)

```console
$ bundle exec ruby examples/streamable_http_server.rb
```

### 2. Start MCP Inspector (Terminal 2)

```console
$ npx @modelcontextprotocol/inspector
```

### 3. Open the Inspector Web UI (http://localhost:6274) in a browser

- Set Transport Type to "Streamable HTTP"
- Set URL to http://localhost:9393
- Disable the Authorization header toggle (the example server does not require authentication)
- Click "Connect"

Before this change, the connection fails due to CORS or 406 errors.
After this change, the connection succeeds and tools are listed.

These steps have been added to examples/README.md.
2026-03-09 10:45:53 +09:00
Koichi ITO
8a97cebc33
Merge pull request #252 from koic/fix_rails_controller_example_to_return_202_for_notifications
[Doc] Fix Rails controller example to return 202 for notifications
2026-03-08 03:06:19 +09:00
Koichi ITO
7e0a339681 [Doc] Fix Rails controller example to return 202 for notifications
The previous example used `Server#handle_json` directly, which does not control HTTP status codes.
Notifications such as `notifications/initialized` require 202 Accepted per the MCP spec,
but the example always returned 200.

Use `StreamableHTTPTransport#handle_request` instead, which returns the correct HTTP status code
for each request type.

- https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#sending-messages-to-the-server
- https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server

Closes #158
2026-03-06 03:21:25 +09:00
Koichi ITO
5d8f1bdf9f
Merge pull request #172 from erickreutz/add-meta-extraction-support
Add automatic _meta parameter extraction support
2026-03-05 02:45:05 +09:00
Eric Kreutzer
50cd86c01c
Add automatic _meta parameter extraction support 2026-03-04 10:11:07 -07:00
Koichi ITO
4bf168840e
Merge pull request #251 from modelcontextprotocol/dependabot/github_actions/actions/setup-node-6
Bump actions/setup-node from 4 to 6
2026-03-04 02:17:09 +09:00
Koichi ITO
7cede9c5fd
Merge pull request #250 from koic/release_0_8_0
Release 0.8.0
2026-03-03 09:11:13 +09:00
dependabot[bot]
773345bd5d
Bump actions/setup-node from 4 to 6
Bumps [actions/setup-node](https://github.com/actions/setup-node) from 4 to 6.
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v6)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 22:05:03 +00:00
Koichi ITO
2da465c985 Release 0.8.0
Some fixes have been identified during the implementation of the conformance infrastructure.
It should be possible to proceed with a release at this stage.
2026-03-03 01:19:53 +09:00
Koichi ITO
fa9f374d73
Merge pull request #237 from koic/replace_assert_empty_with_assert_equal_using_explicit_literals
Replace `assert_empty` with `assert_equal` using explicit literals
2026-03-03 01:05:16 +09:00
Koichi ITO
37c3f0d991
Merge pull request #240 from koic/add_wildcard_gem_to_dot_gitignore
Add `*.gem` to .gitignore
2026-03-03 01:04:41 +09:00
Koichi ITO
ad45c10e13
Merge pull request #248 from koic/conformance
Support running MCP conformance tests against the Ruby SDK
2026-03-02 14:54:41 +09:00
Koichi ITO
13bbd2937d Support running MCP conformance tests against the Ruby SDK
## Motivation

To assess and track the Ruby SDK's compliance with the MCP
specification, integrate `@modelcontextprotocol/conformance` as the
standard evaluation harness. This makes it possible to measure
conformance objectively, catch regressions early, and produce the kind
of evaluation data needed for SDK tier assessments.

## Scope

Only server conformance is included at this point. Client conformance
requires protocol-level features that MCP::Client does not yet
support (initialize handshake, notifications, ping, etc.).

## Usage

Run conformance tests:

```console
bundle exec rake conformance
```

Start the conformance server in the foreground for iterating on a single
scenario without the per-run startup overhead:

```console
bundle exec rake conformance_server
```

## Default Rake Task (`bundle exec rake`)

It is configured to run in order of lower execution cost: `rubocop`, `test`, and then `conformance`.

## CI

`.github/workflows/conformance.yml` file has been added to run the conformance tests in CI.

## SDK Tier Report

The MCP SDK Tier system (https://modelcontextprotocol.io/community/sdk-tiers)
requires SDK maintainers to self-assess and report results to the SDK Working
Group via https://github.com/modelcontextprotocol/modelcontextprotocol/issues.

To generate a full tier assessment report, use the `/mcp-sdk-tier-audit`
slash command from the https://github.com/modelcontextprotocol/conformance repository with
the conformance server running:

```console
# Terminal 1 (this repository): start the conformance server
bundle exec rake conformance_server

# Terminal 2 (conformance repository): run the tier audit skill as a slash command in Claude Code
/mcp-sdk-tier-audit /path/to/modelcontextprotocol/ruby-sdk http://localhost:9292/mcp
```

The skill evaluates conformance pass rate, issue label taxonomy, triage
metrics, documentation coverage, and policy compliance, then produces a
markdown report suitable for tier advancement submissions.
2026-03-02 14:50:03 +09:00
Koichi ITO
5f16abfd96
Merge pull request #244 from koic/add_content_embedded_resource
Add `Content::EmbeddedResource` class for embedded resource content type
2026-03-02 01:35:37 +09:00
Koichi ITO
ba7a08aa04 Add Content::EmbeddedResource class for embedded resource content type
The MCP spec defines an embedded resource content type, but the SDK had
no corresponding class. Add `Content::EmbeddedResource` that wraps a
resource object and serializes it via `to_h`.

https://modelcontextprotocol.io/specification/2025-11-25/server/tools#embedded-resources
2026-03-02 01:33:05 +09:00
Koichi ITO
60f69351ee
Merge pull request #249 from koic/fix_econnreset_in_sse_notification
Handle `Errno::ECONNRESET` in SSE stream operations
2026-03-02 01:30:40 +09:00
Koichi ITO
2fc4f5e1d2
Merge pull request #243 from koic/add_content_audio
Add `Content::Audio` class for audio content type
2026-03-02 01:30:20 +09:00
Koichi ITO
29a32900fd
Merge pull request #246 from koic/fix_prompt_nil_arguments
Fix `Prompt#validate_arguments!` crash when arguments are `nil`
2026-03-01 18:38:14 +09:00
Koichi ITO
cbb81a836c Add Content::Audio class for audio content type
The MCP spec defines an audio content type, but the SDK only had
`Content::Text` and `Content::Image`. Add `Content::Audio` with the
same structure as `Content::Image`.

https://modelcontextprotocol.io/specification/2025-11-25/server/tools#audio-content
2026-03-01 17:30:17 +09:00
Koichi ITO
9c1c2491b1 Handle Errno::ECONNRESET in SSE stream operations
`Errno::ECONNRESET` is a `SystemCallError`, not an `IOError`, so it was
not caught by the existing `rescue IOError, Errno::EPIPE` clauses. When
a client disconnected with a TCP RST during SSE notification broadcast,
the unhandled exception aborted the entire broadcast loop, causing
notifications to be lost for all remaining sessions.

This caused the `tools-call-with-logging` conformance scenario to fail
in CI (#248), where stale sessions from prior scenarios triggered
`ECONNRESET` on the first notification write, aborting the broadcast
and losing log notifications.

Add `Errno::ECONNRESET` to all four rescue clauses in
`StreamableHTTPTransport`: `send_notification` (targeted and broadcast),
`send_response_to_stream`, and `send_keepalive_ping`.
2026-03-01 17:25:38 +09:00
Koichi ITO
200826c7fd
Merge pull request #247 from koic/fix_default_handler_return_values
Fix default handler return values to comply with MCP spec
2026-03-01 17:23:42 +09:00
Koichi ITO
ef5c76373b Fix Prompt#validate_arguments! crash when arguments are nil
`Prompt#validate_arguments!` called `required_args` which does `arguments_value.filter_map`,
crashing with `NoMethodError` when `arguments_value` is `nil` (the default for prompts without
declared arguments). Additionally, passing `nil` as args caused a crash on `args.keys`.

Fix by defaulting `arguments_value` to `[]` and guarding against `nil` args.
2026-03-01 17:21:41 +09:00
Koichi ITO
76ab822ad7
Merge pull request #245 from koic/fix_sse_response_status
Return 202 Accepted for SSE responses per MCP spec
2026-03-01 17:17:26 +09:00
Koichi ITO
145dc1f2c5
Merge pull request #242 from koic/support_ref_in_tool_schema
Allow `$ref` in `Tool::Schema` for protocol version 2025-11-25
2026-03-01 17:16:47 +09:00
Koichi ITO
c62902b1e8
Merge pull request #241 from koic/fix_content_image_to_h
Fix `Content::Image#to_h` to return `mimeType` (camelCase) per MCP spec
2026-03-01 17:16:25 +09:00
Koichi ITO
7b910bca23 Fix default handler return values to comply with MCP spec
The no-op handlers for `completion/complete`, `resources/subscribe`,
and `resources/unsubscribe` returned `nil`.
When a client accesses the expected response structure (e.g., `result[:completion][:values]`),
a `nil` result raises `NoMethodError`.

The MCP spec requires specific response structures even for no-op handlers.
Returning spec-compliant defaults ensures that clients receive valid responses without
requiring servers to explicitly override each handler.

`completion/complete` now returns `{ completion: { values: [], hasMore: false } }`.
ref: https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/completion

`resources/subscribe` and `resources/unsubscribe` now return `{}` (empty result).
ref: https://modelcontextprotocol.io/specification/2025-11-25/server/resources#subscriptions
2026-03-01 00:55:31 +09:00
Koichi ITO
a02a4572c4 Return 202 Accepted for SSE responses per MCP spec
`StreamableHTTPTransport#send_response_to_stream` returned 200 with
`{ accepted: true }` body, but the MCP spec requires 202 with empty body
when a response is sent via SSE stream. This has been a requirement since
Streamable HTTP was introduced in protocol version 2025-03-26.

- https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#sending-messages-to-the-server
- https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#sending-messages-to-the-server
2026-02-28 17:59:54 +09:00
Koichi ITO
99cbefc610 Allow $ref in Tool::Schema for protocol version 2025-11-25
`Tool::Schema` rejected `$ref` with an `ArgumentError`.
Earlier MCP spec versions (2024-11-05 through 2025-06-18) did not define
a JSON Schema dialect or reference the `$ref` keyword. `inputSchema` was described
only as "JSON Schema defining expected parameters" with no further constraints:

- https://modelcontextprotocol.io/specification/2024-11-05/server/tools
- https://modelcontextprotocol.io/specification/2025-06-18/server/tools

The MCP spec 2025-11-25 introduced a "JSON Schema Usage" section that adopts
JSON Schema 2020-12 as the default dialect. Since `$ref` is a core keyword in 2020-12,
it is now allowed for protocol version 2025-11-25 and later.

- https://modelcontextprotocol.io/specification/2025-11-25/basic#json-schema-usage
- https://modelcontextprotocol.io/specification/2025-11-25/server/tools
- https://json-schema.org/draft/2020-12/release-notes

For backward compatibility with older protocol versions (2025-06-18 and earlier),
`Server#validate!` continues to raise `ArgumentError` when a tool input schema contains `$ref`.
This preserves the existing behavior for servers targeting those spec versions.
2026-02-27 14:33:36 +09:00
Koichi ITO
37563e59bd Fix Content::Image#to_h to return mimeType (camelCase) per MCP spec
This is a fix for a similar bug that remained, as in #235.

`Content::Image#to_h` returned `mime_type` (snake_case), but the MCP spec
requires `mimeType` (camelCase) for the MIME type field in image content.
2026-02-27 12:51:38 +09:00
Koichi ITO
bb94bdd6e3 Add *.gem to .gitignore
`gem build mcp.gemspec` outputs the built gem into the working directory (e.g. mcp-0.7.1.gem)
rather than pkg/, which is already ignored.
Without this entry, the file shows up as an untracked file and risks being accidentally
staged and committed during release preparation or local development.
2026-02-26 19:32:38 +09:00
Koichi ITO
912245dc11 Reduce release package size
The current release package contains files that are not required at runtime,
such as `.github`, `docs`, and `examples`.

```ruby
Dir.chdir(File.expand_path("..", __FILE__)) do
  %x(git ls-files -z).split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
=>
[".gitattributes",
 ".github/dependabot.yml",
 ".github/workflows/ci.yml",
 ".github/workflows/release.yml",
 ".gitignore",
 ".rubocop.yml",
 "AGENTS.md",
 "CHANGELOG.md",
 "CODE_OF_CONDUCT.md",
 "Gemfile",
 "LICENSE",
(snip)
```

This PR removes unnecessary files where possible to reduce the size of the release package.
2026-02-25 19:05:02 +09:00
Koichi ITO
a44799b262 Replace assert_empty with assert_equal using explicit literals
Due to overly aggressive detection by RuboCop Minitest, the distinction between `[]` and `{}` was uniformly replaced with `assert_empty`,
making it impossible to differentiate between them.
As a result of https://github.com/rubocop/rubocop-minitest/issues/344, where the `Minitest/AssertEmptyLiteral` cop was disabled,
the return value has been expressed using explicit literal forms.
2026-02-24 16:09:34 +09:00
Koichi ITO
5b04089e06
Merge pull request #236 from koic/release_0_7_1
Release 0.7.1
2026-02-21 11:15:14 +09:00
Koichi ITO
4af216fa32 Release 0.7.1
This is a release that includes several bug fixes.
2026-02-21 03:33:28 +09:00
Koichi ITO
a05da399ba
Merge pull request #235 from koic/fix_property_field_names_in_resource_contents
Fix `Resource::Contents#to_h` to use correct property names per MCP spec
2026-02-20 11:51:34 +09:00
Koichi ITO
c8a68da37b
Merge pull request #231 from koic/return_json_rpc_protocol_errors_for_unknown_tool_calls
Return JSON-RPC protocol errors for unknown tool calls
2026-02-20 11:51:16 +09:00
Koichi ITO
08832c6b43 Fix Resource::Contents#to_h to use correct property names per MCP spec
This PR fixes thr following fields with the MCP specification which requires:

- Text resources use `text` and `mimeType` fields
- Binary resources use `blob` (base64-encoded) and `mimeType` fields

https://modelcontextprotocol.io/specification/2025-11-25/server/resources#resource-contents

Fixes #234.
2026-02-19 13:50:10 +09:00
Den Delimarsky
6df8e4c74c
Add SECURITY.md with GitHub Security Advisories guidance (#232) 2026-02-18 20:49:17 -05:00
Koichi ITO
15710ef0aa Return JSON-RPC protocol errors for unknown tool calls
Per the MCP specification, an unknown tool call is a protocol-level error, not a tool execution error.
Return JSON-RPC -32602 (Invalid params) instead of successful responses with `isError: true`.
https://modelcontextprotocol.io/specification/2025-11-25/server/tools#error-handling

Fixes #228.
2026-02-19 02:53:39 +09:00
Koichi ITO
b8f1cc92e6
Merge pull request #230 from koic/fix_logging_set_level
Fix `logging/setLevel` to return empty hash per MCP specification
2026-02-19 02:52:51 +09:00
Koichi ITO
34b7c68b5a
Merge pull request #219 from koic/acknowledge_shopify_in_the_initial_release
[Doc] Acknowledge Shopify in the initial release
2026-02-17 12:40:08 +09:00
Koichi ITO
4dc2a8eb4a Fix logging/setLevel to return empty hash per MCP specification
This PR fixes `logging/setLevel` to return empty hash per MCP specification.
The MCP specification requires `logging/setLevel` to return an empty result
on success, not nil or the `LoggingMessageNotification` object.

Specification reference:
https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/logging

Fixes #229.
2026-02-17 01:00:15 +09:00
Koichi ITO
2b790d6804
Merge pull request #227 from koic/release_0_7_0
Release 0.7.0
2026-02-14 15:44:43 +09:00
Koichi ITO
0175fff4dd Release 0.7.0
Some new features and fixes have been added, and it seems like a good time to cut a release.

- https://github.com/modelcontextprotocol/ruby-sdk/pull/103
- https://github.com/modelcontextprotocol/ruby-sdk/pull/223
- https://github.com/modelcontextprotocol/ruby-sdk/pull/218
- https://github.com/modelcontextprotocol/ruby-sdk/pull/221
- https://github.com/modelcontextprotocol/ruby-sdk/pull/225
- https://github.com/modelcontextprotocol/ruby-sdk/pull/224
- https://github.com/modelcontextprotocol/ruby-sdk/pull/220

For now, the features completed so far can be included in this release,
and subsequent feature proposals can continue to be incorporated into future releases.
2026-02-14 10:07:07 +09:00
Koichi ITO
c11393f4c4
Merge pull request #224 from koic/extract_annotations_from_mcp
Extract `MCP::Annotations` into a dedicated file
2026-02-10 02:30:42 +09:00
Koichi ITO
1a2750d6d7
Merge pull request #222 from koic/update_readme_for_instrumentation_callback
[Doc] Add `tool_arguments` to instrumentation callback documentation
2026-02-09 00:48:46 +09:00
Koichi ITO
ebd658d50d
Merge pull request #226 from sjrct/remove-unused-require
Remove unused require from logging_message_notification.rb
2026-02-07 02:59:16 +09:00
Koichi ITO
0e30dff80b
Merge pull request #225 from sjrct/add-client-resource-templates
Add resource_templates to MCP::Client
2026-02-07 02:58:52 +09:00
Chris Harding
d0107c304a logging_message_notification: Remove unused require 2026-02-05 16:05:08 -05:00
Chris Harding
c145fe39df Add resource_templates to MCP::Client
Includes relevant README addition and tests
2026-02-05 16:02:07 -05:00
Koichi ITO
15ef5ebda2
Merge pull request #223 from chattermill/md-protocol-negotiation
Add protocol version negotiation to server initialization
2026-02-06 00:11:28 +09:00
Mikhail Dubov
077a5cf15a Add protocol version negotiation to server initialization
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-05 10:43:59 +00:00
Koichi ITO
4a71fa8ec4
Merge pull request #221 from chattermill/md-client-instrumentation
Add client info to instrumentation callback
2026-02-05 11:28:14 +09:00
Mikhail Dubov
2d926ab386 Add client info to instrumentation callback 2026-02-04 12:03:03 +00:00
Koichi ITO
248c1ec532
Merge pull request #220 from koic/fix_resource_embedded_not_setting_resource_in_initialize
Fix `Resource::Embedded` not setting `@resource` in `initialize`
2026-02-04 10:58:49 +09:00
Koichi ITO
a85fa028f7 Extract MCP::Annotations into a dedicated file
This PR moves `MCP::Annotations` from lib/mcp.rb to lib/mcp/annotations.rb for better organization,
following the pattern used for other classes such as `Tool::Annotations`.

This PR also adds the missing `last_modified` attribute to `MCP::Annotations`:
https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-11-25/schema.ts#L1701-L1736

It also adds a `to_h` method for serialization and includes comprehensive test coverage.

NOTE: This code is unused within the ruby-sdk repository, but it is kept for compatibility, as it may be used by users.
2026-02-03 15:38:04 +09:00
Koichi ITO
1c449ae549 [Doc] Add tool_arguments to instrumentation callback documentation
Follow-up to #218, which added the `tool_arguments` feature to the instrumentation callback.
This updates README.md to document the new `tool_arguments` key in both instrumentation callback sections,
and removes redundant instrumentation documentation.
2026-01-31 15:47:56 +09:00
Koichi ITO
0ab77c318f
Merge pull request #103 from dak2/support-logging
Add `logging` support
2026-01-30 12:29:29 +09:00
dak2
afa2fb4077 Add logging support
A server can send structured logging messages to the client.
https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging#logging

Logging was specified in the 2024-11-05 specification, but since it was not supported in ruby-sdk, I implemented it.
https://modelcontextprotocol.io/specification/2024-11-05/server/utilities/logging

I also made it possible to output a simple notification message in the examples.
2026-01-26 22:23:46 +09:00
Koichi ITO
05c0119e53 Fix Resource::Embedded not setting @resource in initialize
The `initialize` method was missing the assignment of `@resource`,
causing the resource method to always return `nil` and `to_h` to return
an incorrect hash with an empty resource value.

Added comprehensive tests to verify the fix and prevent regression.
2026-01-26 11:37:33 +09:00
Koichi ITO
5331c237bd [Doc] Acknowledge Shopify in the initial release
The repository's "About" section currently states,
"The official Ruby SDK for the Model Context Protocol. Maintained in collaboration with Shopify."
However, now that MCP governance has been established, maintenance is handled by the MCP steering group.

Given this, it seems more accurate to remove the maintenance wording from the "About" section.
That said, I think it would be good to preserve acknowledgment of Shopify, which originally developed and released the Ruby SDK.

There may be a more appropriate place for this, but at the very least, it could be recorded in the changelog as part of the project's history.
2026-01-25 16:11:27 +09:00
Koichi ITO
3addc525df
Merge pull request #218 from chattermill/add-tool-arguments-to-instrumentation
Add Tool Arguments to Instrumentation Data
2026-01-23 01:11:28 +09:00
Mikhail Dubov
7412197e52 feat: add tool_arguments to instrumentation data
Include the tool arguments in instrumentation callback data when
tools/call is invoked. This allows consumers to track which arguments
were passed to each tool call for analytics and debugging purposes.
2026-01-21 17:18:28 +00:00
Koichi ITO
830913be5a
Merge pull request #214 from koic/add_explicit_permissions_to_ci_workflow
Add explicit permissions to CI workflow
2026-01-21 02:12:47 +09:00
Koichi ITO
ade3d1fa80
Merge pull request #216 from koic/release_0_6_0
Release 0.6.0
2026-01-16 15:31:38 +09:00
Koichi ITO
c4fd83debf Release 0.6.0
This would have been 0.5.1 release with only the fix from #212, but it has been released as 0.6.0
because it also includes the license change in #213.
2026-01-16 14:58:48 +09:00
Koichi ITO
7bef102224
Merge pull request #212 from koic/omit_icons_from_response_when_empty_or_nil
Omit `icons` from responses when empty or nil
2026-01-15 08:53:14 +09:00
Koichi ITO
27e5dc9c80
Merge pull request #213 from modelcontextprotocol/chore/apache-2.0-license
chore: update licensing to Apache 2.0 for new contributions
2026-01-14 01:04:45 +09:00
Adam Jones
685a4913d4
chore: update licensing to Apache 2.0 for new contributions 2026-01-12 22:49:19 +00:00
Koichi ITO
e484029d53 Add explicit permissions to CI workflow
Set minimal `contents: read` permission following the principle of least privilege.
This prevents using overly permissive repository defaults.
2026-01-13 03:06:05 +09:00
Koichi ITO
bd416c7a5f Omit icons from responses when empty or nil
Previously, the `icons` parameter was always included in responses (as an empty array)
even when not configured. This differs from the response representation in MCP Ruby SDK 0.4.0.

Since `icons` is optional, it should be omitted from responses when unused to reduce
unnecessary context window usage.
https://modelcontextprotocol.io/specification/2025-11-25/schema#implementation

This fix applies to `Tool#to_h`, `Prompt#to_h`, `Resource#to_h`, `ResourceTemplate#to_h`,
and `Server#server_info`.

It doesn't seem critical, but if there are no other issues, it would be good to cut 0.5.1 bugfix release soon.
2026-01-12 09:46:45 +09:00
Koichi ITO
fd1d7a61ec
Merge pull request #211 from koic/release_0_5_0
Release 0.5.0
2026-01-11 12:27:34 +09:00
Koichi ITO
7a21bbd14b Release 0.5.0
Many new features and fixes have been added, and it seems like a good time to cut a release.
This release enables the following user feedback to be addressed:

* https://github.com/modelcontextprotocol/ruby-sdk/issues/99#issuecomment-3667416303
* https://github.com/modelcontextprotocol/ruby-sdk/pull/206#issuecomment-3717086100

For now, the features completed so far can be included in this release,
and subsequent feature proposals can continue to be incorporated into future releases.
2026-01-11 03:37:34 +09:00
Koichi ITO
6b18ca41be
Merge pull request #209 from koic/avoid_redos_in_ruby_3_1_and_earlier
Fix ReDoS vulnerability in `StringUtils#underscore`
2026-01-10 01:16:27 +09:00
Koichi ITO
248b4d2dad Fix ReDoS vulnerability in StringUtils#underscore
## Summary

Replace regex patterns with lookahead/lookbehind assertions to prevent
catastrophic backtracking on Ruby 3.1 and earlier.

This issue only affects Ruby 3.1 and earlier. Since it does not occur on Ruby 3.2+,
it is not an issue in the current stable release (0.4.0), which does not include #206.

## Regression Testing

Ensure the regex patterns complete within 1 second for a 50,000-character input
that would otherwise trigger superlinear backtracking.
2026-01-09 01:14:52 +09:00
Koichi ITO
b92dbe4c28
Merge pull request #207 from keisku/add-Accept-header-validation
Add Accept header validation
2026-01-08 02:49:19 +09:00
Keisuke Umegaki
ab8f53c5b7
Add Accept header validation
- Set Accept header to request JSON or SSE responses
- Validate response Content-Type and raise error for non-JSON responses
- Add Accept header to test fixtures
- Use explicit hash syntax for Ruby 2.7 compatibility
2026-01-07 14:55:19 +09:00
Koichi ITO
05fb98c3bb
Merge pull request #206 from koic/support_for_ruby_2_7_to_3_1
Support Ruby 2.7 - Ruby 3.1
2026-01-07 11:13:05 +09:00
Keisuke Umegaki
6f86acc161
fix dev style (#208) 2026-01-06 01:00:31 -05:00
Koichi ITO
aa8bbad491 Support Ruby 2.7 - Ruby 3.1
## Summary

Unlike applications, libraries provide value by remaining usable for a broad range of users,
even when that means supporting older Ruby versions beyond Ruby's own EOL timeline.

I maintain RuboCop, a Ruby linter. Because linters need to work across the ecosystem,
they often need to keep compatibility with older Ruby versions to some extent.

The trade-off is that the MCP Ruby SDK must remain compatible with Ruby 2.7.
However, given the ecosystem impact, supporting Ruby 2.7 is still worthwhile.

For example, bundled gems such as `csv` (Ruby >= 2.5), `bigdecimal` (Ruby >= 2.5), `json` (Ruby >= 2.7),
and `language_server-protocol` (Ruby >= 2.5) tend to keep compatibility with older Ruby versions.

Unlike dropping support, which imposes restrictions on users,
this change broadens compatibility and does not introduce breaking changes.

## Development Note

`rubocop-shopify` (2.18) supports Ruby 3.1+, and this PR does not change that.
Since RuboCop can configure the runtime Ruby version and the target Ruby version for analysis independently,
CI continues to run RuboCop on Ruby 4.0, while analyzing code with `TargetRubyVersion: 2.7`.

When setting `TargetRubyVersion: 2.7`, several RuboCop offenses were resolved.

Additionally, Sorbet-related libraries support Ruby 3.0+. Since these are not dependencies of the MCP Ruby SDK itself,
they are versioned and tested in the development Gemfile.
2026-01-06 10:38:56 +09:00
Koichi ITO
4968d9cffc
Merge pull request #204 from koic/make_tool_names_stricter
Make tool names stricter
2026-01-04 06:58:20 +09:00
Koichi ITO
ab4f0807d4
Merge pull request #205 from koic/add_icons
Support `icons` parameter
2026-01-03 01:46:43 +09:00
Koichi ITO
d1038c9f90
Merge pull request #203 from koic/remove_redundant_descriptions_in_agents_md
[Doc] Remove redundant descriptions in AGENTS.md
2026-01-02 01:18:00 +09:00
Koichi ITO
3bc1c2c407
Merge pull request #194 from koic/show_exception_messages_for_tool_call_error
Show exception messages for tool call errors
2026-01-01 07:09:15 +09:00
Koichi ITO
b29d522d27 Show exception messages for tool call errors
Claude Code sometimes only shows `Error: MCP error -32603: Internal error`
when an unexpected exception occurs during a tool call.

This change broadens the exception handling scope so the server can surface
the exception message more often, making failures easier to diagnose.
2025-12-31 19:38:14 +09:00
Koichi ITO
ca934456de
Merge pull request #189 from koic/update_specification_url_to_latest
[Docs] Update specification URL to `latest`
2025-12-31 08:11:20 +09:00
Koichi ITO
028c5f3291 Support icons parameter
This PR adds support for the optional `icons` parameter in prompt, resource,
resource template, and server info.

The specifications for `icons` are as follows.
https://modelcontextprotocol.io/specification/2025-11-25/schema#icon

Resolves https://github.com/modelcontextprotocol/ruby-sdk/issues/127.
2025-12-30 05:35:22 +09:00
Koichi ITO
84ff1fcba1 Make tool names stricter
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/199#issuecomment-3659688807

Tool names are now validated to comply with the specification.
https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-names

Since the tool name is optional, `nil` value is treated as "not specified" and is ignored without validation.
2025-12-29 01:19:39 +09:00
Koichi ITO
5aef96773e [Doc] Remove redundant descriptions in AGENTS.md
The "Component definition patterns" section has been removed because it overlaps with
"Three Ways to Define Components" in AGENTS.md:
d745ccde/AGENTS.md (key-patterns)

This helps make the system prompt more concise.
2025-12-28 16:24:58 +09:00
Koichi ITO
d745ccdedc
Merge pull request #202 from koic/ci_against_ruby_4_0
Add Ruby 4.0 to CI
2025-12-27 00:35:36 +09:00
Koichi ITO
3f4400f3b3 Add Ruby 4.0 to CI
Ruby 4.0.0 has been released, so this PR adds Ruby 4.0 to CI.
https://www.ruby-lang.org/en/news/2025/12/25/ruby-4-0-0-released/

To prevent the CI label from showing "CI / Test Ruby 4" instead of
"CI / Test Ruby 4.0", the matrix entries are changed from floats to strings.
2025-12-26 00:25:47 +09:00
Koichi ITO
614c016c8d
Merge pull request #192 from koic/add_missing_assertion
Add a missing assertion in `ConfigurationTest`
2025-12-25 00:33:12 +09:00
Koichi ITO
771163cc94
Merge pull request #188 from koic/add_website_url_to_server_info
Add support for the optional `websiteUrl` parameter in `serverInfo`
2025-12-24 00:49:35 +09:00
Koichi ITO
8d68fc0717
Merge pull request #199 from koic/fix_tool_name_colisions_across_namespaces
Raise an error when duplicate tool names are registered
2025-12-23 01:21:24 +09:00
Koichi ITO
149d977031
Merge pull request #187 from koic/fix_incorrect_example_in_readme
[Doc] Fix incorrect examples in README.md
2025-12-22 00:59:04 +09:00
Koichi ITO
dee80d20ae Raise an error when duplicate tool names are registered
This raises an exception when duplicate tool names are registered,
instead of silently overwriting tools. Tool names are required to be
unique within a server, so this behavior aligns with the MCP specification.

> Tool names SHOULD be unique within a server.

https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-names

Validation for tool names could be made more strictly spec-compliant in a separate effort.

Fixes #197
2025-12-21 22:48:43 +09:00
Koichi ITO
62615d65e4 Add support for the optional websiteUrl parameter in serverInfo
This PR adds support for the optional `websiteUrl` parameter in `serverInfo`.
This parameter has been supported since the 2025-11-25 MCP specification.

This PR also implements part of https://github.com/modelcontextprotocol/ruby-sdk/issues/127.
2025-12-21 22:44:36 +09:00
Koichi ITO
171baa876e
Merge pull request #201 from koic/add_description_to_server_info
Add support for the optional `description` parameter in `serverInfo`
2025-12-21 00:42:35 +09:00
Koichi ITO
851974e454 Add support for the optional description parameter in serverInfo
This PR adds support for the optional `description` parameter in `serverInfo`.
This parameter has been supported since the 2025-11-25 MCP specification.
https://modelcontextprotocol.io/specification/2025-11-25/schema#implementation
2025-12-20 19:12:45 +09:00
Koichi ITO
7b3ff946ac
Merge pull request #184 from koic/support_2025_11_25_specification
Allow stable protocol specification version "2025-11-25"
2025-12-20 19:04:36 +09:00
Koichi ITO
67e03d7b3d Allow stable protocol specification version "2025-11-25"
The MCP specification dated 2025-11-25 has been released:

- https://modelcontextprotocol.io/specification/2025-11-25
- https://blog.modelcontextprotocol.io/posts/2025-11-25-first-mcp-anniversary

This PR allows `'2025-11-25'` to be specified for the `:protocol_version` keyword argument
in `MCP::Configuration.new`.
2025-12-20 18:58:28 +09:00
Koichi ITO
baeb75c8d8
Merge pull request #190 from koic/avoid_draft_protocol_version
Default to the latest stable protocol version
2025-12-20 18:55:18 +09:00
Koichi ITO
4eab486d56
Merge pull request #198 from ebeigarts/feature/schema-additional-properties
Refactor schema validation to reduce duplication and add additionalProperties support
2025-12-16 10:32:42 +09:00
Koichi ITO
0b70ef3d6a
Merge pull request #200 from koic/remove_redundant_string_dup
Remove redundant `String#dup`
2025-12-15 07:54:59 +09:00
Koichi ITO
0429284d5d Remove redundant String#dup
Since no destructive methods are being called, `dup` isn’t necessary.
2025-12-14 14:32:10 +09:00
Edgars Beigarts
a3c24d2bcc
Refactor schema validation to reduce duplication and add additionalProperties support
This refactoring extracts common schema validation logic into a base Schema
class, eliminating ~100 lines of duplicate code between InputSchema and
OutputSchema. It also adds support for the JSON Schema `additionalProperties`
keyword to allow fine-grained control over extra properties in tool arguments.

Previously `additionalParameters` could be set only on OutputSchema.

Key changes:

- Created MCP::Tool::Schema base class consolidating:
  - Schema validation against JSON Schema Draft 4 metaschema
  - Deep key transformation (string to symbol conversion)
  - $ref disallowance checking
  - Common validation methods

- Refactored InputSchema to inherit from Schema:
  - Simplified constructor to accept full schema hash
  - Changed required fields storage from symbols to strings
  - Removed ~40 lines of duplicated validation logic

- Refactored OutputSchema to inherit from Schema:
  - Removed ~54 lines of duplicated validation logic
  - Now shares all common functionality with InputSchema

- Updated Tool.input_schema setter:
  - Simplified to pass full hash directly to InputSchema

- Added additionalProperties support:
  - By default, tools now allow additional properties (JSON Schema default)
  - Can explicitly set `additionalProperties: false` to disallow extras
  - Added comprehensive test coverage for both behaviors
2025-12-12 12:49:52 +02:00
Koichi ITO
85b81a6a65
Merge pull request #196 from guillaumebriday/patch-1
[Docs] Rename APITool to WeatherTool and add error handling
2025-12-10 12:16:56 +09:00
Guillaume Briday
2b205581ea
Rename APITool to WeatherTool and add error handling
Updated the APITool class to WeatherTool and modified method parameters. Added section on tool responses with errors.
2025-12-09 20:09:42 +01:00
Koichi ITO
47c70ef8e7
Merge pull request #195 from modelcontextprotocol/dependabot/github_actions/actions/checkout-6
Bump actions/checkout from 5 to 6
2025-12-09 08:05:19 +09:00
dependabot[bot]
8df42c37b3
Bump actions/checkout from 5 to 6
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-08 20:27:39 +00:00
Koichi ITO
7ca4bf85ad
Merge pull request #193 from devonboyer/fix-symlink-path-comparison-in-schema-validation
Fix symlink path comparison in schema validation
2025-12-06 10:06:48 +09:00
Devon Boyer
b34fae93f0 Fix symlink path comparison in schema validation 2025-12-04 22:39:23 -05:00
Koichi ITO
acf4d6025c Add a missing assertion in ConfigurationTest
This PR adds a missing assertion in `ConfigurationTest`.
2025-12-05 08:49:18 +09:00
Koichi ITO
c786a14f61 Default to the latest stable protocol version
When starting an MCP server in Claude Code with `protocol_version` set to `DRAFT-2025-v3`,
it fails with the following error:

```console
2025-12-04T02:58:01.548Z [DEBUG] MCP server "example": Connection failed after 2093ms: Server's protocol version is not supported: DRAFT-2025-v3
2025-12-04T02:58:01.548Z [ERROR] MCP server "example" Connection failed: Server's protocol version is not supported: DRAFT-2025-v3
```

This PR changes the default behavior so that if `protocol_version` is not specified,
it uses the latest stable protocol version instead of the draft version.

This PR also updates the README to note that the latest stable protocol version includes
new features from the draft version.
2025-12-04 14:58:41 +09:00
Koichi ITO
117bb426e5 [Docs] Update specification URL to latest
This PR updates the specification URL to `latest`.
This change avoids the need to update the URL whenever a new protocol version is released.
The `latest` path redirects to the latest protocol version.
2025-11-30 17:42:27 +09:00
Koichi ITO
dacd5f1741 [Doc] Fix incorrect examples in README.md
This PR fixes incorrect examples in README.md. The block variable could be removed if it is unused,
but when presenting an example `:server_context` should still be shown as a keyword argument.

Fixes #185.
2025-11-28 12:29:06 +09:00
Koichi ITO
00392b660d
Merge pull request #181 from jonathanhefner/generate-api-docs
Add API documentation with GitHub Pages deployment
2025-11-27 12:54:46 +09:00
Koichi ITO
6bb96dd891
Merge pull request #183 from modelcontextprotocol/dependabot/github_actions/actions/checkout-6
Bump actions/checkout from 5 to 6
2025-11-26 00:45:37 +09:00
dependabot[bot]
fecf33588c
Bump actions/checkout from 5 to 6
Bumps [actions/checkout](https://github.com/actions/checkout) from 5 to 6.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-24 20:51:26 +00:00
Koichi ITO
d31c3da8f2
Merge pull request #178 from koic/add_elicitation_skeleton
Add Elicitation skeleton
2025-11-25 01:02:30 +09:00
Koichi ITO
14ef006cd3
Merge pull request #182 from koic/update_agents_md
Update AGENTS.md
2025-11-24 03:49:49 +09:00
Koichi ITO
056b0a61b4 Update AGENTS.md
Follow-up to #175.

Since `json_rpc_handler` was merged in #175, it has been removed from AGENTS.md.

The "Dependencies" section was also removed because the information there would have become redundant.
2025-11-23 02:48:03 +09:00
Jonathan Hefner
281c334075 Add API documentation with GitHub Pages deployment
This adds automated deployment of a versioned API documentation landing
page using GitHub Pages. The landing page links to documentation hosted
on RubyDoc.info, the de facto standard documentation site for the Ruby
ecosystem. The landing page will update to reflect new releases.

Changes
-------

1. **Documentation generation script** (see `bin/generate-gh-pages.sh`)

    Copies and commits documentation files to the gh-pages branch. The
    script uses git worktrees to isolate the process from the main
    workspace.

    The script:

    - Creates the gh-pages branch as an orphan branch if it doesn't exist
    - Parses semantic versions from tag names, ignoring arbitrary
      prefixes (e.g., tags `1.2.3`, `v1.2.3`, and `release-1.2.3` all
      create `v1.2.3`)
    - Determines the latest version using semantic version sorting
    - Copies static Jekyll template files from `docs/` to the gh-pages
      root (for the latest version only)
    - Generates `docs/_data/versions.yml` with a list of all versions
      for the Jekyll templates to consume

2. **Jekyll template files** (see `docs/` directory)

    - `docs/_config.yml` - Jekyll configuration
    - `docs/index.md` - Landing page template that links to all versions
      on RubyDoc.info based on generated `docs/_data/versions.yml`
    - `docs/latest/index.html` - Redirect page template that redirects
      to the latest documentation on RubyDoc.info

3. **GitHub Actions workflow** (see `.github/workflows/release.yml`)

    Added a `publish_gh_pages` job that runs after the `publish_gem` job
    on release events. The job invokes the generation script with the
    release tag name, then pushes the updated gh-pages branch to deploy
    the documentation.

4. **CI validation** (see `.github/workflows/ci.yml`)

    Added a `yard` job that runs YARD validation with `--no-output`.
    This ensures YARD can successfully parse the codebase (without
    generating output), catching documentation issues early in CI.

5. **YARD dependencies** (see `Gemfile`)

    Added `yard` and `yard-sorbet` gems as development dependencies to
    support documentation validation in CI.

    YARD documentation is automatically generated and hosted by
    RubyDoc.info when the gem is published to RubyGems.org.

6. **Documentation links** (see `README.md` and `mcp.gemspec`)

    Added links to the published API documentation on RubyDoc.info in
    the README and gemspec metadata.

Documentation URL
-----------------

Custom documentation will be available at:
https://modelcontextprotocol.github.io/ruby-sdk/

RubyDoc.info documentation will be accessible at:
- https://rubydoc.info/gems/mcp (latest version)
- https://rubydoc.info/gems/mcp/1.2.3 (specific versions)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-21 12:21:38 -06:00
Koichi ITO
11aea51c42
Merge pull request #179 from koic/add_draft_version
Add "Draft" protocol version to supported protocol versions
2025-11-22 01:57:51 +09:00
Koichi ITO
26bbdfc28c
Merge pull request #180 from koic/refactor_mcp_server
Refactor to extract duplicate error tool response in `MCP::Server`
2025-11-21 02:43:05 +09:00
Koichi ITO
dd458b1fb7 Add Elicitation skeleton
The MCP 2025-06-18 specification includes a feature called Elicitation:
https://modelcontextprotocol.io/specification/2025-06-18/client/elicitation

Like Log Level, an implementation is expected to be provided in the near future.
This PR adds Elicitation as a skeleton implementation for now.
2025-11-21 02:42:20 +09:00
Koichi ITO
3c452b807c
Merge pull request #176 from koic/tweak_the_readme_doc_for_stateless
[Doc] Tweak the README for stateless
2025-11-20 10:10:31 +09:00
Koichi ITO
1c4ac125e1 Refactor to extract duplicate error tool response in MCP::Server
Consolidates four identical constructions of error `Tool::Response` in
`handle_call_tool_request` into a single private `error_tool_response` method,
reducing duplication and improving maintainability. No behavior change.
2025-11-14 13:54:44 +09:00
Koichi ITO
bf729baef2 Add "Draft" protocol version to supported protocol versions
For example, the `title` introduced in #109 is not supported in the latest stable protocol version "2025-06-18":
https://modelcontextprotocol.io/specification/2025-06-18

It is supported in the Draft of the next version:
https://modelcontextprotocol.io/specification/draft

In other words, the fact that the Ruby SDK treats "2025-06-18" as the default protocol version while `title` is
only supported in the Draft results in an inconsistency.

Because of this, a new version `"Draft"` has been added to the list of supported versions.
Its value follows the schema below and is defined as `DRAFT-2025-v3`:
14ec41c/schema/draft/schema.ts (L15)

It was also considered to continue using the latest stable version "2025-06-18" as the Ruby SDK default instead of the Draft.
However, in that case, users would need to explicitly specify `MCP::Server.new(protocol_version: 'DRAFT-2025-v3')`,
which adds extra burden. In this PR, Draft is made the default in order to provide the following benefits:

- Users are likely to prefer using the Draft version over the latest stable version
- No need to specify the `protocol_version` option when initializing `MCP::Server`
- Users generally do not need to know the internal development value `DRAFT-2025-v3`

The primary case for specifying `protocol_version` explicitly is when strict adherence to a particular version is required.
However, it seems more practical to prioritize use cases where backward-compatible features, including those from the Draft,
are desirable. This is the rationale behind making the Draft version the default.

In addition, making the Draft version the default protocol version preserves backward compatibility for `MCP::Server`.

NOTE: `DRAFT-2025-v3` is a development code, so its value cannot be set externally.
It is applied either when `protocol_version` is omitted or when `nil` is set explicitly,
such as with `MCP::Configuration.new(protocol_version: nil)`.
This prevents users from creating implementations that depend on development codes like `DRAFT-2025-v3`.
2025-11-11 15:44:36 +09:00
Koichi ITO
b8719ce04f [Doc] Tweak the README for stateless
`stateless` was supported in #101. However, as shown in the official specification below,
the supported transports are stdout and Streamable HTTP, and whether it is stateless is
a detail specific to Streamable HTTP:
https://modelcontextprotocol.io/specification/2025-06-18/basic/transports

This PR updates the documentation to describe `stateless` as part of the Streamable HTTP section.
2025-11-08 12:55:35 +09:00
Koichi ITO
400a56e83d
Merge pull request #101 from 1debit/stateless
Add `stateless` feature to Streamable HTTP protocol
2025-11-07 09:11:33 +09:00
Hiren Hiranandani
08a84c7320
Introduce stateless mode to allow for HA
- Create failing tests for `stateless` mode
- Implement `stateless` mode by turning of SSE in Streamable HTTP,
  making the interaction a standard HTTP Req/Resp
2025-11-04 15:26:12 -08:00
Koichi ITO
55dfbdc3b6
Merge pull request #174 from koic/extract_release_from_readme_to_a_new_file
[Docs] Extract release documentation to RELEASE.md
2025-11-04 12:33:39 +09:00
Koichi ITO
5b737eb9c3 [Docs] Extract release documentation to RELEASE.md
README is generally better kept focused on information that is most valuable to users.
For that reason, release procedures that are not relevant to end users have been moved to
a separate RELEASE.md file.
2025-11-04 11:13:39 +09:00
Ateş Göral
3f5f6f8494
Internalize json_rpc_handler along with an XSS vulnerability fix (#175)
* Copy-paste of files from original gem

* Update copied code to match repo style

* Use the lib instead of the gem
2025-10-30 17:43:31 -04:00
Koichi ITO
c152f15a25
Merge pull request #173 from koic/add_bug_tracker_url_to_gemspec
Add bug tracker URL metadata to gemspec
2025-10-29 09:36:38 +08:00
Koichi ITO
fc59f440b0 Add bug tracker URL metadata to gemspec
It would be convenient if users could visit to the bug tracker directly from the published RubyGems.
https://rubygems.org/gems/mcp
2025-10-28 08:15:30 +09:00
Topher Bullock
ea216047dc
Merge pull request #169 from koic/remove_redundant_require_rack_gem
Remove redundant `rack` gem
2025-10-27 11:06:01 -04:00
Koichi ITO
cdf5b1cf92
Merge pull request #171 from koic/fix_incorrect_schema_name
[Doc] Fix incorrect schema name
2025-10-27 00:24:31 +09:00
Koichi ITO
fb67a9b969 [Doc] Fix incorrect schema name
This PR fixes an incorrect schema name.

The test code already uses `items:`.
https://github.com/modelcontextprotocol/ruby-sdk/blob/v0.4.0/test/mcp/tool/output_schema_test.rb#L135-L141

Fixes #170.
2025-10-26 01:24:45 +09:00
Koichi ITO
61d48cd6d9
Merge pull request #165 from Jflick58/fix/make-tool-error-spec-compliant
Fix tool error handling to follow MCP spec
2025-10-22 10:58:29 +09:00
Justin Flick
389cc2e8e6 Fix tool error handling to follow MCP spec
Tool execution errors now return successful responses with isError: true
instead of JSON-RPC protocol errors, per the MCP specification.

This allows clients to distinguish between protocol-level errors and
tool execution errors, providing better error context.

Fixes #159
2025-10-21 18:33:42 -07:00
Koichi ITO
4851a16d39 Remove redundant rack gem
This PR removes the existing `rack` dependency.
`rack` is a dependency of `rackup`.
2025-10-20 19:24:21 +09:00
Koichi ITO
ad87c8d805
Merge pull request #163 from dak2/add-client-prompts-support
Add `prompts/list` and `prompts/get` support to client
2025-10-19 02:24:36 +09:00
Koichi ITO
b36aea0716
Merge pull request #168 from koic/add_changelog_url_metadata_to_gemspec
Add changelog URL metadata to gemspec
2025-10-17 03:31:56 +09:00
Koichi ITO
e03222d206 Add changelog URL metadata to gemspec
It would be convenient if users could trace the change history directly from the published RubyGems.
https://rubygems.org/gems/mcp
2025-10-16 11:43:41 +09:00
Topher Bullock
944660a8b0
Merge pull request #167 from modelcontextprotocol/release-0.4.0
Release v0.4.0
2025-10-15 14:56:18 -04:00
Topher Bullock
9aafc9add5 Release 0.4.0 2025-10-15 01:25:05 -04:00
dak2
e88deb6b65 Add prompts/list and prompts/get support to client
This commit adds two new methods to `MCP::Client`:
- prompts: Lists available prompts from the server via `prompts/list`
- get_prompt: Retrieves a specific prompt by name via `prompts/get`

Both methods follow the same pattern as the existing resources support,
including comprehensive test coverage and README documentation updates.

ref. https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/server/prompts.mdx#protocol-messages
2025-10-15 13:16:41 +09:00
Koichi ITO
f312695798
Merge pull request #153 from modelcontextprotocol/prompt-spec-compliance
fix `Prompt` type gaps with 2025-06-18 spec
2025-10-15 01:22:45 +09:00
Koichi ITO
f8557e5ceb
Merge pull request #166 from dak2/fix-client-tools-test
Fix and add test for client tools functionality
2025-10-14 01:49:22 +09:00
dak2
7b4ece294b Fix and add test for client tools functionality
- Add test for empty tools array response to ensure client handles empty
  results correctly
- Update call_tool test to use proper content format (array of content
  objects) instead of plain string based on
  modelcontextprotocol spec.
  https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/server/tools.mdx#calling-tools

Follow up: modelcontextprotocol#160
2025-10-13 11:14:48 +09:00
Koichi ITO
92a08bafc7
Merge pull request #162 from dak2/fix-client-resouces-test
Fix test for empty resources response of client
2025-10-13 02:02:25 +09:00
Koichi ITO
5b57563738
Merge pull request #161 from koic/mention_mcp_client_resources_methods_to_readme
[Doc] Mention `resources/list` and `resources/read` in the README
2025-10-12 11:28:30 +09:00
dak2
ad3c1b1b72 Fix test for empty resources response
Update test_resources_returns_empty_array_when_no_resources to use
correct mock response format with empty resources array instead of
empty result object. Also reorder test to group with other resources
tests.

Follow up: https://github.com/modelcontextprotocol/ruby-sdk/pull/160
2025-10-12 00:44:17 +09:00
Koichi ITO
93215f4d52 [Doc] Mention resources/list and resources/read in the README
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/160
2025-10-12 00:33:01 +09:00
Koichi ITO
c51060031a
Merge pull request #160 from modelcontextprotocol/client-add-resource-support
add `resources/list` and `resources/read` support to client
2025-10-11 01:16:06 +09:00
Topher Bullock
2d1a1da937 add resources/list and resources/read support to client 2025-10-10 10:51:42 -04:00
Topher Bullock
a1dd3dd005 add _meta field to Prompt
> See [General fields: `_meta`](/specification/2025-06-18/basic/index#meta) for notes on `_meta` usage.

51e093b8eb/schema/2025-06-18/schema.ts (L680-L683)
2025-10-10 09:05:55 -04:00
Koichi ITO
b10a469013
Merge pull request #157 from koic/fix_a_typo_for_streamable_http_transport
[Doc] Fix incorrect example code in README
2025-10-10 01:03:52 +09:00
Koichi ITO
a217f70d95 [Doc] Fix incorrect example code in README
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/33.

A `NameError` occurs because `MCP::Transports::HTTP` does not exist.
The correct constant is `MCP::Server::Transports::StreamableHTTPTransport`.
2025-10-09 11:44:58 +09:00
Koichi ITO
77370cbb93
Merge pull request #154 from koic/remove_redundant_requiring_transports
Remove unnecessary transport requires
2025-10-08 12:06:31 +09:00
Koichi ITO
bee6eace22 Remove unnecessary transport requires
The transports are already required by `require 'mcp'`:
https://github.com/modelcontextprotocol/ruby-sdk/blob/v0.3.0/lib/mcp.rb#L16-L17
2025-10-07 14:10:48 +09:00
Topher Bullock
701f6faab6 add title field to prompt argument
`PromptArgument extends BaseMetadata`, which includes both name and
title
 - 51e093b8eb/schema/2025-06-18/schema.ts (L686-L698)
 - 51e093b8eb/schema/2025-06-18/schema.ts (L294-l309)
2025-10-06 09:35:42 -04:00
Koichi ITO
b5e344e456
Merge pull request #132 from dr03ramos/patch-1
Update metaschema URI format in input_schema.rb
2025-10-06 10:34:47 +09:00
Koichi ITO
f226e57ce3
Merge pull request #152 from modelcontextprotocol/dependabot/github_actions/actions/checkout-5
Bump actions/checkout from 3 to 5
2025-10-05 02:47:54 +09:00
dependabot[bot]
e41d961e4c
Bump actions/checkout from 3 to 5
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-04 16:35:48 +00:00
Koichi ITO
04de0c8be9
Merge pull request #151 from koic/move_dependabot_yml
Move dependabot.yml into .github
2025-10-05 01:35:06 +09:00
ramos
4c13f6dc08 Update metaschema URI format in input_schema.rb and output_schema.rb for
cross-compatibility across different OS
2025-10-03 17:29:50 -03:00
Koichi ITO
435b8c8b22 Move dependabot.yml into .github
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/138.

The `dependabot.yml` file must be placed under the `.github` directory,
but it was mistakenly placed outside of it.
2025-10-04 00:14:49 +09:00
Koichi ITO
c5f2f98077
Merge pull request #150 from koic/set_default_content_to_an_empty_array_instead_of_nil
Set default `content` to an empty array instead of `nil`
2025-10-03 10:22:46 +09:00
Koichi ITO
0034952df9 Set default content to an empty array instead of nil
Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/pull/147.

According to the specification schema, `content` is not optional and therefore cannot be omitted:

```typescript
interface CallToolResult {
  _meta?: { [key: string]: unknown };
  content: ContentBlock[];
  isError?: boolean;
  structuredContent?: { [key: string]: unknown };
  [key: string]: unknown;
}
```

https://modelcontextprotocol.io/specification/2025-06-18/schema#calltoolresult

Instead of `nil`, an empty array is set as the default value.

There may be a better value for `content`, but at the very least it should not be missing.
2025-10-02 23:52:19 +09:00
Tyler Untisz
73cec83b99
Add support for _meta field on tool schema (#124)
* Add support for _meta field on tool schema

* use `meta` naming for `_meta` field on tool schema

* apply suggestions to fix `_meta` tests

Co-authored-by: Ateş Göral <ates@magnetiq.com>

* Update lib/mcp/tool.rb

Co-authored-by: Ateş Göral <ates@magnetiq.com>

* Update lib/mcp/tool.rb

Co-authored-by: Ateş Göral <ates@magnetiq.com>

---------

Co-authored-by: Topher Bullock <topherbullock@users.noreply.github.com>
Co-authored-by: Ateş Göral <ates@magnetiq.com>
2025-10-01 17:21:27 -04:00
Topher Bullock
c0f7605d25
Merge pull request #149 from juharris/client-call_tool_raw
[client] Change call_tool method to return the full tool response to help get structuredContent
2025-10-01 15:37:49 -04:00
Justin Harris
ae60e2d904
[client] Add call_tool_raw method to get the full tool response to help get structuredContent 2025-10-01 15:18:02 -04:00
Koichi ITO
010ae74edc
Merge pull request #145 from koic/add_validation_to_mcp_configuration_setters
Add validation to `MCP::Configuration` setters
2025-10-01 10:50:38 +09:00
Koichi ITO
f21629ca74
Merge pull request #148 from koic/remove_redundant_sort_in_spec
Remove redundant sort in spec
2025-09-30 00:17:12 +09:00
Koichi ITO
777785b333 Remove redundant sort in spec 2025-09-29 01:24:38 +09:00
Koichi ITO
de1e833ae3
Merge pull request #144 from nilcolor/output_schema_arrays
Allow output schema to be array of objects
2025-09-28 03:17:09 +09:00
Anandaroop Roy
f7cf080cc0
Support structuredContent in tool response (#147) 2025-09-27 02:23:41 -04:00
Koichi ITO
99b57a3cc2
Merge pull request #114 from dak2/handle-202
Fix to return a response code 202 if the server accepts JSON-RPC notifications and responses
2025-09-27 14:00:17 +09:00
Koichi ITO
8f682c4ff6
Merge pull request #146 from koic/fix_some_typos
Fix some typos
2025-09-26 10:12:46 +09:00
dak2
cd7a54a5c9 Fix to return a response code 202 if the server accepts JSON-RPC notifications and responses
If the server accepts JSON-RPC notifications and responses, it must return an HTTP status code of 202 without a body.

refs
- https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#sending-messages-to-the-server
- https://www.jsonrpc.org/specification

Follow up: https://github.com/modelcontextprotocol/ruby-sdk/issues/111
2025-09-26 00:18:01 +09:00
Koichi ITO
99f90b8b31 Fix some typos
The `ModelContextProtocol` module name has been renamed to `MCP`,
and `define_protocol` appears to be a typo for `define_prompt`.
2025-09-25 18:06:34 +09:00
Alexey Blinov
4ee128ad67 Allow output schema to be array of objects
closes #142
2025-09-25 11:56:03 +05:00
Koichi ITO
cb5e87581b Add validation to MCP::Configuration setters
I noticed through the existing tests that `MCP::Configuration#protocol_version=`
allows setting an arbitrary protocol version.

Since the official MCP Ruby SDK is an implementation of the MCP specification,
it should not support arbitrary protocol versions. This change adds validation
to the setter, consistent with `Configuration#initialize`.

The same validation has also been added to `MCP::Configuration#validate_tool_call_arguments=`.
2025-09-24 19:19:02 +09:00
Ateş Göral
aba616342f
Add AGENTS.md with comprehensive development guidance (#134)
* Add CLAUDE.md with development guidance and architecture overview

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Rename CLAUDE.md to AGENTS.md and restructure to follow agents.md standard

- Adopt the new agents.md format for AI coding assistant guidance
- Reorganize content into standard sections: project overview, dev setup, build commands, testing, code style, and architecture
- Maintain all essential technical information while improving accessibility
- Support the growing ecosystem of AI tools that recognize agents.md

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Consolidate Cursor-specific rules into AGENTS.md and remove tool-specific files

- Add release process section to AGENTS.md with changelog guidelines
- Include Keep a Changelog format requirements and entry formatting rules
- Remove .cursor/rules/release-changelogs.mdc to favor universal AGENTS.md format
- Ensure all AI coding assistants have access to release documentation guidelines

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add blank lines after headings

Co-authored-by: Koichi ITO <koic.ito@gmail.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Koichi ITO <koic.ito@gmail.com>
2025-09-22 23:25:29 -04:00
Koichi ITO
e168292876
Merge pull request #139 from koic/remove_useless_block_argument
Remove unused block parameters
2025-09-21 13:09:20 +09:00
Koichi ITO
0c8937de34 Remove unused block parameters
There are some unused block variables. This change removes block parameters
that consist solely of unused block parameters.
Where `Hash#values` suffices instead of ignoring unused variables,
replace such code with `Hash#values`.
2025-09-20 14:45:08 +09:00
Koichi ITO
a17b23e1a4
Merge pull request #138 from koic/enable_dependabot
Enable Dependabot
2025-09-18 09:37:12 +09:00
Koichi ITO
30d2b0b22b Enable Dependabot
Configure Dependabot to automatically detect updates to the actions used in
GitHub Actions (e.g., `actions/checkout`) and create pull requests for them.

Based on experience, checking for updates on a weekly interval should work well.
2025-09-17 00:26:25 +09:00
Koichi ITO
d67609d43d
Merge pull request #137 from koic/remove_useless_magic_comment
Remove useless magic comment
2025-09-16 02:35:22 +09:00
Koichi ITO
b626425521 Remove useless magic comment
This PR removes useless magic comment.
2025-09-15 12:33:09 +09:00
237 changed files with 55513 additions and 2744 deletions

View file

@ -1,17 +0,0 @@
---
description: Updating CHANGELOG.md before cutting a new release of the gem
globs: CHANGELOG.md
alwaysApply: false
---
- start by refreshing your knowledge on the Keep a Changelog convention by reading the format spec referenced at the top of CHANGELOG.md
- stick to Keep a Changelog
- entries should be terse and in a top-level flat list: do not nest
- follow this format for entries:
- Terse description of the change (#nnn)
- git tags are used to mark the commit that cut a new release of the gem
- the gem version is located in [version.rb](mdc:lib/mcp/version.rb)
- use the git history, especially merge commits from PRs to construct the changelog
- when necessary, look at the diff of files changed to determine the true nature of the change
- maintenance PRs that don't concern end users of the gem should not be listed in the changelog
- when checking PRs, see if there's an upstream remote, and if so, fetch PRs from upstream instead of origin

6
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,6 @@
version: 2
updates:
- package-ecosystem: 'github-actions'
directory: '/'
schedule:
interval: 'weekly'

View file

@ -4,16 +4,22 @@ on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
permissions:
contents: read
strategy:
matrix:
entry:
- { ruby: 3.2, allowed-failure: false }
- { ruby: 3.3, allowed-failure: false }
- { ruby: 3.4, allowed-failure: false }
- { ruby: head, allowed-failure: true }
- { ruby: '2.7.0', allowed-failure: false } # Minimum supported Ruby version.
- { ruby: '3.0', allowed-failure: false }
- { ruby: '3.1', allowed-failure: false }
- { ruby: '3.2', allowed-failure: false }
- { ruby: '3.3', allowed-failure: false }
- { ruby: '3.4', allowed-failure: false }
- { ruby: '4.0', allowed-failure: false }
- { ruby: 'head', allowed-failure: true }
name: Test Ruby ${{ matrix.entry.ruby }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v7
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.entry.ruby }}
@ -23,11 +29,26 @@ jobs:
rubocop:
runs-on: ubuntu-latest
permissions:
contents: read
name: RuboCop
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v7
- uses: ruby/setup-ruby@v1
with:
ruby-version: 3.2 # Specify the oldest supported Ruby version.
ruby-version: 4.0 # Specify the latest supported Ruby version.
bundler-cache: true
- run: bundle exec rake rubocop
yard:
runs-on: ubuntu-latest
permissions:
contents: read
name: YARD Documentation
steps:
- uses: actions/checkout@v7
- uses: ruby/setup-ruby@v1
with:
ruby-version: 4.0 # Specify the latest supported Ruby version.
bundler-cache: true
- run: bundle exec yard --no-output

29
.github/workflows/conformance.yml vendored Normal file
View file

@ -0,0 +1,29 @@
name: Conformance Tests
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
concurrency:
group: conformance-${{ github.ref }}-${{ github.event_name == 'push' && github.sha || '' }}
cancel-in-progress: true
permissions:
contents: read
jobs:
server-conformance:
runs-on: ubuntu-latest
continue-on-error: true
steps:
- uses: actions/checkout@v7
- uses: ruby/setup-ruby@v1
with:
ruby-version: '4.0' # Specify the latest supported Ruby version.
bundler-cache: true
- uses: actions/setup-node@v7
with:
node-version: '24' # Specify the latest Node.js version.
- run: bundle exec rake conformance:test

View file

@ -16,10 +16,42 @@ jobs:
id-token: write # IMPORTANT: this permission is mandatory for trusted publishing
contents: write # IMPORTANT: this permission is required for `rake release` to push the release tag
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
bundler-cache: true
ruby-version: 3.4
ruby-version: 4.0
- uses: rubygems/release-gem@v1
publish_gh_pages:
if: github.repository_owner == 'modelcontextprotocol'
name: Publish Documentation to GitHub Pages
runs-on: ubuntu-latest
needs: [publish_gem]
permissions:
contents: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0 # Fetch all history for all branches and tags
- name: Configure Git
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
- name: Get version tag
id: version
run: |
git fetch --tags
TAG=$(git describe --tags --exact-match HEAD)
echo "tag=${TAG}" >> $GITHUB_OUTPUT
- name: Generate GitHub Pages
run: ./bin/generate-gh-pages.sh ${{ steps.version.outputs.tag }}
- name: Push to gh-pages
run: git push origin gh-pages

5
.gitignore vendored
View file

@ -1,4 +1,5 @@
.ruby-version
/*.gem
/.bundle/
/.yardoc
/_yardoc/
@ -8,3 +9,7 @@
/spec/reports/
/tmp/
Gemfile.lock
docs/_site/
docs/.jekyll-cache/
docs/.jekyll-metadata
docs/_data/versions.yml

View file

@ -5,8 +5,19 @@ plugins:
- rubocop-minitest
- rubocop-rake
AllCops:
TargetRubyVersion: 2.7
SuggestExtensions: false
Gemspec/DevelopmentDependencies:
Enabled: true
Lint/IncompatibleIoSelectWithFiberScheduler:
Enabled: true
Minitest/LiteralAsActualArgument:
Enabled: true
Naming/MethodName:
AllowedPatterns:
- '\Atest_'

132
AGENTS.md Normal file
View file

@ -0,0 +1,132 @@
# AGENTS.md
## Project overview
This is the official Ruby SDK for the Model Context Protocol (MCP), implementing both server and client functionality for JSON-RPC 2.0 based communication between LLM applications and context providers.
## Dev environment setup
- Ruby 3.2.0+ required to run the full test suite, including all Sorbet-related features
- Run `bundle install` to install dependencies
- Dependencies: `json-schema` >= 4.1 - Schema validation
## Build and test commands
- `bundle install` - Install dependencies
- `rake test` - Run all tests
- `rake rubocop` - Run linter
- `rake` - Run linting, tests, and the conformance suite (default task)
- `bundle exec rake conformance:test` - Run the MCP conformance suite (see conformance/README.md)
- `bundle exec rake docs:preview` - Serve the documentation site locally at http://localhost:4000 (PORT to override)
- `ruby -I lib -I test test/path/to/specific_test.rb` - Run single test file
- `gem build mcp.gemspec` - Build the gem
## Testing instructions
- Test files are in `test/` directory with `_test.rb` suffix
- Run full test suite with `rake test`
- Run individual tests with `ruby -I lib -I test test/path/to/file_test.rb`
- Tests should pass before submitting PRs
## Code style guidelines
- Follow RuboCop rules (run `rake rubocop`)
- Use frozen string literals
- Follow Ruby community conventions
- Keep dependencies minimal
- Use lowercase HTTP response header names (e.g. `mcp-session-id`); the Rack 3 SPEC requires this, and the MCP spec's `Mcp-Session-Id` casing is prose convention only
## Documentation
- User-facing documentation lives in `docs/`, one page per topic, published at https://ruby.sdk.modelcontextprotocol.io (deploys only when a release is published)
- Pages live in the `docs/_server/`, `docs/_client/`, and `docs/_extensions/` collections
- Keep README.md slim: quick start and pointers only; document features on the relevant docs page
- Internal links are absolute and extensionless (e.g. `/server/tools/`); front matter is followed by a blank line before the h1
- Callout tiers: `.note` (supplementary), `.important` (spec constraints), `.warning` (deprecated features)
## Commit message conventions
- Use conventional commit format when possible
- Include clear, descriptive commit messages
- Releases are triggered by updating version in `lib/mcp/version.rb` and merging to main
## Release process
- Follow [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format in CHANGELOG.md
- Update CHANGELOG.md before cutting releases
- Use git history and PR merge commits to construct changelog entries
- Format entries as: "Terse description of the change (#nnn)"
- Keep entries in flat list format (no nesting)
- Git tags mark commits that cut new releases
- Exclude maintenance PRs that don't concern end users
- Check upstream remote for PRs if available
## Architecture overview
### Core Components
**MCP::Server** (`lib/mcp/server.rb`):
- Main server class handling JSON-RPC requests and holding shared configuration (tools, prompts, resources, handlers, capabilities)
- Implements MCP protocol methods: initialize, ping, tools/list, tools/call, prompts/list, prompts/get, resources/list, resources/read
- Supports custom method registration via `define_custom_method`
- Handles instrumentation, exception reporting, and notifications
- Uses JsonRpcHandler for request processing
**MCP::ServerSession** (`lib/mcp/server_session.rb`):
- Per-connection state: client info, logging level
- Created by the transport layer for each client connection
- Delegates request handling to the shared `Server`
**MCP::Client** (`lib/mcp/client.rb`):
- Client interface for communicating with MCP servers
- Transport-agnostic design with pluggable transport layers
- Supports tool listing and invocation
**Transport Layer**:
- `MCP::Server::Transports::StdioTransport` - Command-line stdio transport
- `MCP::Server::Transports::StreamableHttpTransport` - HTTP with streaming support
- `MCP::Client::HTTP` - HTTP client transport (requires faraday gem)
**Protocol Components**:
- `MCP::Tool` - Tool definition with input/output schemas and annotations
- `MCP::Prompt` - Prompt templates with argument validation
- `MCP::Resource` - Resource registration and retrieval
- `MCP::Configuration` - Global configuration with exception reporting and instrumentation
### Key Patterns
**Three Ways to Define Components**:
1. Class inheritance (e.g., `class MyTool < MCP::Tool`)
2. Define methods (e.g., `MCP::Tool.define(name: "my_tool") { ... }`)
3. Server registration (e.g., `server.define_tool(name: "my_tool") { ... }`)
**Schema Validation**:
- Tools support input_schema and output_schema for JSON Schema validation
- Protocol version 2025-03-26+ supports tool annotations (destructive_hint, idempotent_hint, etc.)
- Validation is configurable via `configuration.validate_tool_call_arguments`
**Session Architecture**:
- `Server` holds shared configuration (tools, prompts, resources, handlers)
- `ServerSession` holds per-connection state (client info, logging level)
- Both `StdioTransport` and `StreamableHTTPTransport` create a `ServerSession` per connection, making the session model transparent across transports
- Session-scoped notifications (`notify_progress`, `notify_log_message`) are sent only to the originating client via `ServerSession`
- Server-wide notifications (`notify_tools_list_changed`, etc.) broadcast to all sessions via `Server`
**Context Passing**:
- `server_context` hash passed through tool/prompt calls for request-specific data
- Methods can accept `server_context:` keyword argument for accessing context
### Integration patterns
- **Rails/Rack apps**: Mount `StreamableHTTPTransport` as a Rack app (e.g., `mount transport => "/mcp"`)
- **Command-line tools**: Use `StdioTransport.new(server).open` for CLI applications
- **HTTP services**: Use `StreamableHTTPTransport` for web-based servers

View file

@ -7,6 +7,543 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.5.1] - 2026-09-09
This release keeps the HTTP client working with json 3.0. That release accepts the options of `JSON.parse`
as keywords only, and Faraday's JSON response middleware, through 2.14.3, passes them as a positional Hash,
which Ruby 3 no longer converts, so every JSON body the client received failed as an internal error.
The client now parses response bodies itself, the way it already handled streamed ones, and no longer
registers the middleware. A malformed JSON body delivered whole by an adapter without streaming support
now raises `RequestHandlerError` with `error_type: :parse_error`, as the streamed path already did.
### Fixed
- Parse HTTP client response bodies without Faraday's JSON middleware, which json 3.0 breaks (#546)
## [1.5.0] - 2026-09-05
This release makes the client answer a server's `ping` with the empty result the specification requires.
Earlier clients replied with Method not found over Streamable HTTP and stayed silent over stdio,
so a server that checks liveness dropped their long-lived sessions. On the OAuth side,
the embedding application can refuse an authorization request through `authorization_request_validator`,
and stored tokens are refreshed only against the authorization server that issued them:
when the server named for a session differs, the client reauthorizes instead of refreshing,
and the validator sees the newly named server. Tokens stored by earlier releases carry no issuer and keep refreshing.
### Added
- Add `authorization_request_validator` to let the embedding application refuse an authorization request (#539)
### Fixed
- Answer server-to-client pings in the client (#541)
## [1.4.0] - 2026-08-28
This release repairs the `subscriptions/listen` stream. A host that buffers its responses,
the documented Rails controller pattern among them, can decline the method with
`serve_subscriptions_listen: false` instead of answering a modern client with a streaming body
it cannot render, and the stream's ordering guarantees are enforced: no notification reaches
a client before the acknowledgement, and none follows the graceful closing result.
### Added
- Add `serve_subscriptions_listen:` for hosts that cannot hold an SSE stream open (#533)
### Fixed
- Deliver `subscriptions/listen` notifications only after the acknowledgement (#532)
- Serialize `subscriptions/listen` writes so the graceful result is the final message (#535)
## [1.3.0] - 2026-08-22
User-facing documentation now lives on the documentation site at https://ruby.sdk.modelcontextprotocol.io,
and README.md keeps the quick start. Two entries under "Changed" reject traffic that earlier releases accepted
and ship in a minor release under the exceptions described in [VERSIONING.md](VERSIONING.md).
### Added
- Add a `resources_list_handler` for context-dependent resource lists (#509)
- Pass a handler-returned `_meta` through the subscribe result (#510)
### Changed
- Bound OAuth response bodies in the client (#520)
- Reject duplicate in-flight JSON-RPC request ids (#521)
- Move the documentation from README.md to the documentation site (#523)
## [1.2.0] - 2026-08-15
This release completes the SEP-2575 stateless lifecycle of the 2026-07-28 specification, together with
the SEP-2322, SEP-2549, and SEP-2243 features that revision builds on. Several entries under "Changed"
are incompatible with 1.1.0 and ship in a minor release under the spec-conformance and security exceptions
described in [VERSIONING.md](VERSIONING.md).
### Added
- Handle the SEP-2575 modern request envelope in the server core (#475)
- Serve both lifecycle eras over stdio with an era lock per SEP-2575 (#478)
- Serve the sessionless modern path over Streamable HTTP per SEP-2575 (#479)
- Finalize `server/discover` and add client modern lifecycle support per SEP-2575 (#480)
- Let handlers return multi round-trip `input_required` results per SEP-2322 (#481)
- Add `MCP::Elicitation::EnumSchema` builders per SEP-1330 (#482)
- Stamp the required `resultType` on modern results per SEP-2322 (#487)
- Enforce the modern lifecycle admission rules per SEP-2575 (#489)
- Stream modern request notifications and honor the envelope `logLevel` per SEP-2575 (#490)
- Expose the user-defined `server_context` in instrumentation data (#493)
- Serve the `subscriptions/listen` notification stream per SEP-2575 (#495)
- Add opt-in `requestState` sealing via `MCP::Server::RequestStateSecurity` (#496)
- Mirror `x-mcp-header` tool parameters into `Mcp-Param-*` headers per SEP-2243 (#498)
- Stamp the required cache hints on modern cacheable results per SEP-2549 (#499)
- Drive multi round-trip `input_required` results on the client per SEP-2322 (#500)
- Fulfill `input_required` results on the legacy wire per SEP-2322 (#501)
### Changed
- Align modern envelope validation with the finalized specification (#491)
- Require the `Mcp-Method` header on the modern path (#492)
- Bound server-to-client requests with a timeout (#502)
- Refuse server-to-client requests in the modern lifecycle per SEP-2575 (#503)
- Bound the total wait across SSE reconnection attempts (#504)
- Bound automatic pagination in the MCP client (#505)
- Reject modern-removed methods before the connection era locks (#511)
- Stop negotiating modern protocol versions through the `initialize` handshake (#516)
### Deprecated
- Warn on modern client connects that declare the Roots or Sampling capabilities deprecated per SEP-2577 (#406, #516)
### Fixed
- Stop leaking exception messages to clients via JSON-RPC error data (#486)
- Return Invalid Params for unknown prompts and missing prompt arguments (#517)
- Restrict OAuth discovery to same-origin metadata URLs and refuse private-network destinations
## [1.1.0] - 2026-08-01
### Added
- Support 2026-07-28 as the Latest Protocol Version (#476)
- Expose server tool annotations on MCP::Client::Tool (#445)
### Fixed
- Preserve explicit tool response content (#469)
## [1.0.0] - 2026-07-24
First stable release. The public API is now stable: breaking changes ship only in major releases,
apart from the narrow exceptions documented in [VERSIONING.md](VERSIONING.md).
### Added
- Add `ROADMAP.md` outlining the path toward SEP-1730 (#465)
- Add `VERSIONING.md` documenting the versioning and breaking-change policy (#466)
## [0.25.0] - 2026-07-18
### Added
- Support SEP-990 Cross-App Access via ID-JAG and the `jwt-bearer` grant (#454)
- Support client-side sampling via `MCP::Client#on_sampling` (#458)
### Fixed
- Reject notifications carrying an unknown or expired session (#455)
- Handle an `initialize` request sent without an ID (#456)
- Bound client-side message buffering in the HTTP transport (#459)
- Lowercase response header names in `StreamableHTTPTransport` (#460)
## [0.24.0] - 2026-07-12
### Added
- Support SSE reconnection per SEP-1699 in the HTTP client transport (#426)
- Validate the RFC 9207 `iss` authorization response parameter per SEP-2468 (#431)
- Support `private_key_jwt` client authentication for the `client_credentials` grant (#432)
- Recognize multi round-trip `input_required` results per SEP-2322 (#433)
- Add opt-in `ttlMs` / `cacheScope` cache hints to List and Read results per SEP-2549 (#436)
- Add `server/discover` and stateless lifecycle error codes per SEP-2575 (#438)
- Associate server-to-client requests with the originating client request per SEP-2260 (#440)
- Add server-side MCP Apps helpers per SEP-1865 (#441)
- Support client-side elicitation with SEP-1034 schema defaults (#443)
- Support class-based Resource and ResourceTemplate definitions (#447)
### Changed
- Bind stored client credentials to the authorization server issuer per SEP-2352 (#439)
### Fixed
- Handle non-object JSON-RPC messages without raising (#448)
- Perform SSE stream writes outside the session mutex (#449)
- Validate required params for `initialize` and `resources/subscribe` (#451)
## [0.23.0] - 2026-07-07
### Added
- Add a session-ownership hook to `StreamableHTTPTransport`
### Changed
- Require calling `MCP::Client#connect` before sending requests on stdio transport (#427)
### Deprecated
- Annotate Roots, Sampling, and Logging APIs as deprecated per SEP-2577 (#429)
### Fixed
- Fix an incorrect `result: null` response to an id-bearing notification message (#435)
- Validate `Host` and `Origin` headers to prevent DNS rebinding per MCP 2025-11-25
- Bound stateful session retention to prevent an initialize-flood DoS
- Bound stdio frame reads with `max_line_bytes`
- Bound request body and frame reads to prevent memory-exhaustion DoS
## [0.22.0] - 2026-06-27
### Added
- Add `audience` role validation for `MCP::Annotations` per MCP specification (#422)
- Send SEP-2243 `Mcp-Method` and `Mcp-Name` headers per MCP specification (#423)
- Support client-side `notifications/cancelled` per MCP specification (#425)
### Changed
- Conform Tool Schemas to JSON Schema 2020-12 per SEP-2106 (#417)
### Fixed
- Fix a `SyntaxError` on Ruby 2.7.0 caused by arguments forwarding syntax (#419)
## [0.21.0] - 2026-06-20
### Added
- Support capability extensions per SEP-2133 (#405)
- Add range validation for `MCP::Annotations#priority` per MCP specification (#410)
- Isolate stateless requests in ephemeral sessions per SEP-2567 (#415)
### Changed
- Set OIDC `application_type` on Dynamic Client Registration per SEP-837 (#408)
- Fall back to legacy 2025-03-26 OAuth discovery for servers without PRM (#414)
## [0.20.0] - 2026-06-14
### Added
- Support W3C Trace Context Propagation via `_meta` per SEP-414 (#397)
- Support OAuth `client_credentials` grant in OAuth client (#399)
- Add `annotations` field to `MCP::Resource` and `MCP::ResourceTemplate` per MCP specification (#403)
### Changed
- Re-run OAuth flow on 403 `insufficient_scope` (step-up) (#368)
- Speed up `Tool::Schema` validation by 5x to 100x (#369)
- Use JSON-RPC error envelope for `StreamableHTTPTransport` errors (#371)
- Pin RFC 8414 default well-known suffix per SEP-2351 (#395)
- Default missing `MCP-Protocol-Version` to `2025-03-26` in `StreamableHTTPTransport` (#392)
### Fixed
- Preserve the request ID in invalid request error responses (#400)
- Standardize Resource Not Found errors on -32602 with URI data per SEP-2164 (#402)
## [0.19.0] - 2026-06-13
### Added
- Support Client ID Metadata Documents in OAuth client (#361)
- Request `offline_access` scope when supported (#365)
- Add `size` field to `MCP::Resource` per MCP specification (#393)
## [0.18.0] - 2026-05-30
### Added
- Support server-to-client `ping` per MCP specification (#358)
### Changed
- Warn on implicit stdio initialization (#338)
- Cache `Tool::Schema` validation to avoid re-validating identical schemas (#363)
### Fixed
- Fix case-sensitive `Accept` header comparison (#359)
## [0.17.0] - 2026-05-19
### Added
- Add OAuth 2.1 client support for MCP authorization flow (#353)
### Fixed
- Validate `MCP-Protocol-Version` header in `StreamableHTTPTransport` (#347)
- Reject duplicate `initialize` requests (#350)
- Reject non-Hash JSON-RPC bodies in `StreamableHTTPTransport` (#354)
## [0.16.0] - 2026-05-14
### Added
- Add opt-in tool output validation (#344)
### Changed
- Advertise JSON Schema 2020-12 dialect on emitted tool schemas (#342)
### Fixed
- Preserve client tool output schemas (#343)
- Fix missing `output_schema` argument in `define_tool` API (#301)
## [0.15.0] - 2026-05-05
### Added
- Support `notifications/cancelled` per MCP specification (#332)
- Add client-level `connect` for initialize handshake (#327)
- Add client-level `connect` handshake to stdio transport (#336)
### Changed
- Return tool argument validation failures as tool execution errors (#333)
### Removed
- Remove obsolete `MCP::Transports` module (#331)
## [0.14.0] - 2026-04-24
### Added
- Support pagination per MCP specification (#320)
- Support resource subscriptions per MCP specification (#313)
- Add `roots/list` and `notifications/roots/list_changed` support (#315)
- Support JSON response mode for `StreamableHTTPTransport` (#328)
- Add HTTP client close for explicit session termination (#326)
- Track `Mcp-Session-Id` and protocol version in HTTP client (#325)
- Support `ping` client API per MCP specification (#324)
### Fixed
- Handle 202 Accepted response in HTTP client (#323)
### Changed
- Parse SSE responses in HTTP client via `event_stream_parser` (#322)
## [0.13.0] - 2026-04-16
### Added
- Make `StreamableHTTPTransport` a Rack application (#263)
- Support `elicitation/create` per MCP specification (#312)
- Add `around_request` hook for request instrumentation (#309)
- Add `_meta` field to resource, content, and result classes (#310)
### Removed
- Remove `Server#create_sampling_message` direct call (#311)
## [0.12.0] - 2026-04-11
### Added
- Support customizing the Faraday client in `MCP::Client::HTTP` (#306)
### Changed
- Auto-set `server.transport` in `Transport#initialize` (#305)
### Fixed
- Validate Content-Type on POST requests (#304)
## [0.11.0] - 2026-04-06
### Added
- Support `sampling/createMessage` per MCP specification (#282)
- Support `completion/complete` per MCP specification (#289)
### Fixed
- Support POST response SSE streams for server-to-client messages (#294)
- Return protocol errors for invalid arguments and server errors (#285)
- Fix client methods silently swallowing JSON-RPC error responses (#281)
- Close streams outside mutex in session cleanup (#291)
## [0.10.0] - 2026-03-30
### Added
- Session expiry controls for `StreamableHTTPTransport` via `session_idle_timeout:` option (#268)
### Changed
- `ServerSession` for per-connection state (#275)
### Removed
- Remove `Server#notify_progress` broadcast API (#276)
- Remove undocumented handler override methods (#270)
### Fixed
- Reject POST requests without session ID in stateful mode (#274)
## [0.9.2] - 2026-03-27
### Fixed
- Use accessor method in `server_context_with_meta` instead of ivar (#273)
- Reject duplicate SSE connections with 409 to prevent stream hijacking
## [0.9.1] - 2026-03-23
### Added
- Allow `Client#call_tool` to accept a tool name (#266)
### Fixed
- Return 404 for invalid session ID in `handle_delete` (#261)
## [0.9.0] - 2026-03-20
### Added
- `MCP::Client::Stdio` transport (#262)
- Progress notifications per MCP specification (#254)
- Automatic `_meta` parameter extraction support (#172)
- CORS and Accept wildcard support for browser-based MCP clients (#253)
### Changed
- Use `autoload` to defer loading of unused subsystems (#255)
- Reduce release package size (#239)
### Fixed
- Return 404 for invalid session ID in `handle_regular_request` (#257)
- Use mutex-protected `session_exists?` in `handle_regular_request` (#258)
## [0.8.0] - 2026-03-03
### Added
- `Content::EmbeddedResource` class for embedded resource content type (#244)
- `Content::Audio` class for audio content type (#243)
- `$ref` support in `Tool::Schema` for protocol version 2025-11-25 (#242)
- MCP conformance test suite (#248)
### Fixed
- Handle `Errno::ECONNRESET` in SSE stream operations (#249)
- Fix default handler return values to comply with MCP spec (#247)
- Fix `Prompt#validate_arguments!` crash when arguments are `nil` (#246)
- Return 202 Accepted for SSE responses per MCP spec (#245)
- Fix `Content::Image#to_h` to return `mimeType` (camelCase) per MCP spec (#241)
## [0.7.1] - 2026-02-21
### Fixed
- Fix `Resource::Contents#to_h` to use correct property names per MCP spec (#235)
- Return JSON-RPC protocol errors for unknown tool calls (#231)
- Fix `logging/setLevel` to return empty hash per MCP specification (#230)
## [0.7.0] - 2026-02-14
### Added
- `logging` support (#103)
- Protocol version negotiation to server initialization (#223)
- Tool arguments to instrumentation data (#218)
- Client info to instrumentation callback (#221)
- `resource_templates` to `MCP::Client` (#225)
### Changed
- Extract `MCP::Annotations` into a dedicated file (#224)
### Fixed
- `Resource::Embedded` not setting `@resource` in `initialize` (#220)
## [0.6.0] - 2026-01-16
### Changed
- Update licensing to Apache 2.0 for new contributions (#213)
### Fixed
- Omit `icons` from responses when empty or nil to reduce context window usage (#212)
## [0.5.0] - 2026-01-11
### Added
- Protocol specification version "2025-11-25" support (#184)
- `icons` parameter support (#205)
- `websiteUrl` parameter in `serverInfo` (#188)
- `description` parameter in `serverInfo` (#201)
- `additionalProperties` support for schema validation (#198)
- "Draft" protocol version to supported versions (#179)
- `stateless` mode for high availability (#101)
- Exception messages for tool call errors (#194)
- Elicitation skeleton (#178)
- `prompts/list` and `prompts/get` support to client (#163)
- Accept header validation for HTTP client transport (#207)
- Ruby 2.7 - Ruby 3.1 support (#206)
### Changed
- Make tool names stricter (#204)
### Fixed
- Symlink path comparison in schema validation (#193)
- Duplicate tool names across namespaces now raise an error (#199)
- Tool error handling to follow MCP spec (#165)
- XSS vulnerability in json_rpc_handler (#175)
## [0.4.0] - 2025-10-15
### Added
- Client resources support with `resources/list` and `resources/read` methods (#160)
- `_meta` field support for Tool schema (#124)
- `_meta` field support for Prompt
- `title` field support for prompt arguments
- `call_tool_raw` method to client for accessing full tool responses (#149)
- Structured content support in tool responses (#147)
- AGENTS.md development guidance documentation (#134)
- Dependabot configuration for automated dependency updates (#138)
### Changed
- Set default `content` to empty array instead of `nil` (#150)
- Improved prompt spec compliance (#153)
- Allow output schema to be array of objects (#144)
- Return 202 response code for accepted JSON-RPC notifications (#114)
- Added validation to `MCP::Configuration` setters (#145)
- Updated metaschema URI format for cross-OS compatibility
### Fixed
- Client tools functionality and test coverage (#166)
- Client resources test for empty responses (#162)
- Documentation typos and incorrect examples (#157, #146)
- Removed redundant transport requires (#154)
- Cleaned up unused block parameters and magic comments
## [0.3.0] - 2025-09-14
### Added
@ -54,4 +591,4 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.1.0] - 2025-05-30
Initial release
Initial release in collaboration with Shopify

1
CLAUDE.md Normal file
View file

@ -0,0 +1 @@
@AGENTS.md

16
Gemfile
View file

@ -6,20 +6,26 @@ source "https://rubygems.org"
gemspec
# Specify development dependencies below
gem "rubocop-minitest", require: false
gem "rubocop-minitest", ">= 0.39.0", require: false
gem "rubocop-rake", require: false
gem "rubocop-shopify", require: false
gem "rubocop-shopify", ">= 2.18", require: false if RUBY_VERSION >= "3.1"
gem "puma", ">= 5.0.0"
gem "rack", ">= 2.0.0"
gem "rack-cors"
gem "rackup", ">= 2.1.0"
gem "activesupport"
gem "debug"
# Fix io-console install error when Ruby 3.0.
gem "debug" if RUBY_VERSION >= "3.1"
# Avoid i18n 1.15.0, which breaks on Ruby 3.1 (ruby-i18n/i18n#735).
gem "i18n", "!= 1.15.0"
gem "rake", "~> 13.0"
gem "sorbet-static-and-runtime"
gem "sorbet-static-and-runtime" if RUBY_VERSION >= "3.0"
gem "yard", "~> 0.9"
gem "yard-sorbet", "~> 0.9" if RUBY_VERSION >= "3.1"
group :test do
gem "event_stream_parser", ">= 1.0"
gem "faraday", ">= 2.0"
gem "minitest", "~> 5.1", require: false
gem "mocha"

216
LICENSE Normal file
View file

@ -0,0 +1,216 @@
The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.
Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.
No rights beyond those granted by the applicable original license are conveyed for such contributions.
---
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright
owner or by an individual or Legal Entity authorized to submit on behalf
of the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
---
MIT License
Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Creative Commons Attribution 4.0 International (CC-BY-4.0)
Documentation in this project (excluding specifications) is licensed under
CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for
the full license text.

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2025 TODO: Write your name
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

835
README.md
View file

@ -1,13 +1,22 @@
# MCP Ruby SDK [![Gem Version](https://img.shields.io/gem/v/mcp)](https://rubygems.org/gems/mcp) [![MIT licensed](https://img.shields.io/badge/license-MIT-green)](https://github.com/modelcontextprotocol/ruby-sdk/blob/main/LICENSE.txt) [![CI](https://github.com/modelcontextprotocol/ruby-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/modelcontextprotocol/ruby-sdk/actions/workflows/ci.yml)
# MCP Ruby SDK [![Gem Version](https://img.shields.io/gem/v/mcp)](https://rubygems.org/gems/mcp) [![Apache 2.0 licensed](https://img.shields.io/badge/license-Apache%202.0-blue)](https://github.com/modelcontextprotocol/ruby-sdk/blob/main/LICENSE) [![CI](https://github.com/modelcontextprotocol/ruby-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/modelcontextprotocol/ruby-sdk/actions/workflows/ci.yml)
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](https://ruby.sdk.modelcontextprotocol.io/server/) that expose tools, prompts, and resources to any MCP host
- Build [MCP clients](https://ruby.sdk.modelcontextprotocol.io/client/) 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:
```ruby
gem 'mcp'
gem "mcp"
```
And then execute:
@ -24,161 +33,17 @@ $ gem install mcp
You may need to add additional dependencies depending on which features you wish to access.
## Building an MCP Server
## Quick Start
The `MCP::Server` class is the core component that handles JSON-RPC requests and responses.
It implements the Model Context Protocol specification, handling model context requests and responses.
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.
### Key Features
### MCP Server
- Implements JSON-RPC 2.0 message handling
- Supports protocol initialization and capability negotiation
- Manages tool registration and invocation
- Supports prompt registration and execution
- Supports resource registration and retrieval
- Supports stdio & Streamable HTTP (including SSE) transports
- Supports notifications for list changes (tools, prompts, resources)
### Supported Methods
- `initialize` - Initializes the protocol and returns server capabilities
- `ping` - Simple health check
- `tools/list` - Lists all registered tools and their schemas
- `tools/call` - Invokes a specific tool with provided arguments
- `prompts/list` - Lists all registered prompts and their schemas
- `prompts/get` - Retrieves a specific prompt by name
- `resources/list` - Lists all registered resources and their schemas
- `resources/read` - Retrieves a specific resource by name
- `resources/templates/list` - Lists all registered resource templates and their schemas
### Custom Methods
The server allows you to define custom JSON-RPC methods beyond the standard MCP protocol methods using the `define_custom_method` method:
```ruby
server = MCP::Server.new(name: "my_server")
# Define a custom method that returns a result
server.define_custom_method(method_name: "add") do |params|
params[:a] + params[:b]
end
# Define a custom notification method (returns nil)
server.define_custom_method(method_name: "notify") do |params|
# Process notification
nil
end
```
**Key Features:**
- Accepts any method name as a string
- Block receives the request parameters as a hash
- Can handle both regular methods (with responses) and notifications
- Prevents overriding existing MCP protocol methods
- Supports instrumentation callbacks for monitoring
**Usage Example:**
```ruby
# Client request
{
"jsonrpc": "2.0",
"id": 1,
"method": "add",
"params": { "a": 5, "b": 3 }
}
# Server response
{
"jsonrpc": "2.0",
"id": 1,
"result": 8
}
```
**Error Handling:**
- Raises `MCP::Server::MethodAlreadyDefinedError` if trying to override an existing method
- Supports the same exception reporting and instrumentation as standard methods
### Notifications
The server supports sending notifications to clients when lists of tools, prompts, or resources change. This enables real-time updates without polling.
#### Notification Methods
The server provides three notification methods:
- `notify_tools_list_changed` - Send a notification when the tools list changes
- `notify_prompts_list_changed` - Send a notification when the prompts list changes
- `notify_resources_list_changed` - Send a notification when the resources list changes
#### Notification Format
Notifications follow the JSON-RPC 2.0 specification and use these method names:
- `notifications/tools/list_changed`
- `notifications/prompts/list_changed`
- `notifications/resources/list_changed`
#### Transport Support
- **stdio**: Notifications are sent as JSON-RPC 2.0 messages to stdout
- **Streamable HTTP**: Notifications are sent as JSON-RPC 2.0 messages over HTTP with streaming (chunked transfer or SSE)
#### Usage Example
```ruby
server = MCP::Server.new(name: "my_server")
transport = MCP::Transports::HTTP.new(server)
server.transport = transport
# When tools change, notify clients
server.define_tool(name: "new_tool") { |**args| { result: "ok" } }
server.notify_tools_list_changed
```
### Unsupported Features ( to be implemented in future versions )
- Log Level
- Resource subscriptions
- Completions
### Usage
#### Rails Controller
When added to a Rails controller on a route that handles POST requests, your server will be compliant with non-streaming
[Streamable HTTP](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http) transport
requests.
You can use the `Server#handle_json` method to handle requests.
```ruby
class ApplicationController < ActionController::Base
def index
server = MCP::Server.new(
name: "my_server",
title: "Example Server Display Name", # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
version: "1.0.0",
instructions: "Use the tools of this server as a last resort",
tools: [SomeTool, AnotherTool],
prompts: [MyPrompt],
server_context: { user_id: current_user.id },
)
render(json: server.handle_json(request.body.read))
end
end
```
#### Stdio Transport
If you want to build a local command-line application, you can use the stdio transport:
A minimal server defines a tool and serves it over the stdio transport:
```ruby
require "mcp"
require "mcp/server/transports/stdio_transport"
# Create a simple tool
class ExampleTool < MCP::Tool
@ -211,668 +76,64 @@ transport = MCP::Server::Transports::StdioTransport.new(server)
transport.open
```
You can run this script and then type in requests to the server at the command line.
Save the script as `server.rb`, run it, and send JSON-RPC requests via stdin:
```console
$ ruby examples/stdio_server.rb
$ 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"}}}
```
### Configuration
The same server can also run over Streamable HTTP, including mounted inside a Rails application;
see [Server Transports](https://ruby.sdk.modelcontextprotocol.io/server/transports/).
The gem can be configured using the `MCP.configure` block:
### MCP Client
A minimal client spawns a stdio server as a subprocess, connects, and lists and calls its tools:
```ruby
MCP.configure do |config|
config.exception_reporter = ->(exception, server_context) {
# Your exception reporting logic here
# For example with Bugsnag:
Bugsnag.notify(exception) do |report|
report.add_metadata(:model_context_protocol, server_context)
end
}
config.instrumentation_callback = ->(data) {
puts "Got instrumentation data #{data.inspect}"
}
end
```
or by creating an explicit configuration and passing it into the server.
This is useful for systems where an application hosts more than one MCP server but
they might require different instrumentation callbacks.
```ruby
configuration = MCP::Configuration.new
configuration.exception_reporter = ->(exception, server_context) {
# Your exception reporting logic here
# For example with Bugsnag:
Bugsnag.notify(exception) do |report|
report.add_metadata(:model_context_protocol, server_context)
end
}
configuration.instrumentation_callback = ->(data) {
puts "Got instrumentation data #{data.inspect}"
}
server = MCP::Server.new(
# ... all other options
configuration:,
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)
### Server Context and Configuration Block Data
# Perform the MCP initialization handshake before sending any requests.
client.connect
#### `server_context`
The `server_context` is a user-defined hash that is passed into the server instance and made available to tools, prompts, and exception/instrumentation callbacks. It can be used to provide contextual information such as authentication state, user IDs, or request-specific data.
**Type:**
```ruby
server_context: { [String, Symbol] => Any }
```
**Example:**
```ruby
server = MCP::Server.new(
name: "my_server",
server_context: { user_id: current_user.id, request_id: request.uuid }
)
```
This hash is then passed as the `server_context` argument to tool and prompt calls, and is included in exception and instrumentation callbacks.
#### Configuration Block Data
##### Exception Reporter
The exception reporter receives:
- `exception`: The Ruby exception object that was raised
- `server_context`: The context hash provided to the server
**Signature:**
```ruby
exception_reporter = ->(exception, server_context) { ... }
```
##### Instrumentation Callback
The instrumentation callback receives a hash with the following possible keys:
- `method`: (String) The protocol method called (e.g., "ping", "tools/list")
- `tool_name`: (String, optional) The name of the tool called
- `prompt_name`: (String, optional) The name of the prompt called
- `resource_uri`: (String, optional) The URI of the resource called
- `error`: (String, optional) Error code if a lookup failed
- `duration`: (Float) Duration of the call in seconds
**Type:**
```ruby
instrumentation_callback = ->(data) { ... }
# where data is a Hash with keys as described above
```
**Example:**
```ruby
config.instrumentation_callback = ->(data) {
puts "Instrumentation: #{data.inspect}"
}
```
### Server Protocol Version
The server's protocol version can be overridden using the `protocol_version` keyword argument:
```ruby
configuration = MCP::Configuration.new(protocol_version: "2024-11-05")
MCP::Server.new(name: "test_server", configuration: configuration)
```
This will make all new server instances use the specified protocol version instead of the default version. The protocol version can be reset to the default by setting it to `nil`:
```ruby
MCP::Configuration.new(protocol_version: nil)
```
If an invalid `protocol_version` value is set, an `ArgumentError` is raised.
Be sure to check the [MCP spec](https://modelcontextprotocol.io/specification/versioning) for the protocol version to understand the supported features for the version being set.
### Exception Reporting
The exception reporter receives two arguments:
- `exception`: The Ruby exception object that was raised
- `server_context`: A hash containing contextual information about where the error occurred
The server_context hash includes:
- For tool calls: `{ tool_name: "name", arguments: { ... } }`
- For general request handling: `{ request: { ... } }`
When an exception occurs:
1. The exception is reported via the configured reporter
2. For tool calls, a generic error response is returned to the client: `{ error: "Internal error occurred", isError: true }`
3. For other requests, the exception is re-raised after reporting
If no exception reporter is configured, a default no-op reporter is used that silently ignores exceptions.
### Tools
MCP spec includes [Tools](https://modelcontextprotocol.io/specification/2025-06-18/server/tools) which provide functionality to LLM apps.
This gem provides a `MCP::Tool` class that can be used to create tools in three ways:
1. As a class definition:
```ruby
class MyTool < MCP::Tool
title "My Tool" # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
description "This tool performs specific functionality..."
input_schema(
properties: {
message: { type: "string" },
},
required: ["message"]
)
output_schema(
properties: {
result: { type: "string" },
success: { type: "boolean" },
timestamp: { type: "string", format: "date-time" }
},
required: ["result", "success", "timestamp"]
)
annotations(
read_only_hint: true,
destructive_hint: false,
idempotent_hint: true,
open_world_hint: false,
title: "My Tool"
)
def self.call(message:, server_context:)
MCP::Tool::Response.new([{ type: "text", text: "OK" }])
end
end
tool = MyTool
```
2. By using the `MCP::Tool.define` method with a block:
```ruby
tool = MCP::Tool.define(
name: "my_tool",
title: "My Tool", # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
description: "This tool performs specific functionality...",
annotations: {
read_only_hint: true,
title: "My Tool"
}
) do |args, server_context|
MCP::Tool::Response.new([{ type: "text", text: "OK" }])
end
```
3. By using the `ModelContextProtocol::Server#define_tool` method with a block:
```ruby
server = ModelContextProtocol::Server.new
server.define_tool(
name: "my_tool",
description: "This tool performs specific functionality...",
annotations: {
title: "My Tool",
read_only_hint: true
}
) do |args, server_context|
Tool::Response.new([{ type: "text", text: "OK" }])
end
```
The server_context parameter is the server_context passed into the server and can be used to pass per request information,
e.g. around authentication state.
### Tool Annotations
Tools can include annotations that provide additional metadata about their behavior. The following annotations are supported:
- `destructive_hint`: Indicates if the tool performs destructive operations. Defaults to true
- `idempotent_hint`: Indicates if the tool's operations are idempotent. Defaults to false
- `open_world_hint`: Indicates if the tool operates in an open world context. Defaults to true
- `read_only_hint`: Indicates if the tool only reads data (doesn't modify state). Defaults to false
- `title`: A human-readable title for the tool
Annotations can be set either through the class definition using the `annotations` class method or when defining a tool using the `define` method.
> [!NOTE]
> This **Tool Annotations** feature is supported starting from `protocol_version: '2025-03-26'`.
### Tool Output Schemas
Tools can optionally define an `output_schema` to specify the expected structure of their results. This works similarly to how `input_schema` is defined and can be used in three ways:
1. **Class definition with output_schema:**
```ruby
class WeatherTool < MCP::Tool
tool_name "get_weather"
description "Get current weather for a location"
input_schema(
properties: {
location: { type: "string" },
units: { type: "string", enum: ["celsius", "fahrenheit"] }
},
required: ["location"]
)
output_schema(
properties: {
temperature: { type: "number" },
condition: { type: "string" },
humidity: { type: "integer" }
},
required: ["temperature", "condition", "humidity"]
)
def self.call(location:, units: "celsius", server_context:)
# Call weather API and structure the response
api_response = WeatherAPI.fetch(location, units)
weather_data = {
temperature: api_response.temp,
condition: api_response.description,
humidity: api_response.humidity_percent
}
output_schema.validate_result(weather_data)
MCP::Tool::Response.new([{
type: "text",
text: weather_data.to_json
}])
end
end
```
2. **Using Tool.define with output_schema:**
```ruby
tool = MCP::Tool.define(
name: "calculate_stats",
description: "Calculate statistics for a dataset",
input_schema: {
properties: {
numbers: { type: "array", items: { type: "number" } }
},
required: ["numbers"]
},
output_schema: {
properties: {
mean: { type: "number" },
median: { type: "number" },
count: { type: "integer" }
},
required: ["mean", "median", "count"]
}
) do |args, server_context|
# Calculate statistics and validate against schema
MCP::Tool::Response.new([{ type: "text", text: "Statistics calculated" }])
end
```
3. **Using OutputSchema objects:**
```ruby
class DataTool < MCP::Tool
output_schema MCP::Tool::OutputSchema.new(
properties: {
success: { type: "boolean" },
data: { type: "object" }
},
required: ["success"]
)
end
```
MCP spec for the [Output Schema](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#output-schema) specifies that:
- **Server Validation**: Servers MUST provide structured results that conform to the output schema
- **Client Validation**: Clients SHOULD validate structured results against the output schema
- **Better Integration**: Enables strict schema validation, type information, and improved developer experience
- **Backward Compatibility**: Tools returning structured content SHOULD also include serialized JSON in a TextContent block
The output schema follows standard JSON Schema format and helps ensure consistent data exchange between MCP servers and clients.
### Prompts
MCP spec includes [Prompts](https://modelcontextprotocol.io/specification/2025-06-18/server/prompts), which enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs.
The `MCP::Prompt` class provides three ways to create prompts:
1. As a class definition with metadata:
```ruby
class MyPrompt < MCP::Prompt
prompt_name "my_prompt" # Optional - defaults to underscored class name
title "My Prompt" # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
description "This prompt performs specific functionality..."
arguments [
MCP::Prompt::Argument.new(
name: "message",
description: "Input message",
required: true
)
]
class << self
def template(args, server_context:)
MCP::Prompt::Result.new(
description: "Response description",
messages: [
MCP::Prompt::Message.new(
role: "user",
content: MCP::Content::Text.new("User message")
),
MCP::Prompt::Message.new(
role: "assistant",
content: MCP::Content::Text.new(args["message"])
)
]
)
end
end
end
prompt = MyPrompt
```
2. Using the `MCP::Prompt.define` method:
```ruby
prompt = MCP::Prompt.define(
name: "my_prompt",
title: "My Prompt", # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
description: "This prompt performs specific functionality...",
arguments: [
MCP::Prompt::Argument.new(
name: "message",
description: "Input message",
required: true
)
]
) do |args, server_context:|
MCP::Prompt::Result.new(
description: "Response description",
messages: [
MCP::Prompt::Message.new(
role: "user",
content: MCP::Content::Text.new("User message")
),
MCP::Prompt::Message.new(
role: "assistant",
content: MCP::Content::Text.new(args["message"])
)
]
)
end
```
3. Using the `ModelContextProtocol::Server#define_protocol` method:
```ruby
server = ModelContextProtocol::Server.new
server.define_protocol(
name: "my_prompt",
description: "This prompt performs specific functionality...",
arguments: [
Prompt::Argument.new(
name: "message",
description: "Input message",
required: true
)
]
) do |args, server_context:|
Prompt::Result.new(
description: "Response description",
messages: [
Prompt::Message.new(
role: "user",
content: Content::Text.new("User message")
),
Prompt::Message.new(
role: "assistant",
content: Content::Text.new(args["message"])
)
]
)
end
```
The server_context parameter is the server_context passed into the server and can be used to pass per request information,
e.g. around authentication state or user preferences.
### Key Components
- `MCP::Prompt::Argument` - Defines input parameters for the prompt template
- `MCP::Prompt::Message` - Represents a message in the conversation with a role and content
- `MCP::Prompt::Result` - The output of a prompt template containing description and messages
- `MCP::Content::Text` - Text content for messages
### Usage
Register prompts with the MCP server:
```ruby
server = MCP::Server.new(
name: "my_server",
prompts: [MyPrompt],
server_context: { user_id: current_user.id },
)
```
The server will handle prompt listing and execution through the MCP protocol methods:
- `prompts/list` - Lists all registered prompts and their schemas
- `prompts/get` - Retrieves and executes a specific prompt with arguments
### Instrumentation
The server allows registering a callback to receive information about instrumentation.
To register a handler pass a proc/lambda to as `instrumentation_callback` into the server constructor.
```ruby
MCP.configure do |config|
config.instrumentation_callback = ->(data) {
puts "Got instrumentation data #{data.inspect}"
}
end
```
The data contains the following keys:
- `method`: the method called, e.g. `ping`, `tools/list`, `tools/call` etc
- `tool_name`: the name of the tool called
- `prompt_name`: the name of the prompt called
- `resource_uri`: the uri of the resource called
- `error`: if looking up tools/prompts etc failed, e.g. `tool_not_found`
- `duration`: the duration of the call in seconds
`tool_name`, `prompt_name` and `resource_uri` are only populated if a matching handler is registered.
This is to avoid potential issues with metric cardinality
### Resources
MCP spec includes [Resources](https://modelcontextprotocol.io/specification/2025-06-18/server/resources).
### Reading Resources
The `MCP::Resource` class provides a way to register resources with the server.
```ruby
resource = MCP::Resource.new(
uri: "https://example.com/my_resource",
name: "my-resource",
title: "My Resource", # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
description: "Lorem ipsum dolor sit amet",
mime_type: "text/html",
)
server = MCP::Server.new(
name: "my_server",
resources: [resource],
)
```
The server must register a handler for the `resources/read` method to retrieve a resource dynamically.
```ruby
server.resources_read_handler do |params|
[{
uri: params[:uri],
mimeType: "text/plain",
text: "Hello from example resource! URI: #{params[:uri]}"
}]
end
```
otherwise `resources/read` requests will be a no-op.
### Resource Templates
The `MCP::ResourceTemplate` class provides a way to register resource templates with the server.
```ruby
resource_template = MCP::ResourceTemplate.new(
uri_template: "https://example.com/my_resource_template",
name: "my-resource-template",
title: "My Resource Template", # WARNING: This is a `Draft` and is not supported in the `Version 2025-06-18 (latest)` specification.
description: "Lorem ipsum dolor sit amet",
mime_type: "text/html",
)
server = MCP::Server.new(
name: "my_server",
resource_templates: [resource_template],
)
```
## Building an MCP Client
The `MCP::Client` class provides an interface for interacting with MCP servers.
This class supports:
- Tool listing via the `tools/list` method
- Tool invocation via the `tools/call` method
- Automatic JSON-RPC 2.0 message formatting
- UUID request ID generation
Clients are initialized with a transport layer instance that handles the low-level communication mechanics.
Authorization is handled by the transport layer.
## Transport Layer Interface
If the transport layer you need is not included in the gem, you can build and pass your own instances so long as they conform to the following interface:
```ruby
class CustomTransport
# Sends a JSON-RPC request to the server and returns the raw response.
#
# @param request [Hash] A complete JSON-RPC request object.
# https://www.jsonrpc.org/specification#request_object
# @return [Hash] A hash modeling a JSON-RPC response object.
# https://www.jsonrpc.org/specification#response_object
def send_request(request:)
# Your transport-specific logic here
# - HTTP: POST to endpoint with JSON body
# - WebSocket: Send message over WebSocket
# - stdio: Write to stdout, read from stdin
# - etc.
end
end
```
### HTTP Transport Layer
Use the `MCP::Client::HTTP` transport to interact with MCP servers using simple HTTP requests.
You'll need to add `faraday` as a dependency in order to use the HTTP transport layer:
```ruby
gem 'mcp'
gem 'faraday', '>= 2.0'
```
Example usage:
```ruby
http_transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp")
client = MCP::Client.new(transport: http_transport)
# List available tools
# List available tools.
tools = client.tools
tools.each do |tool|
puts <<~TOOL_INFORMATION
Tool: #{tool.name}
Description: #{tool.description}
Input Schema: #{tool.input_schema}
TOOL_INFORMATION
puts "Tool: #{tool.name} - #{tool.description}"
end
# Call a specific tool
# Call a specific tool.
response = client.call_tool(
tool: tools.first,
arguments: { message: "Hello, world!" }
)
# Close the transport when done.
stdio_transport.close
```
#### HTTP Authorization
The same client can connect to Streamable HTTP servers with `MCP::Client::HTTP`;
see [Client Transports](https://ruby.sdk.modelcontextprotocol.io/client/transports/).
By default, the HTTP transport layer provides no authentication to the server, but you can provide custom headers if you need authentication. For example, to use Bearer token authentication:
## Examples
```ruby
http_transport = MCP::Client::HTTP.new(
url: "https://api.example.com/mcp",
headers: {
"Authorization" => "Bearer my_token"
}
)
Runnable examples are available in [`examples/`](https://github.com/modelcontextprotocol/ruby-sdk/tree/main/examples),
including a complete Rails application in [`examples/rails`](https://github.com/modelcontextprotocol/ruby-sdk/tree/main/examples/rails).
client = MCP::Client.new(transport: http_transport)
client.tools # will make the call using Bearer auth
```
## Documentation
You can add any custom headers needed for your authentication scheme, or for any other purpose. The client will include these headers on every request.
- [SDK guides](https://ruby.sdk.modelcontextprotocol.io)
- [SDK API documentation](https://rubydoc.info/gems/mcp)
- [Model Context Protocol documentation](https://modelcontextprotocol.io)
### Tool Objects
## License
The client provides a wrapper class for tools returned by the server:
- `MCP::Client::Tool` - Represents a single tool with its metadata
This class provides easy access to tool properties like name, description, input schema, and output schema.
## Releases
This gem is published to [RubyGems.org](https://rubygems.org/gems/mcp)
Releases are triggered by PRs to the `main` branch updating the version number in `lib/mcp/version.rb`.
1. **Update the version number** in `lib/mcp/version.rb`, following [semver](https://semver.org/)
1. **Update CHANGELOG.md**, backfilling the changes since the last release if necessary, and adding a new section for the new version, clearing out the Unreleased section
1. **Create a PR and get approval from a maintainer**
1. **Merge your PR to the main branch** - This will automatically trigger the release workflow via GitHub Actions
When changes are merged to the `main` branch, the GitHub Actions workflow (`.github/workflows/release.yml`) is triggered and the gem is published to RubyGems.
This project is licensed under the Apache License 2.0 for new contributions, with existing code under MIT. See the [LICENSE](https://github.com/modelcontextprotocol/ruby-sdk/blob/main/LICENSE) file for details.

12
RELEASE.md Normal file
View file

@ -0,0 +1,12 @@
## Releases
This gem is published to [RubyGems.org](https://rubygems.org/gems/mcp)
Releases are triggered by PRs to the `main` branch updating the version number in `lib/mcp/version.rb`.
1. **Update the version number** in `lib/mcp/version.rb`, following [semver](https://semver.org/)
2. **Update CHANGELOG.md**, backfilling the changes since the last release if necessary, and adding a new section for the new version, clearing out the Unreleased section
3. **Create a PR and get approval from a maintainer**
4. **Merge your PR to the main branch** - This will automatically trigger the release workflow via GitHub Actions
When changes are merged to the `main` branch, the GitHub Actions workflow (`.github/workflows/release.yml`) is triggered and the gem is published to RubyGems.

51
ROADMAP.md Normal file
View file

@ -0,0 +1,51 @@
# Roadmap
This roadmap outlines the MCP Ruby SDK's path toward SEP-1730 Tier 1.
It is a living document and will evolve as the SDK matures.
## Current Status
The SDK implements the 2025-06-18, 2025-11-25, and 2026-07-28 spec revisions, and passes all scored server
and client conformance scenarios for each revision's requirement set.
Optional protocol extensions (such as DPoP, workload identity federation, and the tasks extension)
are not yet implemented; SEP-1730 does not require extensions for any tier.
## API Stability
The 1.0.0 release marked the public API as stable: breaking changes ship only in major releases,
apart from the narrow exceptions documented in [VERSIONING.md](VERSIONING.md),
which also defines the Semantic Versioning scheme and breaking-change policy.
## Deprecated Features
The 2026-07-28 spec revision deprecates Roots, Sampling, and Logging (SEP-2577).
These features remain supported throughout 1.x: on the legacy lifecycle they work unchanged
(the deprecations do not apply there), and the 2026-07-28 lifecycle carries them through its own mechanisms:
roots-shaped and sampling-shaped input requests embedded in `InputRequiredResult` responses
(the SEP-2322 multi round-trip requests pattern) and per-request log delivery through the envelope's `logLevel`.
The replacements SEP-2577 names live outside the protocol: tool parameters or configuration for roots,
direct LLM provider APIs for sampling, and stderr or OpenTelemetry for logging.
The client emits a deprecation warning when a modern connect declares the deprecated Roots or Sampling capabilities.
Under Semantic Versioning their removal requires a major release, but no removal is scheduled yet: whether 2.0.0 removes
them depends on how future MCP spec revisions treat these features and on adoption of their replacements.
## Conformance
The SDK maintains a 100% conformance pass rate as new scenarios are added to the conformance suite.
Legacy SSE transport (2024-11-05) is intentionally out of scope; the SDK provides modern Streamable HTTP only.
## Documentation
Reference documentation covers all non-experimental features with examples.
## Tracking New Spec Revisions
The SDK aims to support each new MCP specification revision, with the implementation timeline agreed per
release based on feature complexity.
The 2026-07-28 revision shipped during 1.x: the server serves both lifecycle eras side by side,
so the SEP-2575 stateless lifecycle (including `server/discover` and `subscriptions/listen`),
SEP-2322 multi round-trip requests, SEP-2549 cache hints, and SEP-2243 custom headers are available alongside
the legacy handshake. The few incompatible adjustments the revision required shipped in
a minor release under the spec-conformance and security exceptions described in [VERSIONING.md](VERSIONING.md).
Removing legacy-era support is reserved for a future major release.
The tasks extension (SEP-2663) remains planned ([#391](https://github.com/modelcontextprotocol/ruby-sdk/issues/391)).

View file

@ -14,4 +14,90 @@ require "rubocop/rake_task"
RuboCop::RakeTask.new
task default: [:test, :rubocop]
task default: [:rubocop, :test, "conformance:test"]
namespace :conformance do
desc "Run MCP conformance tests (PORT, SCENARIO, SPEC_VERSION, VERBOSE)"
task :test do |t|
next unless npx_available?(t.name)
require_relative "conformance/server_runner"
require_relative "conformance/client_runner"
options = {}
options[:port] = Integer(ENV["PORT"]) if ENV["PORT"]
options[:scenario] = ENV["SCENARIO"] if ENV["SCENARIO"]
options[:spec_version] = ENV["SPEC_VERSION"] if ENV["SPEC_VERSION"]
options[:verbose] = true if ENV["VERBOSE"]
Conformance::ServerRunner.new(**options).run
Conformance::ClientRunner.new(**options.reject { |key, _value| key == :port }).run
end
desc "List available conformance scenarios"
task :list do |t|
next unless npx_available?(t.name)
system("npx", "--yes", "@modelcontextprotocol/conformance", "list", "--server")
system("npx", "--yes", "@modelcontextprotocol/conformance", "list", "--client")
end
desc "Start the conformance server (PORT)"
task :server do
require_relative "conformance/server"
options = {}
options[:port] = Integer(ENV["PORT"]) if ENV["PORT"]
Conformance::Server.new(**options).start
end
end
# The other two former names now fail with a "Did you mean?" suggestion, but a bare `conformance`
# would match the `conformance/` directory: Rake synthesizes a file task for it and exits 0 without
# running anything. This keeps the name pointing at the suite instead of at that silent no-op.
desc "Alias for conformance:test"
task conformance: "conformance:test"
namespace :docs do
desc "Serve the documentation site locally at http://localhost:4000 (PORT)"
task :preview do
docs_dir = File.expand_path("docs", __dir__)
generate_docs_versions_data(docs_dir)
env = {
"BUNDLE_GEMFILE" => File.join(docs_dir, "Gemfile"),
"RUBYOPT" => "-r#{File.join(docs_dir, "_preview", "taint_shim.rb")}",
}
port = ENV.fetch("PORT", "4000")
Bundler.with_unbundled_env do
system(env, "bundle", "install", "--quiet", chdir: docs_dir, exception: true)
system(env, "bundle", "exec", "jekyll", "serve", "--port", port, chdir: docs_dir, exception: true)
rescue Interrupt
# Ctrl-C is the way to stop the preview, not an error.
end
end
end
# Mirrors bin/generate-gh-pages.sh: the released site receives `_data/versions.yml` from
# the version tags at deploy time, and the preview generates the same data so the nav footer
# shows the released-gem version line.
def generate_docs_versions_data(docs_dir)
versions = %x(git tag --list).split("\n").filter_map { |tag|
tag[/\A[^0-9]*(\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?)\z/, 1]
}.sort_by { |version|
Gem::Version.new(version)
}.reverse
return if versions.empty?
mkdir_p(File.join(docs_dir, "_data"))
File.write(File.join(docs_dir, "_data", "versions.yml"), versions.map { |version| "- #{version}\n" }.join)
end
def npx_available?(task_name)
return true if system("which", "npx", out: File::NULL, err: File::NULL)
warn("Skipping #{task_name}: npx is not installed. Install Node.js to run this task: https://nodejs.org/")
false
end

21
SECURITY.md Normal file
View file

@ -0,0 +1,21 @@
# Security Policy
Thank you for helping keep the Model Context Protocol and its ecosystem secure.
## Reporting Security Issues
If you discover a security vulnerability in this repository, please report it through
the [GitHub Security Advisory process](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability)
for this repository.
Please **do not** report security vulnerabilities through public GitHub issues, discussions,
or pull requests.
## What to Include
To help us triage and respond quickly, please include:
- A description of the vulnerability
- Steps to reproduce the issue
- The potential impact
- Any suggested fixes (optional)

56
VERSIONING.md Normal file
View file

@ -0,0 +1,56 @@
# Versioning Policy
The MCP Ruby SDK follows [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html).
This document describes what each version component means for users of the `mcp` gem,
what counts as a breaking change, and how breaking changes are communicated.
## Version Scheme
Given a version number `MAJOR.MINOR.PATCH`:
- **MAJOR** is incremented for incompatible changes to the public API.
- **MINOR** is incremented for backwards-compatible new functionality.
- **PATCH** is incremented for backwards-compatible bug fixes.
### Current 0.x Phase
While the SDK is at version 0.x, the public API is not yet considered stable.
Following SemVer conventions for initial development, minor releases (0.x -> 0.y) may contain breaking changes.
All breaking changes are recorded in [CHANGELOG.md](CHANGELOG.md).
### After 1.0.0
Once 1.0.0 is released, breaking changes will only ship in major releases, with the exceptions described below.
## What Counts as a Breaking Change
A breaking change is any change that requires users to modify their code when upgrading, including:
- Removing or renaming a public class, module, method, or constant
- Changing a public method's signature in a way that rejects previously valid arguments
- Changing documented behavior that users can reasonably depend on
New functionality that is purely additive (new classes, new methods, new optional keyword arguments)
is not a breaking change.
## Exceptions: Spec Compliance, Security, and Clear Defects
Minor releases avoid incompatible changes as much as possible. However, the SDK's primary contract is
conformance to the [MCP specification](https://modelcontextprotocol.io/specification/).
Behavior that deviates from the specification is treated as a bug, even when users may have come to rely on it.
Therefore, incompatible changes may be shipped in a minor release when they are required to:
- Fix incorrect conformance to the MCP specification
- Address a security vulnerability
- Fix a clear defect, such as behavior that contradicts the documentation, a crash,
or data corruption, where compatibility would mean preserving the defect
When such a change ships, the release notes and CHANGELOG entry explicitly call out the incompatibility
and describe how to migrate.
## How Breaking Changes Are Communicated
- [CHANGELOG.md](CHANGELOG.md) records every release in [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format;
breaking changes appear under the "Changed" or "Removed" headings
- [GitHub Releases](https://github.com/modelcontextprotocol/ruby-sdk/releases) mirror the changelog for each release
- Where practical, deprecation warnings are added at least one minor release before removal

119
bin/generate-gh-pages.sh Executable file
View file

@ -0,0 +1,119 @@
#!/bin/bash
set -e
# Generates versioned documentation links and commits to gh-pages branch
#
# PURPOSE:
# This script generates a landing page with links to API documentation on
# RubyDoc.info for a specific version tag. This script is invoked by the
# publish-gh-pages job in the GitHub Actions workflow
# (.github/workflows/release.yml) when a release is published.
#
# HOW IT WORKS:
# - Creates isolated git worktrees for the specified tag and gh-pages branch
# - Copies static Jekyll template files from docs/
# - Generates _data/versions.yml with list of versions
# - Commits changes to gh-pages (does not push automatically)
#
# WORKFLOW:
# 1. Run this script with a tag name: `generate-gh-pages.sh v1.2.3`
# 2. Script generates docs and commits to local gh-pages branch
# 3. Push gh-pages branch to deploy: `git push origin gh-pages`
# Parse semantic version from tag name (ignoring arbitrary prefixes)
if [[ "${1}" =~ ([0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?)$ ]]; then
VERSION="v${BASH_REMATCH[1]}"
else
echo "Error: Must specify a tag name that contains a valid semantic version"
echo "Usage: ${0} <tag-name>"
echo "Examples:"
echo " ${0} 1.2.3"
echo " ${0} v2.0.0-rc.1"
exit 1
fi
TAG_NAME="${1}"
REPO_ROOT="$(git rev-parse --show-toplevel)"
echo "Generating documentation for tag: ${TAG_NAME}"
# Create temporary directories for both worktrees
WORKTREE_DIR=$(mktemp -d)
GHPAGES_WORKTREE_DIR=$(mktemp -d)
# Set up trap to clean up both worktrees on exit
trap 'git worktree remove --force "${WORKTREE_DIR}" 2>/dev/null || true; \
git worktree remove --force "${GHPAGES_WORKTREE_DIR}" 2>/dev/null || true' EXIT
echo "Creating worktree for ${TAG_NAME}..."
git worktree add --quiet "${WORKTREE_DIR}" "${TAG_NAME}"
# Check if gh-pages branch exists
if git show-ref --verify --quiet refs/heads/gh-pages; then
echo "Creating worktree for existing gh-pages branch..."
git worktree add --quiet "${GHPAGES_WORKTREE_DIR}" gh-pages
elif git ls-remote --exit-code --heads origin gh-pages > /dev/null 2>&1; then
echo "Creating worktree for gh-pages branch from remote..."
git worktree add --quiet "${GHPAGES_WORKTREE_DIR}" -b gh-pages origin/gh-pages
else
echo "Creating worktree for new orphan gh-pages branch..."
git worktree add --quiet --detach "${GHPAGES_WORKTREE_DIR}"
git -C "${GHPAGES_WORKTREE_DIR}" checkout --orphan gh-pages
git -C "${GHPAGES_WORKTREE_DIR}" rm -rf . > /dev/null 2>&1 || true
fi
# Change to gh-pages worktree
cd "${GHPAGES_WORKTREE_DIR}"
# Determine if this tag is the latest version
echo "Determining if ${VERSION} is the latest version..."
# Get all existing version tags from the repository (reverse sorted, newest first)
ALL_VERSIONS=$(
git -C "${REPO_ROOT}" tag --list | \
sed -nE 's/^[^0-9]*([0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?)$/v\1/p' | \
sort -Vr
)
# Get the latest version from all version tags
LATEST_VERSION=$(echo "${ALL_VERSIONS}" | head -n 1)
if [ "${VERSION}" = "${LATEST_VERSION}" ]; then
echo "${VERSION} is the latest version"
else
echo "${VERSION} is not the latest version (latest is ${LATEST_VERSION})"
fi
# Update custom documentation for latest version
if [ "${VERSION}" = "${LATEST_VERSION}" ]; then
echo "Updating custom documentation..."
# Clean up old custom docs from gh-pages root
echo "Cleaning gh-pages root..."
git ls-tree --name-only HEAD | xargs -r git rm -rf
# Copy custom docs from docs/ directory
echo "Copying custom docs from ${WORKTREE_DIR}/docs/..."
cp -r "${WORKTREE_DIR}/docs/." "${GHPAGES_WORKTREE_DIR}/"
fi
# Generate version data for Jekyll
echo "Generating _data/versions.yml..."
mkdir -p _data
echo "${ALL_VERSIONS}" | sed 's/^v/- /' > _data/versions.yml
# Stage all changes
git add .
# Commit if there are changes
if git diff --staged --quiet; then
echo "No changes to commit"
else
echo "Committing documentation for ${VERSION}..."
git commit -m "Add ${VERSION} docs"
echo "Documentation committed to gh-pages branch!"
echo "Push to remote to deploy to GitHub Pages"
fi
echo "Done!"

Some files were not shown because too many files have changed in this diff Show more