Skip to content

fix: preserve API gateway path prefix in SSE client URL resolution#2243

Open
Varun6578 wants to merge 2 commits intomodelcontextprotocol:mainfrom
Varun6578:fix/sse-gateway-prefix-resolution
Open

fix: preserve API gateway path prefix in SSE client URL resolution#2243
Varun6578 wants to merge 2 commits intomodelcontextprotocol:mainfrom
Varun6578:fix/sse-gateway-prefix-resolution

Conversation

@Varun6578
Copy link
Contributor

Summary

Fixes #795

When an MCP server sits behind a reverse proxy or API gateway that adds a path prefix (e.g., /gateway), the server's endpoint events contain paths without that prefix. The SSE client previously used urljoin() which drops the base URL's path prefix for absolute paths (starting with /), causing incorrect routing through the gateway.

Changes

src/mcp/client/sse.py:

  • Added _resolve_endpoint_url() that detects and preserves reverse proxy/API gateway path prefixes
  • Replaced urljoin(url, sse.data) with _resolve_endpoint_url(url, sse.data) on the endpoint event handler

tests/shared/test_sse.py:

  • Added 8 parametrized test cases for _resolve_endpoint_url() covering:
    • Gateway prefix preservation (the reported bug)
    • Deep gateway prefixes (/org/team/v1/sse)
    • No prefix (preserves existing behavior)
    • Relative paths and absolute URL endpoints

How it works

The function detects gateway prefixes by finding where the endpoint's first path segment appears in the base URL path. Everything before that match is the prefix to preserve.

base_url: https://host/gateway/v1/sse
endpoint: /v1/messages/?session_id=abc
before:   https://host/v1/messages/?session_id=abc        (prefix lost!)
after:    https://host/gateway/v1/messages/?session_id=abc (prefix preserved)

Varun Sharma and others added 2 commits March 7, 2026 13:10
Fixes modelcontextprotocol#795

When an MCP server sits behind a reverse proxy or API gateway that adds
a path prefix, urljoin drops the prefix for absolute endpoint paths
(starting with '/').

Add _resolve_endpoint_url() that detects gateway prefixes by finding
where the endpoint's first path segment appears in the base URL path.
Everything before that match is preserved as the prefix.

Example:
  base_url: https://host/gateway/v1/sse
  endpoint: /v1/messages/?session_id=abc
  before:   https://host/v1/messages/?session_id=abc  (prefix lost)
  after:    https://host/gateway/v1/messages/?session_id=abc

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Reported-by: lizzzcai <https://github.com/lizzzcai>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support for API Gateway Path Prefixes in SSE Client URL Handling

1 participant