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
This commit is contained in:
Ates Goral 2026-04-20 13:08:28 -04:00
commit ff3a42f3fb

View file

@ -94,6 +94,28 @@ module MCP
)
end
# Terminates the session by sending an HTTP DELETE to the MCP endpoint
# with the current `Mcp-Session-Id` header, and clears locally tracked
# session state afterward. No-op when no session has been established.
#
# Per spec, the server MAY respond with HTTP 405 Method Not Allowed when
# it does not support client-initiated termination, and returns 404 for
# a session it has already terminated. Both mean the session is gone —
# the desired end state. Other errors surface to the caller; local
# session state is cleared either way.
# https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management
def close
return unless @session_id
begin
client.delete("", nil, session_headers)
rescue Faraday::ClientError => e
raise unless [404, 405].include?(e.response&.dig(:status))
ensure
clear_session
end
end
private
attr_reader :headers