mcp 1.8.2 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +5 -0
- data/lib/json_rpc_handler.rb +1 -1
- data/lib/mcp/client/http.rb +29 -5
- data/lib/mcp/client/oauth/client_credentials_provider.rb +16 -0
- data/lib/mcp/client/oauth/cross_app_access_provider.rb +19 -2
- data/lib/mcp/client/oauth/flow.rb +11 -3
- data/lib/mcp/client/oauth/jwt_client_assertion.rb +3 -2
- data/lib/mcp/client/oauth/pkce.rb +3 -2
- data/lib/mcp/client/skill_errors.rb +45 -0
- data/lib/mcp/client/skills.rb +430 -0
- data/lib/mcp/client/stdio.rb +15 -3
- data/lib/mcp/client/tool.rb +8 -2
- data/lib/mcp/client.rb +40 -3
- data/lib/mcp/instrumentation.rb +12 -7
- data/lib/mcp/mcp_param_headers.rb +332 -0
- data/lib/mcp/methods.rb +5 -0
- data/lib/mcp/server/oauth/jwt_verifier.rb +34 -5
- data/lib/mcp/server/transports/stdio_transport.rb +12 -0
- data/lib/mcp/server/transports/streamable_http_transport.rb +193 -31
- data/lib/mcp/server.rb +431 -51
- data/lib/mcp/server_session.rb +23 -1
- data/lib/mcp/skill/directory.rb +316 -0
- data/lib/mcp/skill/frontmatter.rb +262 -0
- data/lib/mcp/skill/resource_entry.rb +109 -0
- data/lib/mcp/skill.rb +522 -0
- data/lib/mcp/tool/output_schema.rb +4 -3
- data/lib/mcp/version.rb +1 -1
- data/lib/mcp.rb +3 -0
- metadata +9 -3
- data/lib/mcp/client/mcp_param_headers.rb +0 -242
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
require "json"
|
|
4
4
|
require "set"
|
|
5
|
+
require "timeout"
|
|
5
6
|
require_relative "../../result_type"
|
|
6
7
|
require_relative "../../transport"
|
|
7
8
|
|
|
@@ -188,6 +189,13 @@ module MCP
|
|
|
188
189
|
# @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its
|
|
189
190
|
# response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`.
|
|
190
191
|
# Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`.
|
|
192
|
+
# @param stream_write_timeout [Numeric, nil] seconds a notification, a server-to-client request, a listen
|
|
193
|
+
# acknowledgement or a keepalive may take to be written to an SSE stream before the stream is dropped as stalled.
|
|
194
|
+
# These writes are made on behalf of every stream in turn, so a peer that stops reading would otherwise hold
|
|
195
|
+
# the writer, and the streams after it, for as long as its buffers stay full. The response of a request is not bounded:
|
|
196
|
+
# it is written on that request's own thread and may be large. The bound is per stream, so several stalled streams delay
|
|
197
|
+
# a notification by the sum of their waits, once each. Closing a stream is given the same number of seconds, once.
|
|
198
|
+
# Defaults to `DEFAULT_STREAM_WRITE_TIMEOUT` (10); pass `nil` to wait without limit.
|
|
191
199
|
# @param token_verifier [#verify, nil] enables built-in OAuth 2.1 bearer enforcement: anything responding to
|
|
192
200
|
# `verify(token) -> MCP::Server::OAuth::AccessToken | nil` (see `MCP::Server::OAuth::TokenVerifier` for
|
|
193
201
|
# the contract and the built-in JWT/introspection implementations). Every POST, GET, and DELETE is verified
|
|
@@ -227,6 +235,7 @@ module MCP
|
|
|
227
235
|
listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL,
|
|
228
236
|
serve_subscriptions_listen: true,
|
|
229
237
|
server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT,
|
|
238
|
+
stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT,
|
|
230
239
|
token_verifier: nil,
|
|
231
240
|
required_scopes: [],
|
|
232
241
|
resource_metadata: nil,
|
|
@@ -325,6 +334,15 @@ module MCP
|
|
|
325
334
|
|
|
326
335
|
@server_to_client_request_timeout = server_to_client_request_timeout
|
|
327
336
|
|
|
337
|
+
unless stream_write_timeout.nil? || (stream_write_timeout.is_a?(Numeric) && stream_write_timeout.positive?)
|
|
338
|
+
raise ArgumentError, "stream_write_timeout must be a positive number or nil"
|
|
339
|
+
end
|
|
340
|
+
|
|
341
|
+
@stream_write_timeout = stream_write_timeout
|
|
342
|
+
|
|
343
|
+
# Keyed by identity and weak, so a stream is not kept alive for having been recorded here.
|
|
344
|
+
@streams_with_abandoned_close = ObjectSpace::WeakMap.new
|
|
345
|
+
|
|
328
346
|
if token_verifier
|
|
329
347
|
@oauth_authenticator = OAuth::Authenticator.new(
|
|
330
348
|
token_verifier: token_verifier,
|
|
@@ -358,6 +376,14 @@ module MCP
|
|
|
358
376
|
REQUIRED_POST_ACCEPT_TYPES_JSON = ["application/json"].freeze
|
|
359
377
|
REQUIRED_GET_ACCEPT_TYPES = ["text/event-stream"].freeze
|
|
360
378
|
STREAM_WRITE_ERRORS = [IOError, Errno::EPIPE, Errno::ECONNRESET].freeze
|
|
379
|
+
|
|
380
|
+
# Raised from a write the transport pushes onto an SSE stream when it has not finished within `stream_write_timeout:` seconds.
|
|
381
|
+
# An `IOError`, so every path that drops a stream on a failed write drops this one the same way.
|
|
382
|
+
class StreamWriteTimeoutError < IOError; end
|
|
383
|
+
|
|
384
|
+
# A write blocks only once the peer's socket buffers are full, which takes a reader already hundreds of kilobytes behind;
|
|
385
|
+
# one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
|
|
386
|
+
DEFAULT_STREAM_WRITE_TIMEOUT = 10
|
|
361
387
|
SESSION_REAP_INTERVAL = 60
|
|
362
388
|
# Seconds `close` waits for a reap in progress to finish closing its streams before it kills the reaper.
|
|
363
389
|
REAPER_JOIN_TIMEOUT = 5
|
|
@@ -476,6 +502,9 @@ module MCP
|
|
|
476
502
|
# with a `StandardError` does not stop the teardown below: `join` re-raises the exception a thread died with,
|
|
477
503
|
# which is not this method's to raise. A reaper still alive after the wait is killed as before, leaving
|
|
478
504
|
# the streams of that reap it had not closed yet as they were.
|
|
505
|
+
# A `close` running on the reaper thread itself, reached from a stream's `close` or from the exception reporter
|
|
506
|
+
# during a reap, neither joins nor kills it: the join would fail on its own thread and the kill would end
|
|
507
|
+
# this teardown with the reap that called it. The reaper leaves its loop on `@closing` once that reap returns.
|
|
479
508
|
def close
|
|
480
509
|
reaper = @mutex.synchronize do
|
|
481
510
|
@closing = true
|
|
@@ -483,13 +512,15 @@ module MCP
|
|
|
483
512
|
@reaper_thread
|
|
484
513
|
end
|
|
485
514
|
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
515
|
+
if reaper && !reaper.equal?(Thread.current)
|
|
516
|
+
begin
|
|
517
|
+
reaper.join(REAPER_JOIN_TIMEOUT)
|
|
518
|
+
rescue StandardError
|
|
519
|
+
# The reaper is gone either way; the exception that ended it is not this method's to report.
|
|
520
|
+
end
|
|
491
521
|
|
|
492
|
-
|
|
522
|
+
reaper.kill if reaper.alive?
|
|
523
|
+
end
|
|
493
524
|
@reaper_thread = nil
|
|
494
525
|
|
|
495
526
|
teardown_listen_subscriptions
|
|
@@ -504,6 +535,20 @@ module MCP
|
|
|
504
535
|
end
|
|
505
536
|
end
|
|
506
537
|
|
|
538
|
+
# Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
|
|
539
|
+
# Public only so that `Server#notify_log_message` can call it. Custom transports may implement this hook;
|
|
540
|
+
# returning `nil` keeps the server-wide filter.
|
|
541
|
+
#
|
|
542
|
+
# @api private
|
|
543
|
+
# @return [Array<ServerSession>]
|
|
544
|
+
def logging_sessions
|
|
545
|
+
@mutex.synchronize do
|
|
546
|
+
@sessions.values.filter_map do |session|
|
|
547
|
+
session[:server_session] if session[:get_sse_stream]
|
|
548
|
+
end
|
|
549
|
+
end
|
|
550
|
+
end
|
|
551
|
+
|
|
507
552
|
def send_notification(method, params = nil, session_id: nil, related_request_id: nil)
|
|
508
553
|
# `subscriptions/listen` streams (SEP-2575) receive matching change notifications regardless of the delivery below:
|
|
509
554
|
# a resource updated by one session's tool call changed globally, so modern subscribers hear about it too.
|
|
@@ -614,7 +659,7 @@ module MCP
|
|
|
614
659
|
# Writes a notification to an SSE stream without holding `@mutex`. On a write error,
|
|
615
660
|
# drops the broken stream and returns false; on success returns true.
|
|
616
661
|
def write_notification(stream, notification, session_id, related_request_id)
|
|
617
|
-
|
|
662
|
+
push_to_stream(stream, notification)
|
|
618
663
|
true
|
|
619
664
|
rescue *STREAM_WRITE_ERRORS => e
|
|
620
665
|
MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to send notification" })
|
|
@@ -717,7 +762,7 @@ module MCP
|
|
|
717
762
|
sent = false
|
|
718
763
|
if stream
|
|
719
764
|
begin
|
|
720
|
-
|
|
765
|
+
push_to_stream(stream, request)
|
|
721
766
|
sent = true
|
|
722
767
|
rescue *STREAM_WRITE_ERRORS
|
|
723
768
|
drop_broken_stream(session_id, stream, related_request_id)
|
|
@@ -861,6 +906,41 @@ module MCP
|
|
|
861
906
|
stream.flush
|
|
862
907
|
end
|
|
863
908
|
|
|
909
|
+
# `send_to_stream` and `send_ping_to_stream` for the frames the transport pushes onto a stream on its own: a notification,
|
|
910
|
+
# a server-to-client request, a listen acknowledgement, a keepalive. One thread writes them to stream after stream,
|
|
911
|
+
# and a keepalive write holds its stream's write mutex, so a peer that stopped reading would stall the notifications of
|
|
912
|
+
# every other client, and each thread that sends one, for as long as its buffers stay full.
|
|
913
|
+
# The write is given `stream_write_timeout:` seconds; past that it fails as a write to a broken stream does, and the caller drops the stream.
|
|
914
|
+
#
|
|
915
|
+
# The deadline may cut a frame short, so the stream is closed here, before the error leaves: a listen stream is written under its write mutex,
|
|
916
|
+
# which the error releases on its way out, ahead of the caller's removal of the entry, and a writer waiting on that mutex would otherwise put
|
|
917
|
+
# its frame after the cut one. Closed first, every later write fails as on any closed stream. The entry of a listen stream, passed as `subscription`,
|
|
918
|
+
# is marked closed as well, still under its write mutex, so those writers skip it even when the close itself had to be abandoned.
|
|
919
|
+
#
|
|
920
|
+
#
|
|
921
|
+
# The deadline interrupts the write with the exception `Timeout` raises on its own, which no `rescue` of an `IOError` or a `StandardError` inside
|
|
922
|
+
# a stream implementation catches, and becomes `StreamWriteTimeoutError` only here, where it leaves the write.
|
|
923
|
+
def push_to_stream(stream, data, subscription: nil)
|
|
924
|
+
within_stream_write_timeout(stream, subscription) { send_to_stream(stream, data) }
|
|
925
|
+
end
|
|
926
|
+
|
|
927
|
+
def push_ping_to_stream(stream, subscription: nil)
|
|
928
|
+
within_stream_write_timeout(stream, subscription) { send_ping_to_stream(stream) }
|
|
929
|
+
end
|
|
930
|
+
|
|
931
|
+
def within_stream_write_timeout(stream, subscription, &block)
|
|
932
|
+
return yield unless @stream_write_timeout
|
|
933
|
+
|
|
934
|
+
begin
|
|
935
|
+
Timeout.timeout(@stream_write_timeout, &block)
|
|
936
|
+
rescue Timeout::Error
|
|
937
|
+
subscription[:closed] = true if subscription
|
|
938
|
+
close_stream_safely(stream)
|
|
939
|
+
|
|
940
|
+
raise StreamWriteTimeoutError, "SSE stream write did not finish within #{@stream_write_timeout} seconds"
|
|
941
|
+
end
|
|
942
|
+
end
|
|
943
|
+
|
|
864
944
|
# Serves one request of the stateless modern lifecycle (MCP 2026-07-28, SEP-2575):
|
|
865
945
|
# a single POST/JSON exchange with no session. The modern path never consults
|
|
866
946
|
# `@stateless`, `@sessions`, or `@enable_json_response`, and never issues or accepts
|
|
@@ -900,9 +980,9 @@ module MCP
|
|
|
900
980
|
message: "Unsupported protocol version",
|
|
901
981
|
data: {
|
|
902
982
|
supported: MCP::Configuration::SUPPORTED_MODERN_PROTOCOL_VERSIONS,
|
|
903
|
-
requested: header_version,
|
|
983
|
+
requested: printable_value(header_version),
|
|
904
984
|
},
|
|
905
|
-
id: body[:id],
|
|
985
|
+
id: echoable_id(body[:id]),
|
|
906
986
|
)
|
|
907
987
|
end
|
|
908
988
|
|
|
@@ -911,13 +991,20 @@ module MCP
|
|
|
911
991
|
status: 400,
|
|
912
992
|
code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
|
|
913
993
|
message: "Bad Request: Mcp-Session-Id is not accepted in the modern lifecycle",
|
|
914
|
-
id: body[:id],
|
|
994
|
+
id: echoable_id(body[:id]),
|
|
915
995
|
)
|
|
916
996
|
end
|
|
917
997
|
|
|
918
998
|
mismatch_error = validate_modern_headers(request, body, header_version)
|
|
919
999
|
return mismatch_error if mismatch_error
|
|
920
1000
|
|
|
1001
|
+
# SEP-2243 custom headers: the `Mcp-Param-*` headers of a `tools/call` are checked against the body here,
|
|
1002
|
+
# before dispatch, so a disagreement is refused without the tool ever running.
|
|
1003
|
+
if body[:method] == Methods::TOOLS_CALL
|
|
1004
|
+
param_error = validate_mcp_param_headers(request, body)
|
|
1005
|
+
return param_error if param_error
|
|
1006
|
+
end
|
|
1007
|
+
|
|
921
1008
|
# `subscriptions/listen` is a long-lived notification stream served at the transport layer;
|
|
922
1009
|
# it never dispatches through `Server#handle`. A transport constructed with
|
|
923
1010
|
# `serve_subscriptions_listen: false` skips the interception, so the method falls through
|
|
@@ -975,10 +1062,10 @@ module MCP
|
|
|
975
1062
|
# converge on enforcement.
|
|
976
1063
|
def validate_modern_headers(request, body, header_version)
|
|
977
1064
|
params = body[:params]
|
|
978
|
-
meta_version = params.is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
|
|
1065
|
+
meta_version = params.is_a?(Hash) && params[:_meta].is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
|
|
979
1066
|
if meta_version && meta_version != header_version
|
|
980
1067
|
return header_mismatch_response(
|
|
981
|
-
"MCP-Protocol-Version header value '#{header_version}' does not match body value '#{meta_version}'",
|
|
1068
|
+
"MCP-Protocol-Version header value '#{printable_value(header_version)}' does not match body value '#{printable_value(meta_version)}'",
|
|
982
1069
|
body[:id],
|
|
983
1070
|
)
|
|
984
1071
|
end
|
|
@@ -997,7 +1084,7 @@ module MCP
|
|
|
997
1084
|
end
|
|
998
1085
|
if method_header != body[:method]
|
|
999
1086
|
return header_mismatch_response(
|
|
1000
|
-
"Mcp-Method header value '#{method_header}' does not match body value '#{body[:method]}'",
|
|
1087
|
+
"Mcp-Method header value '#{printable_value(method_header)}' does not match body value '#{printable_value(body[:method])}'",
|
|
1001
1088
|
body[:id],
|
|
1002
1089
|
)
|
|
1003
1090
|
end
|
|
@@ -1008,7 +1095,7 @@ module MCP
|
|
|
1008
1095
|
if body_name
|
|
1009
1096
|
if name_header.to_s.empty?
|
|
1010
1097
|
return header_mismatch_response(
|
|
1011
|
-
"Mcp-Name header is required for `#{body[:method]}`",
|
|
1098
|
+
"Mcp-Name header is required for `#{printable_value(body[:method])}`",
|
|
1012
1099
|
body[:id],
|
|
1013
1100
|
)
|
|
1014
1101
|
end
|
|
@@ -1016,7 +1103,7 @@ module MCP
|
|
|
1016
1103
|
decoded_name = decode_header_value(name_header)
|
|
1017
1104
|
if decoded_name != body_name
|
|
1018
1105
|
return header_mismatch_response(
|
|
1019
|
-
"Mcp-Name header value '#{decoded_name}' does not match body value '#{body_name}'",
|
|
1106
|
+
"Mcp-Name header value '#{printable_value(decoded_name)}' does not match body value '#{printable_value(body_name)}'",
|
|
1020
1107
|
body[:id],
|
|
1021
1108
|
)
|
|
1022
1109
|
end
|
|
@@ -1026,6 +1113,39 @@ module MCP
|
|
|
1026
1113
|
nil
|
|
1027
1114
|
end
|
|
1028
1115
|
|
|
1116
|
+
# Enforces the SEP-2243 server behavior for custom headers (`-32020`, HTTP 400) on a modern `tools/call`: each
|
|
1117
|
+
# `x-mcp-header` parameter of the called tool must have its `Mcp-Param-{Name}` header present exactly when the body
|
|
1118
|
+
# carries a value for it, agreeing with that value once a `=?base64?...?=` sentinel is decoded, and a malformed
|
|
1119
|
+
# sentinel is refused outright. The comparison runs before the tool does, on the schema the server itself serves
|
|
1120
|
+
# in `tools/list`, so the body a handler acts on is the one an intermediary routed on. A tool the server does not
|
|
1121
|
+
# know, or one whose declarations are invalid (a conforming client drops such a tool and sends no headers for it),
|
|
1122
|
+
# is left to the dispatcher, and headers for parameters no declaration names are ignored, as the spec asks of any
|
|
1123
|
+
# server that does not recognize them. The refusal names the header and the argument, not their values.
|
|
1124
|
+
#
|
|
1125
|
+
# Rack folds header names into `HTTP_` keys with `-` as `_`, so `Mcp-Param-Region-A` and `Mcp-Param-Region_A` land
|
|
1126
|
+
# on one key; a token that differs only in that way is the schema author's choice, and the value still has to
|
|
1127
|
+
# agree with the body.
|
|
1128
|
+
def validate_mcp_param_headers(request, body)
|
|
1129
|
+
params = body[:params]
|
|
1130
|
+
return unless params.is_a?(Hash)
|
|
1131
|
+
|
|
1132
|
+
tool = @server.tools[params[:name]]
|
|
1133
|
+
return unless tool
|
|
1134
|
+
|
|
1135
|
+
scan = McpParamHeaders.scan(tool.input_schema.to_h)
|
|
1136
|
+
return unless scan[:valid] && !scan[:declarations].empty?
|
|
1137
|
+
|
|
1138
|
+
arguments = params[:arguments] || {}
|
|
1139
|
+
return unless arguments.is_a?(Hash)
|
|
1140
|
+
|
|
1141
|
+
message = McpParamHeaders.mismatch(scan[:declarations], arguments) do |header_name|
|
|
1142
|
+
header_bytes(request, "HTTP_#{header_name.upcase.tr("-", "_")}")
|
|
1143
|
+
end
|
|
1144
|
+
return unless message
|
|
1145
|
+
|
|
1146
|
+
header_mismatch_response(message, body[:id])
|
|
1147
|
+
end
|
|
1148
|
+
|
|
1029
1149
|
# Serves `subscriptions/listen` (SEP-2575): opens a long-lived SSE stream whose first message is
|
|
1030
1150
|
# `notifications/subscriptions/acknowledged` with the subset of requested notification types
|
|
1031
1151
|
# the server agreed to honor. Notifications delivered on the stream carry `io.modelcontextprotocol/subscriptionId`
|
|
@@ -1130,6 +1250,14 @@ module MCP
|
|
|
1130
1250
|
false
|
|
1131
1251
|
end
|
|
1132
1252
|
|
|
1253
|
+
# The id a refusal built here can echo: an Integer, or a String that is valid UTF-8. A String holding other
|
|
1254
|
+
# bytes would make the body's `to_json` raise, so the refusal carries no id, as for an id it could not read.
|
|
1255
|
+
def echoable_id(id)
|
|
1256
|
+
return id if id.is_a?(Integer) || (id.is_a?(String) && id.valid_encoding?)
|
|
1257
|
+
|
|
1258
|
+
nil
|
|
1259
|
+
end
|
|
1260
|
+
|
|
1133
1261
|
def listen_subscriptions_full?
|
|
1134
1262
|
return false unless @max_listen_subscriptions
|
|
1135
1263
|
|
|
@@ -1217,7 +1345,7 @@ module MCP
|
|
|
1217
1345
|
acknowledged = subscription[:write_mutex].synchronize do
|
|
1218
1346
|
next false if subscription[:closed]
|
|
1219
1347
|
|
|
1220
|
-
|
|
1348
|
+
push_to_stream(stream, acknowledgement, subscription: subscription)
|
|
1221
1349
|
|
|
1222
1350
|
# Set on the entry itself, not through the registry: a concurrent close may already have cleared the registry
|
|
1223
1351
|
# while its result write waits on this mutex, and that write must still find the stream acknowledged.
|
|
@@ -1298,7 +1426,7 @@ module MCP
|
|
|
1298
1426
|
subscription[:write_mutex].synchronize do
|
|
1299
1427
|
next if subscription[:closed]
|
|
1300
1428
|
|
|
1301
|
-
|
|
1429
|
+
push_ping_to_stream(subscription[:stream], subscription: subscription)
|
|
1302
1430
|
end
|
|
1303
1431
|
end
|
|
1304
1432
|
|
|
@@ -1440,7 +1568,7 @@ module MCP
|
|
|
1440
1568
|
subscription[:write_mutex].synchronize do
|
|
1441
1569
|
next if subscription[:closed]
|
|
1442
1570
|
|
|
1443
|
-
|
|
1571
|
+
push_to_stream(subscription[:stream], notification, subscription: subscription)
|
|
1444
1572
|
end
|
|
1445
1573
|
rescue *STREAM_WRITE_ERRORS => e
|
|
1446
1574
|
MCP.configuration.exception_reporter.call(
|
|
@@ -1530,6 +1658,10 @@ module MCP
|
|
|
1530
1658
|
# The stream is left open for the caller to close.
|
|
1531
1659
|
def write_listen_closing_result(subscription)
|
|
1532
1660
|
subscription[:write_mutex].synchronize do
|
|
1661
|
+
# Already marked by a write that ran into its deadline: the last frame on the stream may be cut short,
|
|
1662
|
+
# and the stream may still be open because its close was abandoned, so the result must not follow it.
|
|
1663
|
+
next if subscription[:closed]
|
|
1664
|
+
|
|
1533
1665
|
subscription[:closed] = true
|
|
1534
1666
|
|
|
1535
1667
|
# A stream whose acknowledgement was never written gets no result either: SEP-2575 makes
|
|
@@ -1566,12 +1698,21 @@ module MCP
|
|
|
1566
1698
|
end
|
|
1567
1699
|
end
|
|
1568
1700
|
|
|
1701
|
+
# A client-supplied value for an error message or `data` member. A header value reaches the transport as
|
|
1702
|
+
# ASCII-8BIT from a Rack server, or tagged UTF-8 from a test request or a framework, and a body value comes
|
|
1703
|
+
# out of the JSON parser; a value holding bytes that are not valid UTF-8 would make the response's `to_json`
|
|
1704
|
+
# raise and turn the intended 400 into a 500 with an exception report. Such bytes are replaced with U+FFFD;
|
|
1705
|
+
# a valid value comes through unchanged.
|
|
1706
|
+
def printable_value(value)
|
|
1707
|
+
value.to_s.dup.force_encoding(Encoding::UTF_8).scrub
|
|
1708
|
+
end
|
|
1709
|
+
|
|
1569
1710
|
def header_mismatch_response(message, id)
|
|
1570
1711
|
json_rpc_error_response(
|
|
1571
1712
|
status: 400,
|
|
1572
1713
|
code: ErrorCodes::HEADER_MISMATCH,
|
|
1573
1714
|
message: "Header mismatch: #{message}",
|
|
1574
|
-
id: id,
|
|
1715
|
+
id: echoable_id(id),
|
|
1575
1716
|
)
|
|
1576
1717
|
end
|
|
1577
1718
|
|
|
@@ -1648,7 +1789,7 @@ module MCP
|
|
|
1648
1789
|
if header_version && MCP::Configuration.modern_protocol_version?(header_version)
|
|
1649
1790
|
return invalid_request_response(
|
|
1650
1791
|
"Invalid Request: the session already negotiated the legacy lifecycle via `initialize`",
|
|
1651
|
-
request_id: body[:id],
|
|
1792
|
+
request_id: echoable_id(body[:id]),
|
|
1652
1793
|
)
|
|
1653
1794
|
end
|
|
1654
1795
|
|
|
@@ -1694,7 +1835,7 @@ module MCP
|
|
|
1694
1835
|
session = @mutex.synchronize { @sessions[session_id] }
|
|
1695
1836
|
return session_not_found_response unless session && session_principal_matches?(session, request)
|
|
1696
1837
|
|
|
1697
|
-
return already_initialized_response(body[:id])
|
|
1838
|
+
return already_initialized_response(echoable_id(body[:id]))
|
|
1698
1839
|
end
|
|
1699
1840
|
|
|
1700
1841
|
return session_not_found_response
|
|
@@ -1829,8 +1970,21 @@ module MCP
|
|
|
1829
1970
|
removed[:post_request_streams]&.each_value { |stream| streams_to_close << stream }
|
|
1830
1971
|
end
|
|
1831
1972
|
|
|
1973
|
+
# A close can block on the same full buffers a write does (a TLS stream writes its closing alert, a buffered one flushes),
|
|
1974
|
+
# and it runs on the threads that deliver to every stream, in places under a stream's write mutex,
|
|
1975
|
+
# so it gets `stream_write_timeout:` seconds as well. One that has not finished by then is abandoned,
|
|
1976
|
+
# and not tried again: the path that drops a stream after its write timed out closes it a second time,
|
|
1977
|
+
# which would wait out the same block once more.
|
|
1832
1978
|
def close_stream_safely(stream)
|
|
1833
|
-
stream
|
|
1979
|
+
return unless stream
|
|
1980
|
+
return stream.close unless @stream_write_timeout
|
|
1981
|
+
return if @streams_with_abandoned_close.key?(stream)
|
|
1982
|
+
|
|
1983
|
+
begin
|
|
1984
|
+
Timeout.timeout(@stream_write_timeout) { stream.close }
|
|
1985
|
+
rescue Timeout::Error
|
|
1986
|
+
@streams_with_abandoned_close[stream] = true
|
|
1987
|
+
end
|
|
1834
1988
|
rescue StandardError
|
|
1835
1989
|
# Ignore close-related errors from already closed/broken streams.
|
|
1836
1990
|
end
|
|
@@ -1894,7 +2048,7 @@ module MCP
|
|
|
1894
2048
|
end
|
|
1895
2049
|
|
|
1896
2050
|
def validate_accept_header(request, required_types)
|
|
1897
|
-
accept_header = request
|
|
2051
|
+
accept_header = header_bytes(request, "HTTP_ACCEPT")
|
|
1898
2052
|
return not_acceptable_response(required_types) unless accept_header
|
|
1899
2053
|
|
|
1900
2054
|
accepted_types = parse_accept_header(accept_header)
|
|
@@ -1913,7 +2067,7 @@ module MCP
|
|
|
1913
2067
|
end
|
|
1914
2068
|
|
|
1915
2069
|
def validate_content_type(request)
|
|
1916
|
-
content_type = request
|
|
2070
|
+
content_type = header_bytes(request, "CONTENT_TYPE")
|
|
1917
2071
|
media_type = content_type&.split(";")&.first&.strip&.downcase
|
|
1918
2072
|
return if media_type == "application/json"
|
|
1919
2073
|
|
|
@@ -1961,7 +2115,7 @@ module MCP
|
|
|
1961
2115
|
status: 413,
|
|
1962
2116
|
code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
|
|
1963
2117
|
message: "Payload too large: initialize request #{reason}",
|
|
1964
|
-
id: request_id,
|
|
2118
|
+
id: echoable_id(request_id),
|
|
1965
2119
|
)
|
|
1966
2120
|
end
|
|
1967
2121
|
|
|
@@ -2050,7 +2204,7 @@ module MCP
|
|
|
2050
2204
|
json_rpc_error_response(
|
|
2051
2205
|
status: 400,
|
|
2052
2206
|
code: JsonRpcHandler::ErrorCode::INVALID_REQUEST,
|
|
2053
|
-
message: "Bad Request: Unsupported protocol version: #{header_value}. Supported versions: #{supported}",
|
|
2207
|
+
message: "Bad Request: Unsupported protocol version: #{printable_value(header_value)}. Supported versions: #{supported}",
|
|
2054
2208
|
)
|
|
2055
2209
|
end
|
|
2056
2210
|
|
|
@@ -2423,10 +2577,18 @@ module MCP
|
|
|
2423
2577
|
validate_host(request) || validate_origin(request)
|
|
2424
2578
|
end
|
|
2425
2579
|
|
|
2580
|
+
# A header value as bytes. Rack servers hand header values over as ASCII-8BIT, where every byte is valid, but a framework
|
|
2581
|
+
# or a test request can tag them UTF-8, and then `downcase`, `split`, and regexps raise on an invalid byte sequence
|
|
2582
|
+
# before any rescue applies. Reading the value as bytes puts both on the same footing: a malformed value fails its comparison
|
|
2583
|
+
# and gets the rejection that comparison produces, instead of failing the request.
|
|
2584
|
+
def header_bytes(request, name)
|
|
2585
|
+
request.env[name]&.b
|
|
2586
|
+
end
|
|
2587
|
+
|
|
2426
2588
|
# Rejects a rebound `Host` (e.g. `evil.example.com` re-pointed at 127.0.0.1).
|
|
2427
2589
|
# A request without a `Host` header (e.g. HTTP/1.0) is allowed; the rebinding vector this guards against always carries one.
|
|
2428
2590
|
def validate_host(request)
|
|
2429
|
-
host = request
|
|
2591
|
+
host = header_bytes(request, "HTTP_HOST")
|
|
2430
2592
|
return if host.nil?
|
|
2431
2593
|
|
|
2432
2594
|
# An `allowed_hosts:` entry matches either the bare host name (any port)
|
|
@@ -2441,7 +2603,7 @@ module MCP
|
|
|
2441
2603
|
# A request without an `Origin` header (typical for non-browser MCP clients) is allowed. A browser cross-origin request is
|
|
2442
2604
|
# rejected unless the origin is same-origin or explicitly allow-listed via `allowed_origins:`.
|
|
2443
2605
|
def validate_origin(request)
|
|
2444
|
-
origin = request
|
|
2606
|
+
origin = header_bytes(request, "HTTP_ORIGIN")
|
|
2445
2607
|
return if origin.nil?
|
|
2446
2608
|
return if same_origin?(origin, request)
|
|
2447
2609
|
return if @allowed_origins.include?(origin.downcase)
|
|
@@ -2462,7 +2624,7 @@ module MCP
|
|
|
2462
2624
|
# but the `Origin`'s scheme is used to drop a redundant default port (`:80` for http, `:443` for https) from
|
|
2463
2625
|
# both sides so `http://example.com` matches `Host: example.com:80`. Comparison is case-insensitive.
|
|
2464
2626
|
def same_origin?(origin, request)
|
|
2465
|
-
host = request
|
|
2627
|
+
host = header_bytes(request, "HTTP_HOST")
|
|
2466
2628
|
return false if host.nil?
|
|
2467
2629
|
|
|
2468
2630
|
normalized = origin.downcase
|
|
@@ -2644,7 +2806,7 @@ module MCP
|
|
|
2644
2806
|
def send_keepalive_ping(session_id, stream)
|
|
2645
2807
|
return unless session_holds_stream?(session_id, stream)
|
|
2646
2808
|
|
|
2647
|
-
|
|
2809
|
+
push_ping_to_stream(stream)
|
|
2648
2810
|
rescue *STREAM_WRITE_ERRORS => e
|
|
2649
2811
|
MCP.configuration.exception_reporter.call(
|
|
2650
2812
|
e,
|