Class: Parse::Agent::MCPRackApp

Inherits:
Object
  • Object
show all
Defined in:
lib/parse/agent/mcp_rack_app.rb,
lib/parse/agent/mcp_deployments.rb

Overview

Supported MCP deployment patterns, packaged as MCPRackApp factories.

Two explicit access modes, so a deployment can never drift from one into the other by accident:

  • MCPRackApp.user_scoped: every request carries a Parse session token. The agent acts as that user (ACL/CLP enforced by Parse Server on REST and by the SDK on mongo-direct paths). A missing, blank, invalid, expired, or revoked token is refused with 401 before any agent is built, and there is no fallback to master-key access.

  • MCPRackApp.master_analytics: master authority for analytics and trusted operational tools, narrowed by the agent's configured tools, classes, and fields, and read-only by default. Operator identity is mandatory: without a principal_resolver every master-key agent fingerprints as the same principal, and callers would share ownership of each other's streams, approvals, and cancellations.

Direct MCPRackApp.new(agent_factory: ...) construction is unchanged and remains the way to build anything else, including an intentional single-operator master-key endpoint.

Defined Under Namespace

Classes: CancellationRegistry, ListeningStreamBody, PrincipalRateLimiters, SSEBody, SessionCheckUnavailable, SessionOwnerRegistry

Constant Summary collapse

DEFAULT_MAX_BODY_SIZE =

Maximum allowed request body size in bytes (matches MCPServer::MAX_BODY_SIZE).

1_048_576
MAX_JSON_NESTING =

JSON nesting depth limit (matches MCPServer::MAX_JSON_NESTING).

20
DEFAULT_HEARTBEAT_INTERVAL =

Default heartbeat interval in seconds when streaming is enabled.

2
DEFAULT_MAX_CONCURRENT_DISPATCHERS =

Default bound on concurrently-active streaming dispatchers — and, separately, on concurrently-open listening streams — when the max_concurrent_dispatchers: constructor argument is omitted. Finite by default so that enabling a streaming surface (request-scoped SSE or the long-lived GET / stream) does not silently expose an unbounded orphan-thread DoS surface. The cap is applied SEPARATELY to each surface, so the effective ceiling across both is up to 2x this value. Pass an explicit nil to knowingly opt into the unbounded surface.

100
DEFAULT_APPROVAL_TIMEOUT =

Seconds to wait for a human's elicitation reply before failing closed (refusing the destructive op). Generous by default — a human-in-the-loop approver needs time the tool timeout doesn't allow. Tune via approval_timeout:.

300
JSON_CONTENT_TYPE =

Standard Content-Type for all JSON responses. Frozen template — call #json_headers to obtain a per-response mutable copy that composes with Rack middleware that decorates response headers (e.g. Sinatra's xss_header / json_csrf / common_logger).

{ "Content-Type" => "application/json" }.freeze
SSE_HEADERS =

SSE response headers. X-Accel-Buffering disables Nginx proxy buffering. Frozen template — call #sse_headers to obtain a per-response copy.

{
  "Content-Type" => "text/event-stream",
  "Cache-Control" => "no-cache",
  "Connection" => "keep-alive",
  "X-Accel-Buffering" => "no",
}.freeze
DEFAULT_SESSION_REVALIDATE_INTERVAL =

Default seconds between identity re-checks on a user-scoped listening stream. Bounds how long a revoked session keeps receiving notifications on an already-open stream.

60
USER_PRINCIPAL_ENV_KEY =

Rack env key where user_scoped records the verified user id for the request, read back by its principal resolver.

"parse.agent.user_scoped.user_id"
SESSION_VALIDATION_MODES =

Accepted values for session_validation:.

%i[per_request cached].freeze
USER_SCOPED_REFUSED_AGENT_OPTIONS =

Options that would give a user-scoped agent authority beyond its session, refused by user_scoped.

%i[master_atlas allow_mutations].freeze
FACTORY_OWNED_AGENT_OPTIONS =

Agent constructor options a factory owns. Passing them through agent_options: would let configuration override the identity or authority the factory pins, so they are refused at construction.

%i[
  session_token acl_user acl_role
  impersonate_user impersonation_user impersonate_mint impersonation_mint
  impersonate_label impersonation_label
  tenant_id client permissions permission parent
].freeze
FACTORY_OWNED_APP_OPTIONS =

Rack app options a factory owns.

%i[
  agent_factory principal_resolver
  listening_stream_revalidator listening_stream_revalidate_interval
].freeze
DEFAULT_SESSION_TOKEN_FROM =

Default session-token extraction: Authorization: Bearer <token>, else X-Parse-Session-Token.

lambda do |env|
  auth = env["HTTP_AUTHORIZATION"].to_s.strip
  if (m = auth.match(/\ABearer\s+(\S+)\z/i))
    m[1]
  else
    env["HTTP_X_PARSE_SESSION_TOKEN"]
  end
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(agent_factory: nil, max_body_size: DEFAULT_MAX_BODY_SIZE, logger: nil, streaming: nil, heartbeat_interval: DEFAULT_HEARTBEAT_INTERVAL, max_concurrent_dispatchers: DEFAULT_MAX_CONCURRENT_DISPATCHERS, pre_auth_rate_limiter: nil, allowed_origins: nil, require_custom_header: nil, loopback_csrf_default: false, allowed_hosts: nil, loopback_bind: false, resource_subscriptions: false, subscription_manager: nil, notifications: nil, transport: nil, approval_timeout: DEFAULT_APPROVAL_TIMEOUT, principal_resolver: nil, listening_stream_revalidator: nil, listening_stream_revalidate_interval: nil, health_path: nil, &block) ⇒ MCPRackApp

Returns a new instance of MCPRackApp.

Parameters:

  • agent_factory (Proc, nil) (defaults to: nil) —

    callable invoked with the Rack env on every request. Must return a Parse::Agent or raise Parse::Agent::Unauthorized. Mutually exclusive with a block.

  • max_body_size (Integer) (defaults to: DEFAULT_MAX_BODY_SIZE) —

    reject bodies larger than this many bytes. Defaults to DEFAULT_MAX_BODY_SIZE.

  • logger (#warn, nil) (defaults to: nil) —

    optional logger. When set, auth failures are warned at class-name level, and internal errors include a backtrace.

  • streaming (Boolean) (defaults to: nil) —

    enable SSE streaming for clients that send Accept: text/event-stream. Defaults to false for backward compatibility. Has no effect on WEBrick-backed deployments (see class documentation).

  • heartbeat_interval (Numeric) (defaults to: DEFAULT_HEARTBEAT_INTERVAL) —

    seconds between progress heartbeat events when streaming is active. Defaults to DEFAULT_HEARTBEAT_INTERVAL. Ignored when streaming: false.

  • max_concurrent_dispatchers (Integer, nil) (defaults to: DEFAULT_MAX_CONCURRENT_DISPATCHERS) —

    limits the number of concurrently active dispatcher threads across all SSE connections served by this app instance (and, separately, the number of open listening streams). When the limit is reached a new SSE request immediately receives a 503 JSON-RPC error envelope (-32000 "server busy") rather than spawning another dispatcher.

    Defaults to a finite DEFAULT_MAX_CONCURRENT_DISPATCHERS (100) — so a streaming surface is bounded out of the box rather than unbounded. Pass an explicit positive Integer to set the cap, or nil to knowingly opt into the unbounded surface (which warns at construction). A non-positive or non-integer value raises ArgumentError. Use active_dispatcher_count to monitor current concurrency from operator tooling.

  • pre_auth_rate_limiter (#check!, nil) (defaults to: nil) —

    optional rate limiter consulted at the top of every request, BEFORE the agent_factory is invoked. Closes the factory-amplification DoS where each malformed request burns a Parse Server round-trip (factories typically validate session tokens by calling out). Must respond to #check! and raise an exception responding to #retry_after (such as Parse::Agent::RateLimiter::RateLimitExceeded) when exhausted. Defaults to nil (no pre-auth limiter). On exhaustion the request is rejected with HTTP 429 and a Retry-After header. #check! is called with no arguments, so this limits total volume, not any one client. A per-agent RateLimiter built inside a per-request factory does not limit across requests. Enforce per-client limits at a reverse proxy or API gateway as well; see "Deployment-layer limits" in docs/mcp_guide.md.

  • allowed_origins (Array<String>, nil) (defaults to: nil) —

    when set, the Origin request header must match one of these entries (case-insensitive, exact host match — wildcard via leading . matches subdomains). nil (default) skips the check. Browsers always send Origin on cross-origin POST; native clients (curl, ruby HTTP client, SDK-to-SDK) typically don't, and an absent Origin is treated as allowed regardless of this setting. The default loopback bind makes this check optional in development; operators who bind MCP to a routable interface should configure it.

  • allowed_hosts (Array<String>, nil) (defaults to: nil) —

    Host header values this app answers to, as a hostname ("mcp.example.com", any port) or host:port ("mcp.example.com:8443", that port only), compared case-insensitively. This is the MCP spec's DNS-rebinding guidance: a rebinding page reaches a loopback server under the attacker's hostname, so its requests carry that hostname in Host even when it strips or spoofs nothing else. When set, a request whose Host is not listed (and, on a loopback bind, is not a loopback host) is refused with 403. nil (default) applies the check only on a loopback bind.

  • loopback_bind (Boolean) (defaults to: false) —

    the app is served on a loopback interface. Enables the Host check with localhost, 127.0.0.1, and [::1] (any port) allowed, plus any allowed_hosts: entries. Implied by loopback_csrf_default: true. Parse::Agent::MCPServer sets it from its bind address. A request with no Host header is allowed: browsers always send one, so its absence is a native client.

  • require_custom_header (String, nil) (defaults to: nil) —

    when set (e.g. "X-MCP-Client"), requests must carry that header with any non-empty value. Custom headers can't be set by a <form> CSRF and force a CORS preflight on browser fetch(), so this gate closes the browser-driven attack surface entirely. Pair with allowed_origins for defense in depth.

  • health_path (String, nil) (defaults to: nil) —

    when set (e.g. "/health"), GET requests to that exact path return 200 {"status":"ok"} without invoking the agent_factory, without authentication, without rate-limiting, and without applying the allowed_origins / require_custom_header CSRF gates. Intended as a liveness probe for load balancers and orchestrators (Kubernetes, ECS, Consul) that cannot present a matching Origin or custom header. Because the probe sits ahead of the pre-auth rate limiter, operators should front-edge rate-limit the path at the LB/Nginx layer if public-facing. The response intentionally contains no version, build, or counter information — fingerprint-minimal by design. nil (default) disables the endpoint entirely; empty-string values are coerced to nil. Any non-GET method on the path falls through to the standard 405 handler.

  • resource_subscriptions (Boolean) (defaults to: false) —

    enable MCP resource subscriptions (resources/subscribe + notifications/resources/updated) bridged onto Parse LiveQuery. Defaults to false. When true, this app accepts a GET with Accept: text/event-stream and an Mcp-Session-Id header as a long-lived server→client listening stream, and advertises the resources.subscribe capability on initialize — but ONLY while LiveQuery is enabled (Parse.live_query_enabled = true) and available (a live_query_url is configured). Requires a streaming-capable Rack server (Puma, Falcon); WEBrick buffers responses and cannot hold the listening stream open. See docs/mcp_guide.md for the credential-scoping and single-process caveats.

  • subscription_manager (Parse::Agent::MCPSubscriptions::Manager, nil) (defaults to: nil) —

    inject a pre-built manager (tests, or to share a clustered-notifier adapter). Takes precedence over resource_subscriptions:. When nil and resource_subscriptions: true, a default in-process manager is constructed.

  • transport (Symbol, nil) (defaults to: nil) —

    MCP transport selector. Pass :streamable_http to enable the full MCP 2025-06-18 Streamable HTTP transport in one switch — exactly equivalent to streaming: true, notifications: true (POST→SSE plus the server→client GET / stream). resource_subscriptions: true may still be combined to upgrade the bus to its LiveQuery-backed posture. :legacy (or the default nil) selects the historical non-streaming behavior; the standalone SSE/JSON path stays a supported fallback. Any other value raises ArgumentError. Passing :streamable_http together with an explicit streaming: or notifications: also raises, since the switch already owns those toggles. Requires a streaming-capable Rack server (Puma, Falcon, Unicorn); has no effect under WEBrick.

  • listening_stream_revalidator (#call, nil) (defaults to: nil) —

    re-checks the caller's identity on long-lived GET listening streams. Called with the agent that opened the stream every listening_stream_revalidate_interval seconds; a falsy return (or a raise) closes the stream, which tears down that session's subscriptions. POST requests re-authenticate through the agent factory on every call, but a listening stream is authenticated once at attach, so this is what bounds how long a revoked session keeps receiving notifications. nil (default) skips revalidation. user_scoped installs one.

  • listening_stream_revalidate_interval (Numeric, nil) (defaults to: nil) —

    seconds between revalidations. Required (positive) when a revalidator is set.

Raises:

  • (ArgumentError) —

    if both or neither of agent_factory/block are given.



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# File 'lib/parse/agent/mcp_rack_app.rb', line 348

def initialize(agent_factory: nil, max_body_size: DEFAULT_MAX_BODY_SIZE,
               logger: nil, streaming: nil,
               heartbeat_interval: DEFAULT_HEARTBEAT_INTERVAL,
               max_concurrent_dispatchers: DEFAULT_MAX_CONCURRENT_DISPATCHERS,
               pre_auth_rate_limiter: nil,
               allowed_origins: nil,
               require_custom_header: nil,
               loopback_csrf_default: false,
               allowed_hosts: nil,
               loopback_bind: false,
               resource_subscriptions: false,
               subscription_manager: nil,
               notifications: nil,
               transport: nil,
               approval_timeout: DEFAULT_APPROVAL_TIMEOUT,
               principal_resolver: nil,
               listening_stream_revalidator: nil,
               listening_stream_revalidate_interval: nil,
               health_path: nil, &block)
  if agent_factory && block
    raise ArgumentError, "Provide agent_factory: OR a block, not both"
  end
  unless agent_factory || block
    raise ArgumentError, "Either agent_factory: keyword or a block is required"
  end
  if pre_auth_rate_limiter && !pre_auth_rate_limiter.respond_to?(:check!)
    raise ArgumentError, "pre_auth_rate_limiter must respond to #check!"
  end

  # `transport:` is the consolidation switch over the granular
  # `streaming:` / `notifications:` toggles. `streaming` and
  # `notifications` default to nil (not false) precisely so we can tell
  # "operator left it alone" from "operator explicitly set it" and raise
  # on a conflicting combination instead of silently letting the switch
  # win. Closed enum — unknown values fail closed.
  unless transport.nil? || %i[legacy streamable_http].include?(transport)
    raise ArgumentError,
          "transport: must be :streamable_http, :legacy, or nil, got #{transport.inspect}"
  end
  if transport == :streamable_http
    unless streaming.nil? && notifications.nil?
      raise ArgumentError,
            "transport: :streamable_http already enables streaming and the server-initiated " \
            "notification stream; do not also pass streaming:/notifications: " \
            "(resource_subscriptions: may still be combined to upgrade the bus to LiveQuery)"
    end
    streaming = true
    notifications = true
  end
  # Collapse the nil sentinel to the historical default for the
  # remainder of the constructor (and @streaming below).
  streaming = false if streaming.nil?
  notifications = false if notifications.nil?

  @agent_factory = agent_factory || block
  @max_body_size = max_body_size
  @logger = logger
  @streaming = streaming
  @heartbeat_interval = heartbeat_interval
  # The dispatcher cap defaults to the finite DEFAULT_MAX_CONCURRENT_DISPATCHERS
  # (set in the signature). An explicit positive Integer overrides it; an
  # explicit nil knowingly opts into the unbounded surface; anything else
  # is a config error and raises.
  validate_max_concurrent_dispatchers!(max_concurrent_dispatchers)
  @max_concurrent_dispatchers = max_concurrent_dispatchers
  @pre_auth_rate_limiter = pre_auth_rate_limiter
  @allowed_origins = normalize_allowed_origins(allowed_origins)
  @required_custom_header = normalize_required_custom_header(require_custom_header)
  # NEW-9: when no explicit allowed_origins / require_custom_header CSRF
  # gate is configured but the server was started on an unauthenticated
  # loopback bind, default to a loopback-only Origin policy. A browser
  # DNS-rebinding attack against 127.0.0.1 always carries an `Origin`
  # header (the attacker page's origin), so refusing any present
  # non-loopback Origin closes that vector — while native clients (curl,
  # SDK-to-SDK) send NO Origin and stay allowed, and a legitimate local
  # browser UI sends a loopback Origin and is allowed. Ignored when an
  # explicit allowlist is configured (operator owns the policy then).
  @loopback_csrf_default = loopback_csrf_default && @allowed_origins.nil?
  # Host header gate (DNS-rebinding). Keyed off the raw
  # `loopback_csrf_default` argument, not the Origin-suppressed value
  # above: an explicit Origin allowlist does not change the fact that
  # the app is reachable on a loopback interface.
  @allowed_hosts = normalize_allowed_hosts(allowed_hosts)
  @loopback_host_check = loopback_bind == true || loopback_csrf_default == true
  @health_path = health_path.is_a?(String) && !health_path.empty? ? health_path : nil
  # Per-app registry of in-flight cancellable requests. Keyed by
  # [correlation_id, request_id]. A `notifications/cancelled` POST
  # whose `params.requestId` matches an entry trips the registered
  # CancellationToken. Scoped per-instance, not per-process: this
  # registry does not span multiple MCPRackApp mount points within
  # a process, nor multiple processes in a clustered deployment.
  @cancellation_registry = CancellationRegistry.new

  # Elicitation (human-in-the-loop approval) state, shared across
  # this app's requests and its GET listening streams. The
  # capability registry records (per session) whether the client
  # advertised `elicitation` at initialize; the pending registry
  # holds server→client requests awaiting a reply. Both are cheap
  # and always present; they only do work when
  # Parse::Agent.require_approval_for opts a tier in.
  @elicitation_capabilities = Parse::Agent::ClientCapabilityRegistry.new
  # Per-session minimum log level set by `logging/setLevel`. Log
  # messages ride the response stream of an SSE request, so a session
  # that never sets a level (or never streams) receives none.
  @log_levels = Parse::Agent::MCPDispatcher::LogLevelRegistry.new
  @pending_elicitations = Parse::Agent::PendingElicitationRegistry.new
  @approval_timeout = approval_timeout

  # Binds each MCP session id to the principal that established it so a
  # listening stream can't be hijacked by another authenticated caller.
  # Same per-instance / single-process scope as @cancellation_registry.
  # Live sessions (an attached listening stream or a pending approval)
  # keep their owner binding under LRU pressure.
  @session_owners = SessionOwnerRegistry.new(
    # A session holding subscriptions is pinned too: evicting its
    # binding would leave LiveQuery subscriptions (and a global session
    # slot) owned by no one, outside every per-principal bound.
    pinned: lambda do |sid|
      @pending_elicitations.pending_for?(sid) ||
        (@subscription_manager.respond_to?(:listener?) && @subscription_manager.listener?(sid)) ||
        (@subscription_manager.respond_to?(:subscriptions?) && @subscription_manager.subscriptions?(sid))
    end,
  )
  if principal_resolver && !principal_resolver.respond_to?(:call)
    raise ArgumentError, "principal_resolver must respond to #call"
  end
  @principal_resolver = principal_resolver

  if listening_stream_revalidator
    unless listening_stream_revalidator.respond_to?(:call)
      raise ArgumentError, "listening_stream_revalidator must respond to #call"
    end
    unless listening_stream_revalidate_interval.is_a?(Numeric) && listening_stream_revalidate_interval.positive?
      raise ArgumentError,
            "listening_stream_revalidate_interval must be a positive Numeric when a " \
            "listening_stream_revalidator is set (got #{listening_stream_revalidate_interval.inspect})"
    end
  end
  @listening_stream_revalidator = listening_stream_revalidator
  @listening_stream_revalidate_interval = listening_stream_revalidate_interval

  # Listening-stream coordinator (the server→client broadcast bus
  # backing resource subscriptions, MCP elicitation, and
  # general-purpose server-initiated notifications). An injected
  # manager wins. Otherwise:
  #   - `resource_subscriptions: true` builds a LiveQuery-backed
  #     manager whose `supported?` resolves live (advertises
  #     `resources.subscribe` and serves subscribe POSTs).
  #   - `notifications: true` (without resource subscriptions) builds
  #     a manager in `supported: false` posture: the GET listening
  #     stream + `#notify` bus work, but `resources.subscribe` stays
  #     unadvertised and subscribe POSTs fail closed. This is the
  #     decoupling lever — a server can push arbitrary notifications
  #     without enabling LiveQuery resource subscriptions.
  # nil disables the GET listening stream entirely.
  @subscription_manager = if subscription_manager
      subscription_manager
    elsif resource_subscriptions
      Parse::Agent::MCPSubscriptions::Manager.new(logger: @logger)
    elsif notifications
      Parse::Agent::MCPSubscriptions::Manager.new(logger: @logger, supported: false)
    end

  # Warn operators who enable a streaming surface AND have explicitly
  # opted into an unbounded dispatcher cap. Both request-scoped SSE
  # (streaming:) and the long-lived GET listening stream
  # (resource_subscriptions:/notifications:, which set
  # @subscription_manager) spawn per-connection threads; an unbounded
  # endpoint is a practical DoS surface — a slow or hostile client opening
  # connections faster than they close can exhaust the host thread pool and
  # downstream Parse connection pool. The cap bounds each surface
  # SEPARATELY, so the effective ceiling is up to 2x max_concurrent_dispatchers
  # across both. The default is now the finite DEFAULT_MAX_CONCURRENT_DISPATCHERS,
  # so a nil here means the operator deliberately chose `nil` (unbounded) —
  # we warn once at construction so the choice is visible.
  if (streaming || @subscription_manager) && @max_concurrent_dispatchers.nil?
    surface = streaming ? "streaming: true" : "resource_subscriptions/notifications"
    line = "[Parse::Agent::MCPRackApp] #{surface} with an explicitly unbounded dispatcher cap " \
           "(max_concurrent_dispatchers: nil). This is an orphan-thread DoS surface. " \
           "Prefer the finite default (#{DEFAULT_MAX_CONCURRENT_DISPATCHERS}) or pass a value sized to " \
           "~2x your Puma max_threads. See docs/mcp_guide.md for sizing guidance."
    if @logger
      @logger.warn(line)
    else
      warn line
    end
  end
end

Instance Attribute Details

#subscription_manager ⇒ Parse::Agent::MCPSubscriptions::Manager? (readonly)

The listening-stream coordinator backing this app's server→client bus, or nil when neither resource subscriptions nor notifications are enabled. Exposed so a clustered/Redis notifier adapter or an out-of-band publisher can reach the bus directly. Direct #publish accepts arbitrary messages (notifications OR id-bearing requests); prefer #notify for the validated notification path.



544
545
546
# File 'lib/parse/agent/mcp_rack_app.rb', line 544

def subscription_manager
  @subscription_manager
end

Class Method Details

.abandoned_dispatcher_count ⇒ Object

Process-wide CUMULATIVE count of GENUINE orphaned dispatchers — a client disconnect that closed the stream while the dispatcher thread was still running. Excludes already-finished-but-undelivered closes (a delivery miss, not an orphan). Unlike active_dispatcher_count / active_listening_stream_count this is a monotonic total, not a live gauge — operators alert on its rate of increase, the orphan-thread pressure signal under a disconnect-against-slow-tools storm. EVERY premature close (orphan or delivery-miss) also emits a parse.agent.mcp_dispatcher_abandoned ActiveSupport::Notifications event carrying dispatcher_alive:, so subscribers wanting the broader delivery-miss signal can filter there. Reset is not supported (counters are process-lifetime); subtract a baseline if you need a windowed delta.



616
617
618
# File 'lib/parse/agent/mcp_rack_app.rb', line 616

def self.abandoned_dispatcher_count
  @abandoned_dispatcher_mutex.synchronize { @abandoned_dispatcher_count }
end

.active_dispatcher_count ⇒ Object

Returns the number of currently live dispatcher threads spawned by any SSEBody across all MCPRackApp instances in this process. Threads are counted by the :parse_mcp_dispatcher thread-local tag set when each dispatcher_thread is started. Use this for operator dashboards or health checks; do NOT use it to make flow-control decisions at runtime (use the max_concurrent_dispatchers: constructor option for that).



581
582
583
# File 'lib/parse/agent/mcp_rack_app.rb', line 581

def self.active_dispatcher_count
  Thread.list.count { |t| t[:parse_mcp_dispatcher] }
end

.active_listening_stream_count ⇒ Object

Process-wide count of currently-open GET listening streams across all MCPRackApp instances. A listening stream is long-lived (the server→client notification channel) — each pins a server worker thread in #each plus a heartbeat thread — so it is bounded SEPARATELY from request-scoped SSE dispatchers (which #each, dispatch once, then close). Used as the soft cap in #serve_listening_stream. Maintained by ListeningStreamBody via adjust_listening_stream_count; unlike a Thread.list scan this is an explicit counter because the heartbeat thread is intentionally not tagged as a dispatcher.



594
595
596
# File 'lib/parse/agent/mcp_rack_app.rb', line 594

def self.active_listening_stream_count
  @listening_stream_mutex.synchronize { @listening_stream_count }
end

.adjust_listening_stream_count(delta) ⇒ Object



600
601
602
# File 'lib/parse/agent/mcp_rack_app.rb', line 600

def self.adjust_listening_stream_count(delta)
  @listening_stream_mutex.synchronize { @listening_stream_count += delta }
end

.master_analytics(principal_resolver:, permissions: :readonly, client: nil, tenant_from: nil, agent_options: {}, **rack_options, &block) ⇒ MCPRackApp

Build an MCP endpoint whose agents use master authority, for analytics and trusted operational tools.

principal_resolver: is required and must identify the operator behind each request (->(agent, env) { "op:#{verified_id}" }). It is used for session ownership (streams, approvals, cancellations) and audit; a request it cannot resolve (nil or blank) is refused with 401. Master authority governs what data the agent may reach; the agent's configured tools:, classes:, filters:, and field policy govern what it may actually do. Read-only by default.

Parameters:

  • principal_resolver (#call) —

    ->(agent, env) { principal }. Required.

  • permissions (Symbol) (defaults to: :readonly) —

    defaults to :readonly.

  • client (Parse::Client, nil) (defaults to: nil) —

    a client configured with the master key. nil uses Parse.client at request time.

  • tenant_from (#call, nil) (defaults to: nil) —

    ->(env, principal) { tenant } to pin tenant_id; nil or blank is refused with 401.

  • agent_options (Hash) (defaults to: {}) —

    extra Parse::Agent.new options. Identity and authority options are refused.

  • rack_options (Hash) —

    remaining MCPRackApp.new options.

Returns:

Raises:

  • (ArgumentError) —

    without a callable principal_resolver, or on a factory-owned option.



269
270
271
272
273
274
275
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/parse/agent/mcp_deployments.rb', line 269

def master_analytics(principal_resolver:, permissions: :readonly, client: nil,
                     tenant_from: nil, agent_options: {}, **rack_options, &block)
  raise ArgumentError, "MCPRackApp.master_analytics builds its own agent factory; do not pass a block" if block
  unless principal_resolver.respond_to?(:call)
    raise ArgumentError,
          "MCPRackApp.master_analytics requires principal_resolver: (->(agent, env) { operator_id }). " \
          "Without it every master-key agent shares one principal, so callers could attach to, " \
          "approve, or cancel each other's sessions. For a deliberate single-operator endpoint, " \
          "build MCPRackApp.new(agent_factory: ...) directly."
  end
  if tenant_from && !tenant_from.respond_to?(:call)
    raise ArgumentError, "tenant_from must respond to #call"
  end
  assert_factory_options!(:master_analytics, agent_options, rack_options)
  options = agent_options.dup.freeze
  limiters = Parse::Agent::MCPRackApp.principal_rate_limiters_for(options)

  # Resolve once per request and reuse it for ownership, so the
  # resolver's identity check is not repeated (and cannot disagree
  # with itself) between the factory and the fingerprint.
  memo_key = "parse.mcp.analytics_principal"
  resolver = lambda do |agent, env|
    env.key?(memo_key) ? env[memo_key] : (env[memo_key] = principal_resolver.call(agent, env))
  end

  factory = lambda do |env|
    parse_client = client || Parse.client
    unless parse_client.respond_to?(:master_key) && !parse_client.master_key.to_s.empty?
      raise Parse::Agent::Unauthorized.new("master_analytics requires a master-key client",
                                           reason: :no_master_key)
    end
    kwargs = options.merge(permissions: permissions)
    kwargs[:client] = client if client
    agent = Parse::Agent.new(**kwargs)
    principal = resolver.call(agent, env)
    if principal.nil? || principal.to_s.strip.empty?
      raise Parse::Agent::Unauthorized.new("Unidentified operator", reason: :missing_principal)
    end
    # The operator is known only once an agent exists (the resolver
    # receives it), so rebuild this request's agent with the
    # operator's shared limiter.
    agent = Parse::Agent.new(**kwargs, rate_limiter: limiters.fetch("op:#{principal}")) if limiters
    if tenant_from
      tenant = tenant_from.call(env, principal)
      if tenant.nil? || tenant.to_s.strip.empty?
        raise Parse::Agent::Unauthorized.new("No tenant for operator", reason: :missing_tenant)
      end
      agent.tenant_id = tenant
    end
    agent
  end

  new(agent_factory: factory, principal_resolver: resolver, **rack_options)
end

.principal_rate_limiters_for(agent_options) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The registry a factory uses, or nil when the caller injected its own rate_limiter: (honored as-is, e.g. a shared Redis limiter).



82
83
84
85
86
87
88
89
90
# File 'lib/parse/agent/mcp_deployments.rb', line 82

def self.principal_rate_limiters_for(agent_options)
  # Only a real injected limiter bypasses the registry; an explicit
  # `rate_limiter: nil` would otherwise give every request a fresh one.
  return nil unless agent_options[:rate_limiter].nil?
  PrincipalRateLimiters.new(
    limit: agent_options.fetch(:rate_limit, Parse::Agent::DEFAULT_RATE_LIMIT),
    window: agent_options.fetch(:rate_window, Parse::Agent::DEFAULT_RATE_WINDOW),
  )
end

.record_abandoned_dispatcher! ⇒ Object



622
623
624
# File 'lib/parse/agent/mcp_rack_app.rb', line 622

def self.record_abandoned_dispatcher!
  @abandoned_dispatcher_mutex.synchronize { @abandoned_dispatcher_count += 1 }
end

.strip_underscore_smuggled_headers!(env) ⇒ Hash

Drop env keys that would have come from underscore-form HTTP header names. The Rack-spec-compliant interpretation of HTTP headers maps X-MCP-API-Key and X_MCP_API_KEY to the same env key (HTTP_X_MCP_API_KEY); a misbehaving upstream server that forwards the underscore-form lets an attacker overwrite trusted reverse-proxy- injected headers.

This helper is invoked automatically at the top of #call, so any MCPRackApp mounted in a Rack 3+ pipeline (which exposes the original header list via rack.headers) gets defense-in-depth scrubbing without operator opt-in. On Rack 2 / pre-3 servers rack.headers is not set and the helper is a no-op; operators on those stacks must configure their upstream (e.g. Nginx underscores_in_headers off) OR mount this helper as an explicit middleware.

The standalone MCPServer rewrites its own build_rack_env to drop underscore-form names before they reach this app, so the standalone path is covered regardless of Rack version.

Examples:

Explicit middleware (Rack 2 / pre-3 deployments)

class StripSmuggledHeaders
  def initialize(app); @app = app; end
  def call(env)
    Parse::Agent::MCPRackApp.strip_underscore_smuggled_headers!(env)
    @app.call(env)
  end
end

Parameters:

  • env (Hash) —

    the Rack env, mutated in place

Returns:

  • (Hash) —

    the same env, for chaining



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/parse/agent/mcp_rack_app.rb', line 203

def self.strip_underscore_smuggled_headers!(env)
  # Rack 3+ preserves the original header list in env["rack.headers"]
  # (a Rack::Headers instance or Hash). When present, we can identify
  # which env keys came from an underscore-form header and delete
  # them, even if a dashed-form sibling arrived too.
  if env["rack.headers"].respond_to?(:each)
    suspect = []
    env["rack.headers"].each do |name, _|
      suspect << name if name.is_a?(String) && name.include?("_")
    end
    suspect.each do |name|
      env.delete("HTTP_#{name.upcase.tr("-", "_")}")
    end
  end
  env
end

.user_scoped(session_token_from: nil, permissions: :readonly, client: nil, tenant_from: nil, session_validation: :per_request, session_revalidate_interval: DEFAULT_SESSION_REVALIDATE_INTERVAL, agent_options: {}, **rack_options, &block) ⇒ MCPRackApp

Build an MCP endpoint whose agents act as the calling Parse user.

Every request (POST and the GET listening stream) must carry a session token. The token is validated before an agent is built; anything missing, blank, invalid, expired, or revoked gets 401. The resulting agent is Parse::Agent.new(session_token: token, ...), so identity comes from the session and cannot be changed by tool arguments. There is no master-key fallback in this mode.

Revocation. With the default session_validation: :per_request, each request re-checks the token against Parse Server (GET /users/me, uncached), so a logged-out, expired, or revoked session is refused on the next request. An already-open listening stream is re-checked every session_revalidate_interval seconds and closed (tearing down its subscriptions) when the check fails. session_validation: :cached trades that for fewer round trips: the token is resolved through client.authorization, so revocation takes effect after the identity-cache TTL unless the Parse::Cache::Invalidation hooks evict it first. See the "Deployment patterns" section of the MCP guide for the full interval table.

Parameters:

  • session_token_from (#call, nil) (defaults to: nil) —

    ->(env) { token }. Defaults to DEFAULT_SESSION_TOKEN_FROM.

  • permissions (Symbol) (defaults to: :readonly) —

    agent permission tier; :readonly (default), :write, or :admin. Writes still flow only through declared agent_methods and the existing env gates.

  • client (Parse::Client, nil) (defaults to: nil) —

    the client to validate tokens and build agents against. nil uses Parse.client at request time.

  • tenant_from (#call, nil) (defaults to: nil) —

    ->(env, user_id) { tenant } to pin the agent's tenant_id server-side. A nil or blank result is refused with 401 (fail closed).

  • session_validation (Symbol) (defaults to: :per_request) —

    :per_request (default) or :cached. See above.

  • session_revalidate_interval (Numeric) (defaults to: DEFAULT_SESSION_REVALIDATE_INTERVAL) —

    seconds between identity re-checks on an open listening stream.

  • agent_options (Hash) (defaults to: {}) —

    extra Parse::Agent.new options (for example tools:, methods:, classes:, filters:). Identity and authority options in FACTORY_OWNED_AGENT_OPTIONS are refused.

  • rack_options (Hash) —

    remaining MCPRackApp.new options (transport:, logger:, allowed_origins:, ...). Options in FACTORY_OWNED_APP_OPTIONS are refused.

Returns:

Raises:

  • (ArgumentError) —

    on a factory-owned option or invalid setting.



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/parse/agent/mcp_deployments.rb', line 167

def user_scoped(session_token_from: nil, permissions: :readonly, client: nil,
                tenant_from: nil, session_validation: :per_request,
                session_revalidate_interval: DEFAULT_SESSION_REVALIDATE_INTERVAL,
                agent_options: {}, **rack_options, &block)
  raise ArgumentError, "MCPRackApp.user_scoped builds its own agent factory; do not pass a block" if block
  if permissions.to_s == "admin"
    # The admin tier skips the spend cap and score quantization, which
    # are cost and inference controls meant for untrusted callers. Every
    # signed-in user of this endpoint would inherit that exemption.
    raise ArgumentError,
          "MCPRackApp.user_scoped does not accept permissions: :admin; use :readonly or :write"
  end
  assert_factory_options!(:user_scoped, agent_options, rack_options)
  extractor = session_token_from || DEFAULT_SESSION_TOKEN_FROM
  raise ArgumentError, "session_token_from must respond to #call" unless extractor.respond_to?(:call)
  if tenant_from && !tenant_from.respond_to?(:call)
    raise ArgumentError, "tenant_from must respond to #call"
  end
  unless SESSION_VALIDATION_MODES.include?(session_validation)
    raise ArgumentError,
          "session_validation must be one of #{SESSION_VALIDATION_MODES.inspect} " \
          "(got #{session_validation.inspect})"
  end
  options = agent_options.dup.freeze
  limiters = Parse::Agent::MCPRackApp.principal_rate_limiters_for(options)

  factory = lambda do |env|
    token = extractor.call(env).to_s.strip
    raise Parse::Agent::Unauthorized.new("Missing session token", reason: :missing_session) if token.empty?

    parse_client = client || Parse.client
    user_id = begin
        validate_session!(parse_client, token, mode: session_validation)
      rescue SessionCheckUnavailable
        # Fail closed for the request, but keep the token cached: the
        # session may well be valid once Parse Server answers again.
        raise Parse::Agent::Unauthorized.new("Session could not be verified",
                                             reason: :session_check_unavailable)
      end
    # The verified user id is the session's principal, so a refreshed
    # token (or a second login) for the same user keeps its sessions,
    # and per-principal bounds apply per user rather than per token.
    env[USER_PRINCIPAL_ENV_KEY] = user_id
    kwargs = options.merge(session_token: token, permissions: permissions)
    kwargs[:client] = client if client
    kwargs[:rate_limiter] = limiters.fetch("user:#{user_id}") if limiters
    if tenant_from
      tenant = tenant_from.call(env, user_id)
      if tenant.nil? || tenant.to_s.strip.empty?
        raise Parse::Agent::Unauthorized.new("No tenant for session", reason: :missing_tenant)
      end
      kwargs[:tenant_id] = tenant
    end
    Parse::Agent.new(**kwargs)
  end

  # A session Parse Server reports invalid closes the stream at once.
  # SessionCheckUnavailable (Parse Server unreachable, a 5xx) is left
  # to propagate, so the stream's revalidation loop counts it as a
  # transient error and only closes after repeated failures.
  revalidator = lambda do |agent|
    token = agent.respond_to?(:session_token) ? agent.session_token.to_s : ""
    return false if token.empty?
    validate_session!(client || Parse.client, token, mode: :per_request)
    true
  rescue Parse::Agent::Unauthorized
    false
  end

  resolver = ->(_agent, env) { (uid = env[USER_PRINCIPAL_ENV_KEY]) ? "user:#{uid}" : nil }

  new(agent_factory: factory,
      principal_resolver: resolver,
      listening_stream_revalidator: revalidator,
      listening_stream_revalidate_interval: session_revalidate_interval,
      **rack_options)
end

.validate_session!(parse_client, token, mode:) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Validate a session token and return its user id, or raise Unauthorized.

:per_request asks Parse Server directly (GET /users/me, response cache bypassed) and, on failure, evicts the token from the client's authorization identity cache so mongo-direct paths stop trusting it too. :cached resolves through client.authorization (identity cache, then /users/me on a miss).



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/parse/agent/mcp_deployments.rb', line 334

def validate_session!(parse_client, token, mode:)
  if mode == :cached
    begin
      resolved = parse_client.authorization.resolve(token)
    rescue Parse::Authorization::InvalidSession
      raise Parse::Agent::Unauthorized.new("Invalid session", reason: :invalid_session)
    end
    user_id = resolved.respond_to?(:user_id) ? resolved.user_id : nil
    raise Parse::Agent::Unauthorized.new("Invalid session", reason: :invalid_session) if user_id.to_s.empty?
    return user_id.to_s
  end

  response = begin
      parse_client.current_user(token, cache: false)
    rescue Parse::Error::InvalidSessionTokenError
      # Parse Server 9.x answers `/users/me` for a revoked, expired or
      # unknown token with HTTP 400 and code 209, which the client
      # raises as InvalidSessionTokenError. That is a definitive
      # rejection of the session, not an outage: evict the token and
      # refuse it. Treating it as an outage left a logged-out token
      # in the identity cache and answered the caller with a retryable
      # error instead of a 401.
      evict_session!(parse_client, token)
      raise Parse::Agent::Unauthorized.new("Invalid session", reason: :invalid_session)
    rescue StandardError => e
      raise SessionCheckUnavailable, "session check failed: #{e.class}"
    end
  if response.nil?
    raise SessionCheckUnavailable, "session check returned no response"
  end
  if response.error? && !session_rejected?(response)
    # Parse Server could not answer (5xx, timeout, an unexpected
    # error code). That says nothing about the session, so it is
    # neither accepted nor evicted from the identity cache.
    raise SessionCheckUnavailable, "session check failed (#{response.http_status || response.code})"
  end
  result = response.error? ? nil : response.result
  user_id = result.is_a?(Hash) ? (result["objectId"] || result[:objectId]) : nil
  if user_id.to_s.empty?
    evict_session!(parse_client, token)
    raise Parse::Agent::Unauthorized.new("Invalid session", reason: :invalid_session)
  end
  user_id.to_s
end

Instance Method Details

#call(env) ⇒ Array(Integer, Hash, #each)

Rack interface.

Parameters:

  • env (Hash) —

    Rack environment

Returns:

  • (Array(Integer, Hash, #each)) —

    Rack triple



630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
# File 'lib/parse/agent/mcp_rack_app.rb', line 630

def call(env)
  # 0. Defense-in-depth: strip underscore-form HTTP headers from env
  #    before any subsequent lookup reads HTTP_X_MCP_API_KEY / etc.
  #    No-op on Rack < 3 (where env["rack.headers"] is absent); on
  #    Rack 3+ this removes any HTTP_* env key whose original header
  #    name contained an underscore. Closes the smuggling path where
  #    a hostile client sends `X_MCP_API_Key: ...` alongside a
  #    trusted reverse-proxy-injected `X-MCP-API-Key: ...` and the
  #    underscored form collapses-and-overwrites the trusted slot.
  self.class.strip_underscore_smuggled_headers!(env)

  # 0a. Liveness probe. When `health_path:` is configured, a GET to
  #     that exact path returns `{"status":"ok"}` without auth,
  #     rate-limiting, or factory invocation. Intentionally
  #     fingerprint-minimal: no version, no build, no counter —
  #     a load balancer needs "is it up?", not "what is it?".
  if @health_path && env["PATH_INFO"] == @health_path && env["REQUEST_METHOD"] == "GET"
    return [200, json_headers, ['{"status":"ok"}']]
  end

  # 0a2. Host header gate (DNS-rebinding). Runs ahead of every method
  #      branch (POST, GET listening stream, DELETE) so a rebinding page
  #      cannot reach any of them under its own hostname.
  if host_refused?(env)
    @logger&.warn("[Parse::Agent::MCPRackApp] Host refused: #{env["HTTP_HOST"].to_s.strip[0, 255].inspect}")
    return [403, json_headers, [json_rpc_error(-32_700, "Host not allowed")]]
  end

  # 0b. NEW-MCP-6: pre-auth rate limit. Runs BEFORE the agent_factory
  #     so a malformed body / missing key / empty `{}` cannot force
  #     the operator-supplied factory to round-trip to Parse Server
  #     on every request. Off by default (constructor kwarg).
  if @pre_auth_rate_limiter
    begin
      @pre_auth_rate_limiter.check!
    rescue StandardError => e
      retry_after = e.respond_to?(:retry_after) ? e.retry_after : nil
      headers = json_headers.dup
      headers["Retry-After"] = retry_after.ceil.to_s if retry_after && retry_after > 0
      return [429, headers, [json_rpc_error(-32_000, "Too Many Requests")]]
    end
  end

  # 0c. DELETE /  — MCP 2025-06-18 Streamable HTTP session
  #     termination. A client signals it is done with a session by
  #     sending DELETE with the same `Mcp-Session-Id` header it
  #     received from initialize. Per spec the server MAY support
  #     this; if it doesn't, it MUST return 405. We support it.
  #
  #     Stateless-agent reality: the factory builds a fresh agent
  #     per request, so there is no server-side session store to
  #     evict. What DELETE meaningfully does is cancel any
  #     in-flight requests still running under that correlation_id
  #     so worker threads exit instead of completing wasted work.
  #     The cancellation_registry returns 0 when nothing matches
  #     (also the "unknown session" case) — we don't probe-leak by
  #     differentiating known vs unknown ids in the response.
  #
  #     Sanitized through Parse::Agent#correlation_id= via a
  #     throwaway agent so a malicious header value (CRLF, shell
  #     metachars) is silently rejected rather than reaching the
  #     registry as a key.
  if env["REQUEST_METHOD"] == "DELETE"
    sid = env["HTTP_MCP_SESSION_ID"].to_s
    if sid.empty?
      return [400, json_headers, [json_rpc_error(-32_600, "Missing Mcp-Session-Id")]]
    end
    clean_sid = sanitize_session_id(sid)
    if clean_sid.nil?
      return [400, json_headers, [json_rpc_error(-32_600, "Invalid Mcp-Session-Id")]]
    end
    # Termination is gated like every other session operation: the
    # Origin policy, authentication through the agent factory, and the
    # session's owner binding. Before 5.8 any caller who knew a session
    # id could terminate it (cancel its requests, drop its approvals,
    # subscriptions, and log level) without authenticating.
    if origin_refused?(env)
      return [403, json_headers, [json_rpc_error(-32_700, "Origin not allowed")]]
    end
    begin
      terminating_agent = @agent_factory.call(env)
    rescue Parse::Agent::Unauthorized
      @logger&.warn("[Parse::Agent::MCPRackApp] Unauthorized session termination")
      return [401, json_headers, [unauthorized_body]]
    rescue StandardError => e
      @logger&.warn("[Parse::Agent::MCPRackApp] Factory error on DELETE: #{e.class.name}")
      return [500, json_headers, [json_rpc_error(-32_603, "Internal error")]]
    end
    if @session_owners.claimed_by_other?(clean_sid, principal_fingerprint(terminating_agent, env))
      @logger&.warn("[Parse::Agent::MCPRackApp] session termination refused: owned by another principal")
      return [403, json_headers, [json_rpc_error(-32_600, "Mcp-Session-Id is owned by another principal")]]
    end
    @cancellation_registry.cancel_all_for(clean_sid, reason: :session_terminated)
    # Wake any tool thread blocked on an elicitation reply for this
    # session (it returns `unavailable` → fail closed) and drop the
    # session's cached elicitation capability.
    @pending_elicitations.abort_all_for(clean_sid, :session_terminated)
    @elicitation_capabilities.forget(clean_sid)
    @log_levels.forget(clean_sid)
    # Tear down any resource subscriptions and the listening stream
    # bound to this session so a terminated session leaves no LiveQuery
    # sockets behind.
    @subscription_manager&.detach_listener(clean_sid)
    # Drop the owner binding so the id can be reclaimed after explicit
    # termination (only here — not on mere stream close, so a reconnect
    # keeps its claim).
    @session_owners.forget(clean_sid)
    return [204, json_headers, [""]]
  end

  # 0d. GET listening stream — the MCP 2025-06-18 Streamable HTTP
  #     server→client channel that carries unsolicited
  #     `notifications/resources/updated`. Only when resource
  #     subscriptions are enabled, the client opted into SSE, and a
  #     valid Mcp-Session-Id is present. Authenticated via the same
  #     agent_factory as POST: the session id is a server-issued
  #     bearer capability (returned on initialize), so possession of
  #     it plus a valid agent gates the stream.
  if env["REQUEST_METHOD"] == "GET" && @subscription_manager &&
     env["HTTP_ACCEPT"].to_s.include?("text/event-stream")
    return serve_listening_stream(env)
  end

  # 1. Method check — only POST is accepted.
  unless env["REQUEST_METHOD"] == "POST"
    return [405,
            json_headers.merge("Allow" => "POST"),
            [json_rpc_error(-32_700, "method_not_allowed")]]
  end

  # 2. Content-type check — must be application/json (charset ignored).
  content_type = env["CONTENT_TYPE"].to_s.split(";").first.to_s.strip.downcase
  unless content_type == "application/json"
    return [415, json_headers, [json_rpc_error(-32_700, "Unsupported Media Type: Content-Type must be application/json")]]
  end

  # 2b. Origin allowlist. Browsers always send an `Origin` header
  #     on cross-origin POST; native clients typically don't.
  #     When configured, a non-empty `Origin` must match the
  #     allowlist or the request is rejected with 403.
  #     Missing/empty `Origin` is allowed regardless — native
  #     clients (curl, SDK-to-SDK) shouldn't be broken by a
  #     CSRF defense aimed at browsers.
  if origin_refused?(env)
    @logger&.warn("[Parse::Agent::MCPRackApp] Origin refused: #{env["HTTP_ORIGIN"].to_s.strip.inspect}")
    return [403, json_headers, [json_rpc_error(-32_700, "Origin not allowed")]]
  end

  # 2c. Required custom header (CSRF defense-in-depth). A header
  #     like `X-MCP-Client` cannot be set by a `<form>` CSRF and
  #     forces a CORS preflight on browser `fetch()`. When
  #     configured, the header must be present and (if a value
  #     was supplied to the constructor) match.
  if @required_custom_header
    header_env_key, expected_value = @required_custom_header
    actual = env[header_env_key].to_s
    if actual.empty? || (expected_value && actual != expected_value)
      return [403, json_headers, [json_rpc_error(-32_700, "Required custom header missing or invalid")]]
    end
  end

  # 3. Body size limit — read one byte beyond limit to detect oversized bodies
  #    without buffering the full stream.
  raw_body = env["rack.input"].read(@max_body_size + 1)
  if raw_body.bytesize > @max_body_size
    return [413, json_headers, [json_rpc_error(-32_700, "Payload Too Large: body exceeds #{@max_body_size} bytes")]]
  end

  # 4. JSON parse.
  begin
    body = JSON.parse(raw_body.empty? ? "{}" : raw_body, max_nesting: MAX_JSON_NESTING)
  rescue JSON::ParserError, JSON::NestingError
    return [400, json_headers, [json_rpc_error(-32_700, "Parse error: invalid JSON")]]
  end

  # 4b. NEW-MCP-6: refuse obviously-malformed JSON-RPC envelopes
  #     BEFORE invoking the agent_factory. The factory typically
  #     hits Parse Server (token validation, audit logging), so a
  #     barrage of empty `{}` or missing-method bodies otherwise
  #     amplifies into a Parse Server load problem. Empty-object
  #     and missing-method requests cannot possibly be valid
  #     JSON-RPC, so we shortcut to -32600 (Invalid Request).
  #     A method-less JSON-RPC RESPONSE ({jsonrpc,id,result|error}) is
  #     NOT malformed: it is the client's reply to a server-issued
  #     elicitation/create request. Let it through here; it is routed
  #     (session-bound) after the agent_factory resolves the session.
  unless (body.is_a?(Hash) && body["method"].is_a?(String) && !body["method"].empty?) ||
         elicitation_reply?(body)
    return [400, json_headers, [json_rpc_error(-32_600, "Invalid Request")]]
  end

  # 4c. MCP-Protocol-Version header validation (MCP 2025-06-18
  #     Streamable HTTP). The spec says:
  #       - The client MUST send `MCP-Protocol-Version: <ver>`
  #         on every request AFTER initialize.
  #       - If absent on a non-initialize request, the server
  #         SHOULD assume `2025-03-26` for backwards compatibility.
  #       - If present but not a version the server supports,
  #         the server MUST respond `400 Bad Request`.
  #     Initialize requests are exempt — initialize IS the
  #     negotiation, so the header is meaningless there.
  #     Cancellation notifications are also exempt because they
  #     may be sent by a client that has not (yet) completed
  #     initialize against this transport instance (e.g. a
  #     reconnecting client cancelling a pre-disconnect request).
  #     `server/discover` is exempt too. Newer clients send it before
  #     initialize, stamped with their own (newer) protocol version.
  #     A 400 here makes the client treat the server as broken. Letting
  #     it through yields -32601 from the dispatcher, and the client
  #     falls back to initialize, which negotiates a supported version.
  unless body["method"] == "initialize" ||
         body["method"] == "server/discover" ||
         body["method"] == "notifications/cancelled" ||
         elicitation_reply?(body)
    requested = env["HTTP_MCP_PROTOCOL_VERSION"]
    if requested.is_a?(String) && !requested.empty? &&
       !Parse::Agent::MCPDispatcher::SUPPORTED_PROTOCOL_VERSIONS.include?(requested)
      return [400, json_headers,
              [json_rpc_error(-32_600,
                              "Unsupported MCP-Protocol-Version: #{requested}",
                              id: body["id"])]]
    end
  end

  # 5. Agent factory — auth gate. Rescue Unauthorized first, then catch-all
  #    for unexpected factory errors.
  begin
    agent = @agent_factory.call(env)
  rescue Parse::Agent::Unauthorized => e
    @logger.warn("[Parse::Agent::MCPRackApp] Unauthorized: #{e.class.name}") if @logger
    return [401, json_headers, [unauthorized_body]]
  rescue StandardError => e
    if @logger
      @logger.warn("[Parse::Agent::MCPRackApp] Factory error: #{e.class.name}")
      @logger.warn(e.backtrace.join("\n")) if e.backtrace
    end
    return [500, json_headers, [json_rpc_error(-32_603, "Internal error")]]
  end

  # 5a-i. Surface the silent-ungated-writes footgun. A write/admin agent
  #     served over MCP with no approval tier configured runs every
  #     destructive tool without a human gate; warn once per process so
  #     the operator notices (mirrors the unrestricted-endpoints warning).
  if agent.respond_to?(:permissions) &&
     %i[write admin].include?(agent.permissions) &&
     Parse::Agent.require_approval_for.empty?
    Parse::Agent.warn_mcp_writes_unguarded!
  end

  # 5b. Thread the conversation correlation id through. Source
  #     header: the MCP 2025-06-18 Streamable HTTP spec-canonical
  #     `Mcp-Session-Id` (Rack env key `HTTP_MCP_SESSION_ID`).
  #
  #     Only fills it when the factory hasn't already assigned one
  #     — application code that needs to override the
  #     client-supplied id (e.g., bind to an internal session
  #     record) can do so in the factory and we don't stomp on it.
  #     The Parse::Agent#correlation_id= setter sanitizes the
  #     value; an invalid header is silently dropped.
  if agent && agent.respond_to?(:correlation_id=) &&
     agent.correlation_id.nil? &&
     (sid = env["HTTP_MCP_SESSION_ID"])
    agent.correlation_id = sid
  end

  # 5b-i. Server-assigned Mcp-Session-Id on initialize. Per MCP
  #     2025-06-18 Streamable HTTP, the server SHOULD assign a
  #     fresh session id during initialize when the client did not
  #     supply one, and return it on the response so the client
  #     can echo it on subsequent requests. Stateless-agent
  #     reality: the SDK does not maintain a server-side session
  #     store — the id is best-effort correlation only (used for
  #     audit-log threading and cancellation routing). We do not
  #     refuse subsequent requests carrying an "unknown" id.
  if body.is_a?(Hash) && body["method"] == "initialize" &&
     agent && agent.respond_to?(:correlation_id=) &&
     agent.correlation_id.nil?
    agent.correlation_id = SecureRandom.uuid
  end

  # 5b-ii. Capture the client's elicitation capability at initialize.
  #     The server reads (does not advertise) the client's
  #     `capabilities.elicitation`; the approval gate consults this
  #     per session before attempting a server→client prompt.
  if body.is_a?(Hash) && body["method"] == "initialize" &&
     agent.respond_to?(:correlation_id) && agent.correlation_id
    # Bind this session to the initializing principal FIRST, so only the
    # same principal can later attach a listening stream, set its log
    # level, or have its elicitation capability recorded (owner-binding;
    # see SessionOwnerRegistry). A session id already owned by another
    # principal is refused outright rather than rebound.
    if (limited = charge_session_op(agent, body))
      return limited
    end
    bound = @session_owners.bind(agent.correlation_id, principal_fingerprint(agent, env))
    if bound == :full
      @logger&.warn("[Parse::Agent::MCPRackApp] initialize refused: session registry full")
      return [503, json_headers, [json_rpc_error(-32_000, "Session capacity exhausted", id: body["id"])]]
    end
    unless bound
      @logger&.warn("[Parse::Agent::MCPRackApp] initialize refused: session owned by another principal")
      return [403, json_headers,
              [json_rpc_error(-32_600, "Mcp-Session-Id is owned by another principal", id: body["id"])]]
    end
    supported = elicitation_form_supported?(body.dig("params", "capabilities", "elicitation"))
    @elicitation_capabilities.set(agent.correlation_id, supported)
  end

  # 5b-iii. Elicitation reply ingress. A method-less JSON-RPC
  #     RESPONSE is the client's answer to a server-issued
  #     elicitation/create. Route it into the pending registry,
  #     session-bound by the same `correlation_id` the cancellation
  #     path uses, so one session can never answer another's prompt.
  #     Failures (no correlation_id, no match) are silent 202 no-ops
  #     to avoid a probe oracle — exactly like notifications/cancelled.
  if elicitation_reply?(body)
    # Only the session's owner may answer its approval prompts. A
    # mismatch is the same silent 202 as any other miss (no oracle).
    route_elicitation_reply(agent, body) if session_controllable?(agent, env)
    return [202, json_headers, [""]]
  end

  # 5c. notifications/cancelled — special-cased BEFORE the dispatcher.
  #     A JSON-RPC notification has no `id`, expects no response
  #     body, and must trip the in-flight request whose
  #     `(correlation_id, request_id)` matches. We require the
  #     cancelling request to carry the same Mcp-Session-Id
  #     (sanitized into agent.correlation_id above) as the original
  #     request — otherwise an attacker who guesses sequential
  #     JSON-RPC ids could cancel arbitrary in-flight requests.
  #
  #     Failures (no correlation_id, no requestId, no match) are
  #     silent no-ops to avoid a probe oracle. The response is
  #     always 202 Accepted with an empty body.
  if body.is_a?(Hash) && body["method"] == "notifications/cancelled"
    request_id = body.dig("params", "requestId")
    # Only the session's owner may cancel its in-flight requests; a
    # caller who merely knows (or chose) the same Mcp-Session-Id gets the
    # same silent 202 as any other miss.
    if agent.respond_to?(:correlation_id) && agent.correlation_id && request_id &&
       session_controllable?(agent, env)
      @cancellation_registry.cancel(
        agent.correlation_id,
        request_id,
        reason: :notifications_cancelled,
      )
    end
    return [202, json_headers, [""]]
  end

  # 5d. Session ownership for every other request. A request carrying a
  #     session id bound to another principal is refused, so knowing a
  #     session id is not enough to unsubscribe its resources, fill its
  #     subscription cap, or route an approval prompt to its stream.
  #     An unbound id (stateless clients, or a cluster where initialize
  #     landed on another worker) still works for ordinary calls.
  if (cid = agent.respond_to?(:correlation_id) ? agent.correlation_id : nil) &&
     body.is_a?(Hash) && body["method"] != "initialize"
    fingerprint = principal_fingerprint(agent, env)
    if @session_owners.claimed_by_other?(cid, fingerprint)
      @logger&.warn("[Parse::Agent::MCPRackApp] request refused: session owned by another principal")
      return [403, json_headers,
              [json_rpc_error(-32_600, "Mcp-Session-Id is owned by another principal", id: body["id"])]]
    end
    # Subscriptions hold server resources (LiveQuery sockets, global
    # session slots), so they need a session this principal established
    # (initialize, or a listening stream it attached). Without that, a
    # caller could invent session ids to fill the global session limit.
    if SESSION_BOUND_METHODS.include?(body["method"]) && @subscription_manager
      unless @session_owners.owned_by?(cid, fingerprint)
        # Not owned by anyone else (that was refused above), so the id
        # is unknown here: never initialized, or bound on another
        # process before a restart. 404 is the MCP signal for an
        # unknown session; a compliant client re-initializes.
        return [404, json_headers,
                [json_rpc_error(-32_001,
                                "Unknown session; send initialize to start a new one",
                                id: body["id"])]]
      end
      if (limited = charge_session_op(agent, body))
        return limited
      end
    end
  end

  # 6. Branch on streaming preference. Transport-level errors (steps 1-5)
  #    always return plain JSON regardless of the Accept header.
  log_levels = session_log_levels(agent, env)
  if @streaming && env["HTTP_ACCEPT"].to_s.include?("text/event-stream")
    serve_sse(body, agent, log_levels)
  else
    serve_json(body, agent, log_levels)
  end
end

#notify(session_id, method:, params: nil) ⇒ Boolean

Push a server-initiated JSON-RPC NOTIFICATION to a session's open listening stream. This is the public front door for application code to deliver unsolicited notifications/* events (the GET stream must be open for the session — open it client-side with a GET carrying Accept: text/event-stream + Mcp-Session-Id).

The envelope is built server-side as a notification — it never carries an id, which is what distinguishes it from the server-initiated request path (e.g. elicitation/create). A caller wanting an id-bearing request uses the internal subscription_manager.publish seam, not this method.

Parameters:

  • session_id (String) —

    the target session (Mcp-Session-Id).

  • method (String) —

    a non-empty JSON-RPC method, e.g. "notifications/custom".

  • params (Hash, nil) (defaults to: nil) —

    optional params object.

Returns:

  • (Boolean) —

    true if a listening stream received it; false when notifications are disabled or no stream is attached.

Raises:

  • (ArgumentError) —

    when method is blank or not a String.



565
566
567
568
569
570
571
572
573
# File 'lib/parse/agent/mcp_rack_app.rb', line 565

def notify(session_id, method:, params: nil)
  unless method.is_a?(String) && !method.empty?
    raise ArgumentError, "notify: method must be a non-empty String"
  end
  return false unless @subscription_manager
  envelope = { "jsonrpc" => "2.0", "method" => method }
  envelope["params"] = params unless params.nil?
  !!@subscription_manager.publish(session_id, envelope)
end