Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable http headers in sse in the context #216

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/mcp/server/lowlevel/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,12 @@ async def _handle_request(
logger.debug(f"Dispatching request of type {type(req).__name__}")

token = None
headers = {}
try:
# TODO: This try/catch and ignoring the type is wrong.
headers = message.request.root.headers # type: ignore
except Exception:
pass
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume we most likely want headers to be extracted from the transport protocol itself. This means providing ways within a session context to access to original request headers for the HTTP Post in the case of SSE. For STDIO this would be empty. If we ever come to the conclusion that headers are absolutely necessary, I think we likely would move to a STDIO transport description that is akin to the header-based JSON-RPC that LSP is doing, which is of the form:

Some-Header: Some-Value
Some-Header: Some-Value
{"jsonrpc": "2.0", ...}

try:
# Set our global state that can be retrieved via
# app.get_request_context()
Expand All @@ -535,6 +541,7 @@ async def _handle_request(
message.request_meta,
session,
lifespan_context,
headers,
)
)
response = await handler(req)
Expand Down
3 changes: 2 additions & 1 deletion src/mcp/server/sse.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,8 @@ async def handle_post_message(
logger.debug(f"Received JSON: {json}")

try:
message = types.JSONRPCMessage.model_validate(json)
message_with_headers = {**json, "headers": dict(request.headers)}
message = types.JSONRPCMessage.model_validate(message_with_headers)
logger.debug(f"Validated client message: {message}")
except ValidationError as err:
logger.error(f"Failed to parse message: {err}")
Expand Down
3 changes: 2 additions & 1 deletion src/mcp/shared/context.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from dataclasses import dataclass
from dataclasses import dataclass, field
from typing import Generic, TypeVar

from mcp.shared.session import BaseSession
Expand All @@ -14,3 +14,4 @@ class RequestContext(Generic[SessionT, LifespanContextT]):
meta: RequestParams.Meta | None
session: SessionT
lifespan_context: LifespanContextT
headers: dict[str, str] = field(default_factory=dict)
1 change: 1 addition & 0 deletions src/mcp/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ class JSONRPCRequest(Request):
jsonrpc: Literal["2.0"]
id: RequestId
params: dict[str, Any] | None = None
headers: dict[str, str] | None = None
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think we would want to add headers to the types. The types are a direct translation of the schema.ts in the specification. Adding headers here would not be compatible with JSON-RPC in it's most used form.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dsp-ant Thank you! That's fair. I was trying to initially do the change such that only the sse file is the one with changes, but here's my problem, and a suggestion for an approach to fix it. Please correct me if my understanding of the code is not complete.

  • The HTTP request is only available in transport layer (sse.py)
  • The only way to pass stuff down from the transport layer to the server implementation is going to be through the streams, which have JSONRPCMessage type
  • We don't want to extend/change the JSONRPCMessage type because it is part of the schema (and honestly it makes sense, since it only applies to certain transports)

To solve this, here are my other 2 suggestions:

  • Inject the metadata (one of which is optional headers) in the params of the JSONRPCMessage
  • Change the streams so that they now hold a new type (a container type with the JSONRPCMessage + meta), where the meta can be anything that is transport-specific?

Let me know what you think.



class JSONRPCNotification(Notification):
Expand Down