Class: Tina4::McpServer

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/mcp.rb

Overview

── McpServer ─────────────────────────────────────────────────────

Constant Summary collapse

SUPPORTED_PROTOCOL_VERSIONS =

MCP protocol versions this server can speak, newest first. The 2025-* versions are the Streamable HTTP era; 2024-11-05 is the legacy HTTP+SSE transport we still accept for older clients (Claude Desktop et al.).

%w[2025-06-18 2025-03-26 2024-11-05].freeze
LATEST_PROTOCOL_VERSION =
SUPPORTED_PROTOCOL_VERSIONS.first

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, name: "Tina4 MCP", version: "1.0.0") ⇒ McpServer

Returns a new instance of McpServer.



234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/tina4/mcp.rb', line 234

def initialize(path, name: "Tina4 MCP", version: "1.0.0")
  @path        = path.chomp("/")
  @name        = name
  @version     = version
  @tools       = {}
  @resources   = {}
  @initialized = false
  # Streamable HTTP sessions: id => opened-at epoch. `initialize` mints one
  # (returned in the Mcp-Session-Id header); a request bearing an unknown id
  # gets a 404 so the client re-initializes.
  @sessions    = {}
  self.class.instances << self
end

Class Attribute Details

.instancesObject (readonly)

Returns the value of attribute instances.



231
232
233
# File 'lib/tina4/mcp.rb', line 231

def instances
  @instances
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



226
227
228
# File 'lib/tina4/mcp.rb', line 226

def name
  @name
end

#pathObject (readonly)

Returns the value of attribute path.



226
227
228
# File 'lib/tina4/mcp.rb', line 226

def path
  @path
end

#versionObject (readonly)

Returns the value of attribute version.



226
227
228
# File 'lib/tina4/mcp.rb', line 226

def version
  @version
end

Instance Method Details

#close_session(session_id) ⇒ Object

Forget a session (client DELETE or SSE stream close). Returns true when a live session was actually removed.



324
325
326
# File 'lib/tina4/mcp.rb', line 324

def close_session(session_id)
  !@sessions.delete(session_id).nil?
end

#dispatch_http(raw_data, session_id = "") ⇒ Object

Transport-agnostic Streamable HTTP POST handler. Every transport calls this so the wire behaviour stays identical:

- `initialize` mints a session id, returned in the Mcp-Session-Id header.
- a non-initialize request carrying an unknown session id is a 404
(JSON-RPC error) so the client knows to re-initialize.
- a notification / response-only POST (no id) yields 202 with an empty
body.
- anything else returns 200 with the JSON-RPC response as
application/json (the MCP Streamable HTTP spec permits a POST that
resolves to a single response to answer inline).

Returns { status:, headers:, body: }.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/tina4/mcp.rb', line 348

def dispatch_http(raw_data, session_id = "")
  is_init = peek_method(raw_data) == "initialize"
  if !is_init && !session_id.to_s.empty? && !is_valid_session(session_id)
    return {
      status: 404,
      headers: {},
      body: McpProtocol.encode_error(nil, McpProtocol::INVALID_REQUEST, "session not found")
    }
  end

  body = handle_message(raw_data)
  headers = {}
  headers["Mcp-Session-Id"] = open_session if is_init
  return { status: 202, headers: headers, body: "" } if body.nil? || body.empty?

  { status: 200, headers: headers, body: body }
end

#handle_message(raw_data) ⇒ Object

Process an incoming JSON-RPC message and return the response string.



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/tina4/mcp.rb', line 276

def handle_message(raw_data)
  begin
    method, params, request_id = McpProtocol.decode_request(raw_data)
  rescue ArgumentError => e
    return McpProtocol.encode_error(nil, McpProtocol::PARSE_ERROR, e.message)
  end

  handler_method = {
    "initialize"                 => :_handle_initialize,
    "notifications/initialized"  => :_handle_initialized,
    "tools/list"                 => :_handle_tools_list,
    "tools/call"                 => :_handle_tools_call,
    "resources/list"             => :_handle_resources_list,
    "resources/read"             => :_handle_resources_read,
    "ping"                       => :_handle_ping
  }[method]

  if handler_method.nil?
    return McpProtocol.encode_error(request_id, McpProtocol::METHOD_NOT_FOUND, "Method not found: #{method}")
  end

  begin
    result = send(handler_method, params)
    return "" if request_id.nil? # Notification -- no response
    McpProtocol.encode_response(request_id, result)
  rescue => e
    McpProtocol.encode_error(request_id, McpProtocol::INTERNAL_ERROR, e.message)
  end
end

#is_valid_session(session_id) ⇒ Object

True when session_id was issued by this server and is still open.



318
319
320
# File 'lib/tina4/mcp.rb', line 318

def is_valid_session(session_id)
  !session_id.to_s.empty? && @sessions.key?(session_id)
end

#negotiate_protocol_version(requested) ⇒ Object

Pick the protocol version to run on. Echo the client's requested version when we support it (proper negotiation), else fall back to the newest version we speak so an unversioned/old client still connects.



331
332
333
334
335
# File 'lib/tina4/mcp.rb', line 331

def negotiate_protocol_version(requested)
  return requested if SUPPORTED_PROTOCOL_VERSIONS.include?(requested)

  LATEST_PROTOCOL_VERSION
end

#open_sessionObject

Mint a new session id and remember it. Called on initialize.



311
312
313
314
315
# File 'lib/tina4/mcp.rb', line 311

def open_session
  sid = SecureRandom.hex(16)
  @sessions[sid] = Time.now.to_f
  sid
end

#register_resource(uri, handler, description = "", mime_type = "application/json") ⇒ Object

Register a resource URI.



265
266
267
268
269
270
271
272
273
# File 'lib/tina4/mcp.rb', line 265

def register_resource(uri, handler, description = "", mime_type = "application/json")
  @resources[uri] = {
    "uri"         => uri,
    "name"        => description.empty? ? uri : description,
    "description" => description.empty? ? uri : description,
    "mimeType"    => mime_type,
    "handler"     => handler
  }
end

#register_routes(router = nil) ⇒ Object

Register HTTP routes for this MCP server on the Tina4 router. Custom (developer-created) MCP servers use this; the built-in dev server mounts the same transport via DevAdmin's dispatcher.



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/tina4/mcp.rb', line 369

def register_routes(router = nil)
  server    = self
  base_path = @path
  msg_path  = "#{@path}/message"
  sse_path  = "#{@path}/sse"

  # Streamable HTTP (current transport) — single POST endpoint.
  Tina4::Router.post(base_path) do |request, response|
    out = server.dispatch_http(request.body, (request.header("mcp-session-id") || "").to_s)
    out[:headers].each { |k, v| response.header(k, v) }
    response.call(out[:body], out[:status], "application/json")
  end

  # DELETE terminates the session (Streamable HTTP spec).
  Tina4::Router.delete(base_path) do |request, response|
    server.close_session((request.header("mcp-session-id") || "").to_s)
    response.call("", 204)
  end

  # GET on the endpoint is a server->client stream we do not open here.
  Tina4::Router.get(base_path) do |_request, response|
    response.header("allow", "POST, DELETE")
    response.call({ "error" => "Method Not Allowed" }, 405, "application/json")
  end

  # Legacy HTTP+SSE POST target — inline, session-lenient.
  Tina4::Router.post(msg_path) do |request, response|
    out = server.dispatch_http(request.body, "")
    out[:headers].each { |k, v| response.header(k, v) }
    response.call(out[:body], out[:status], "application/json")
  end

  # Legacy HTTP+SSE handshake — one-shot endpoint event.
  Tina4::Router.get(sse_path) do |request, response|
    endpoint_url = "#{request.url.sub(%r{/sse\z}, "")}/message"
    sse_data = "event: endpoint\ndata: #{endpoint_url}\n\n"
    response.call(sse_data, 200, "text/event-stream")
  end
end

#register_tool(name, handler, description = "", schema = nil) ⇒ Object

Register a tool callable.

Parameters:

  • name (String)
  • handler (Method, Proc, #call)

    the callable

  • description (String) (defaults to: "")
  • schema (Hash, nil) (defaults to: nil)

    override auto-detected schema



254
255
256
257
258
259
260
261
262
# File 'lib/tina4/mcp.rb', line 254

def register_tool(name, handler, description = "", schema = nil)
  schema ||= Tina4.schema_from_method(handler)
  @tools[name] = {
    "name"        => name,
    "description" => description.empty? ? name : description,
    "inputSchema" => schema,
    "handler"     => handler
  }
end

#resourcesObject

Access registered resources (for testing)



440
441
442
# File 'lib/tina4/mcp.rb', line 440

def resources
  @resources
end

#toolsObject

Access registered tools (for testing)



435
436
437
# File 'lib/tina4/mcp.rb', line 435

def tools
  @tools
end

#write_claude_config(port = 7145) ⇒ Object

Write/update .claude/settings.json with this MCP server config.



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/tina4/mcp.rb', line 410

def write_claude_config(port = 7145)
  config_dir = File.join(Dir.pwd, ".claude")
  FileUtils.mkdir_p(config_dir)
  config_file = File.join(config_dir, "settings.json")

  config = {}
  if File.exist?(config_file)
    begin
      config = JSON.parse(File.read(config_file))
    rescue JSON::ParserError, IOError
      # ignore corrupt file
    end
  end

  config["mcpServers"] ||= {}
  server_key = @name.downcase.gsub(" ", "-")
  config["mcpServers"][server_key] = {
    "type" => "http",
    "url"  => "http://localhost:#{port}#{@path}"
  }

  File.write(config_file, JSON.pretty_generate(config) + "\n")
end