Commit graph ruby-sdk/test
Author SHA1 Message Date
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
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
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
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
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
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
Eric Kreutzer
50cd86c01c
Add automatic _meta parameter extraction support 2026-03-04 10:11:07 -07: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
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
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
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
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
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
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
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
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
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
c145fe39df Add resource_templates to MCP::Client
Includes relevant README addition and tests
2026-02-05 16:02:07 -05: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
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
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
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
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
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
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