feat: Add custom context support for MCP transports #819
+171
−16
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds support for passing custom context data from transport implementations to MCP handlers (tools, resources, prompts). This enables server implementations to inject application-specific context like tenant ID, user info, feature flags, etc. without relying on closures or global state.
Motivation and Context
Currently, MCP server implementations have no standard way to pass request-specific context (e.g., authentication info, tenant data) from the transport layer to tool/resource/prompt handlers. This limitation forces developers to use workarounds like closures or session-based context maps.
This PR solves this problem by:
customContext
field toMessageExtraInfo
RequestHandlerExtra
to all handlerssetCustomContext()
method on all transport implementationsImplementation Details
Core Changes:
customContext?: Record<string, unknown>
toMessageExtraInfo
customContext
toRequestHandlerExtra
, passed through in_onrequest
setCustomContext()
method to Transport interfaceTransport Implementations:
handleMessage()
onmessage()
callsUsage Example:
How Has This Been Tested?
Breaking Changes
None. All changes are backwards compatible:
customContext
is an optional fieldsetCustomContext()
is an optional methodTypes of changes
Checklist
Additional context
This feature was developed to address the need for multi-tenant MCP server implementations where request-specific context needs to be available throughout the handler chain. The implementation follows existing patterns in the codebase (similar to how
authInfo
andrequestInfo
are handled) and maintains full backwards compatibility.Implementation Notes:
Future Enhancements: