Class: McpToolkit::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/mcp_toolkit/session.rb

Overview

Server-side session for the MCP Streamable HTTP transport: created on initialize, identified by an opaque Mcp-Session-Id header the client echoes on every later request, stored in the configured cache with a sliding TTL.

Cache-backed (rather than the gem's in-process StreamableHTTPTransport) so sessions survive across Puma workers and interoperate with a gateway's client. The cache store + TTL come from McpToolkit.config.

A session carries an opaque data hash the transport can attach at creation (e.g. { token_id: ... }) so an AUTHORITY can bind a session to a token id — the property that lets a revoked token kill an in-flight session. The gem does NOT interpret data (it never re-resolves a token; that's the consumer's auth concern): it stores it, round-trips it, and exposes it via #data.

Constant Summary collapse

CACHE_KEY_PREFIX =
"mcp_toolkit:session:"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id:, data: {}) ⇒ Session

Returns a new instance of Session.



50
51
52
53
# File 'lib/mcp_toolkit/session.rb', line 50

def initialize(id:, data: {})
  @id = id
  @data = data || {}
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



48
49
50
# File 'lib/mcp_toolkit/session.rb', line 48

def data
  @data
end

#idObject (readonly)

Returns the value of attribute id.



48
49
50
# File 'lib/mcp_toolkit/session.rb', line 48

def id
  @id
end

Class Method Details

.create!(data: {}, config: McpToolkit.config) ⇒ Object



19
20
21
22
23
# File 'lib/mcp_toolkit/session.rb', line 19

def self.create!(data: {}, config: McpToolkit.config)
  id = SecureRandom.uuid
  config.cache_store.write(cache_key(id), { created_at: Time.now.to_i, data: }, expires_in: config.session_ttl)
  new(id:, data:)
end

.delete(id, config: McpToolkit.config) ⇒ Object



37
38
39
40
41
# File 'lib/mcp_toolkit/session.rb', line 37

def self.delete(id, config: McpToolkit.config)
  return false if id.to_s.empty?

  config.cache_store.delete(cache_key(id))
end

.find(id, config: McpToolkit.config) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/mcp_toolkit/session.rb', line 25

def self.find(id, config: McpToolkit.config)
  return nil if id.to_s.empty?

  stored = config.cache_store.read(cache_key(id))
  return nil unless stored

  # Sliding expiry: bump TTL on every successful lookup.
  config.cache_store.write(cache_key(id), stored, expires_in: config.session_ttl)
  # `data` defaults to {} for legacy rows written before the payload existed.
  new(id:, data: stored[:data] || {})
end