mcp-context-forge icon indicating copy to clipboard operation
mcp-context-forge copied to clipboard

Forward elicitation/create over fallback per-call upstream MCP ClientSession

Open jonpspri opened this issue 7 months ago • 1 comments

🧭 Type of Feature

  • [x] Enhancement to existing functionality

🧭 Epic

Title: Elicitation pass-through on the fallback per-call upstream session path Goal: Close the last remaining hole in the MCP elicitation pass-through path — when the gateway opens a per-call ClientSession to an upstream MCP server (instead of reusing one through the upstream session registry), elicitation/create requests issued by that server are not delivered to the originating downstream client. Why now: Issue #1985 is closed: the JSON-RPC elicitation/create handler in mcpgateway/main.py (around line 10691) and the response-completion path (around line 4515) cover the documented use case, and the session-affinity reuse path forwards server-initiated requests via NotificationService._forward_request_to_stream. The only path that still drops elicitation today is the fallback per-call branch in tool_service.invoke_tool, which currently opens a ClientSession with no elicitation_callback (and is the path used by admin UI test-invocations, internal /rpc callers, and traced calls that need per-request traceparent headers). PR #4091 attempted this but with a different, broken design (see "Alternatives Considered" below) and is being closed in favor of this scoped follow-up.


🧑🏻‍💻 User Story 1

As an MCP server author I want my elicitation/create requests issued during a tool call to be forwarded to the originating client So that elicitation works regardless of whether the gateway routed my tool call through the upstream session registry or via a per-call fallback session

✅ Acceptance Criteria

Scenario: Elicitation reaches the originating downstream client on the fallback path
  Given the gateway is configured with `MCPGATEWAY_ELICITATION_ENABLED=true`
  And a downstream MCP client has connected and advertised `capabilities.elicitation`
  And a tool invocation is routed via the per-call fallback `ClientSession` (no upstream session reuse)
  When the upstream MCP server issues `elicitation/create` during tool execution
  Then the gateway forwards a JSON-RPC `elicitation/create` to the originating downstream session
  And the request's JSON-RPC id matches the gateway-side pending request id
  And the gateway awaits the downstream client's `elicitation/create` response
  And the gateway returns that result to the upstream MCP server via the SDK
  And no other downstream session receives the elicitation

Scenario: Capability gating
  Given a downstream MCP client did not advertise `capabilities.elicitation`
  When the upstream MCP server issues `elicitation/create` during a fallback per-call invocation
  Then the gateway returns `-32601 Method not found` to the upstream server
  And no broadcast is performed
  And the rejection is logged with the downstream session id

Scenario: Feature disabled
  Given `MCPGATEWAY_ELICITATION_ENABLED=false`
  When an elicitation would otherwise fire on the fallback path
  Then the gateway returns the same error the legacy JSON-RPC handler returns when disabled
  And no `ClientSession.elicitation_callback` is wired

🧑🏻‍💻 User Story 2

As a platform operator I want observability for fallback-path elicitations to match the registry-reuse path So that I can correlate, debug, and rate-limit elicitations uniformly across both code paths

✅ Acceptance Criteria

Scenario: Structured logs and metrics on the fallback path
  Given the fallback path forwards an elicitation
  Then the same structured-log events emitted by the registry-reuse path are emitted (created, delivered, completed/timeout/error)
  And `elicitation.delivered` is emitted ONLY after the wire-level send to the downstream session, not on enqueue
  And the existing `elicitation_*_total` counters and `elicitation_duration_seconds` histogram are incremented

📐 Design Sketch

The minimal correct shape, reusing existing primitives:

sequenceDiagram
    participant Client as Downstream MCP Client
    participant Gateway
    participant Registry as session_registry
    participant Service as elicitation_service
    participant Server as Upstream MCP Server

    Note over Gateway: Fallback per-call branch in tool_service.invoke_tool
    Client->>Gateway: tools/call
    Gateway->>Server: open per-call ClientSession (with elicitation_callback)
    Server->>Gateway: elicitation/create (via SDK callback)
    Gateway->>Service: create pending elicitation (request_id)
    Gateway->>Registry: broadcast(downstream_session_id, JSON-RPC elicitation/create with id=request_id)
    Registry-->>Client: elicitation/create
    Client-->>Gateway: JSON-RPC response (action, content)
    Note over Gateway: existing main.py:4515 path completes pending request
    Gateway->>Service: complete_elicitation(request_id, result)
    Service-->>Gateway: ElicitResult
    Gateway-->>Server: SDK callback returns ElicitResult

Key implementation notes:

  • The two fallback branches are at mcpgateway/services/tool_service.py SSE (~line 5380) and Streamable HTTP (~line 5580) — wherever ClientSession(...) is opened directly without going through get_upstream_session_registry().acquire(...).
  • Reuse session_registry.broadcast(downstream_session_id, envelope) — same primitive as mcpgateway/main.py:10751-10759.
  • Reuse mcpgateway/main.py:4515-4538 for response completion; key by JSON-RPC id matching the ElicitationService pending request_id.
  • The downstream session id is already available on the fallback path via _downstream_session_id_from_request(); no new tool_call_id → session_id registry is needed.
  • Capability check via await session_registry.has_elicitation_capability(downstream_session_id) (already present).
  • Honor mcpgateway_elicitation_enabled, mcpgateway_elicitation_timeout, and the existing concurrency limit.

🔗 MCP Standards Check

  • [x] Change adheres to current MCP 2025-06-18 elicitation specification
  • [x] No breaking changes to existing MCP-compliant integrations
  • [ ] Forward-looking: 2025-11-25 introduces mode: "form" | "url" and URLElicitationRequiredError (-32042). This issue stays scoped to 2025-06-18 form mode. A separate issue should track the 2025-11-25 delta if/when adopted.

🔄 Alternatives Considered

  • PR #4091 attempted this with a parallel design built around a new ToolCallRegistry (process-local tool_call_id → downstream_session_id map) and an SDK-callback path that delegated to ElicitationService.create_elicitation without ever broadcasting. Three blocking issues were identified:
    1. Schema field bug (params.model_dump().get("schema", {}) always returned {} because the field is requestedSchema) — every elicitation failed with -32602 before delivery could even be attempted.
    2. Missing broadcast — create_elicitation only stored a pending future and waited; no code in the new path actually sent elicitation/create to the downstream session.
    3. Process-local ToolCallRegistry is unsafe for the gunicorn-multi-worker / multi-replica deployment topologies the gateway supports.
  • Doing nothing — leaves elicitation broken specifically on admin UI test-invocations, traced tool calls, and internal /rpc callers. Correctness gap rather than a missing feature.
  • Routing fallback through the upstream session registry — possible in principle but the fallback path exists precisely for cases where the registry can't be used (no Mcp-Session-Id, distributed-trace per-request headers, registry not initialized). Forcing those through the registry would regress those flows.

📓 Additional Context

  • Closed PR: #4091
  • Closed issue confirming the broader feature is implemented on main: #1985
  • Existing patterns to reuse:
    • mcpgateway/main.py:10691-10766 (legacy JSON-RPC elicitation/create handler — broadcast pattern)
    • mcpgateway/main.py:4515-4538 (response-completion path)
    • mcpgateway/services/notification_service.py:529-755 (_forward_request_to_stream — pattern for the registry-reuse path; useful reference)
    • mcpgateway/cache/session_registry.py (has_elicitation_capability, broadcast)
  • Tests should include an end-to-end harness driving a real fallback ClientSession against a stub upstream server that fires elicitation/create, with a real downstream SSE / Streamable-HTTP client, asserting the wire path — not just direct complete_elicitation() calls on the service.

jonpspri avatar Apr 26 '26 09:04 jonpspri

We hit this hole in production with ContextForge 1.1.1, so here is a concrete use case in case it helps prioritise it.

Setup

  • Gateway config: MCPGATEWAY_ELICITATION_ENABLED=true, but MCPGATEWAY_SESSION_AFFINITY_ENABLED=false, MCP_SESSION_POOL_ENABLED=false, USE_STATEFUL_SESSIONS=false (single-tenant homelab, stateless gateway on Kubernetes). So every tool call goes through the fallback per-call ClientSession described in this issue.
  • Upstream: gramps-web-mcp 2.11.2 (family-tree server), federated in a virtual server. Its destructive tools (delete_object, merge_objects, undo_change) ask for confirmation through elicitation/create, and we set GRAMPS_CONFIRMATION=required so that an AI agent can never delete or merge records without a human confirming.

What happens

  • The upstream sees the gateway's per-call client as mcp 0.1.0 without the elicitation capability (upstream log: Client mcp 0.1.0 does not support elicitation; delete_object, merge_objects and undo_change refuse to change the tree).
  • Result through the gateway: every destructive call returns not_confirmed, for every downstream client, even though MCPGATEWAY_ELICITATION_ENABLED=true. The confirmation is never relayed, so required turns into "always refused" and the only way to delete is outside MCP.

What would help

  1. Forwarding elicitation/create on the fallback per-call path, as proposed here (or, at minimum, declaring the downstream client's elicitation capability upstream, as in #6640, so servers can tell a capable client from an incapable one).
  2. Until then, a short note in the docs: elicitation pass-through currently requires session affinity / the upstream session registry; with MCPGATEWAY_SESSION_AFFINITY_ENABLED=false it is silently dropped, which is easy to miss because MCPGATEWAY_ELICITATION_ENABLED defaults to true.

Happy to test a fix against this setup.

Shyrka973 avatar Nov 23 '26 11:11 Shyrka973