-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feature(auth): Allow delegating OAuth authorization to existing app-level implementations #485
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
base: main
Are you sure you want to change the base?
feature(auth): Allow delegating OAuth authorization to existing app-level implementations #485
Conversation
3352fce
to
96f19fc
Compare
b0e2654
to
1bf3a74
Compare
7758221
to
02f8659
Compare
59b8e7f
to
e544126
Compare
Hi @ihrpr , Sorry for the direct tag. I really appreciate that this is already on the HPR list, and I completely understand you have a lot on your plate. This is just a gentle nudge on the PR - a decision here would really help me move forward on my side, especially if the change is accepted. Thanks again for all the amazing work on the SDK! It’s been a real pleasure working with it over the past three months ;-) |
b8b1a68
to
96d2b31
Compare
One additional detail worth mentioning: the OAuth implementation used by my company (and others as well 😉) includes JWT tokens in the final authentication response. These tokens encode valuable metadata such as user identity, organization context, and more. This is yet another reason to allow client implementations to fully control the authentication flow - they may want to extract and act on this information in ways that are specific to their environment. |
aa7a7b1
to
2be7d47
Compare
👋 Hello, I just wanted to follow up on this PR. I’ve been keeping it up to date over the past month, including adapting to changes like the recent addition of protected resource support (RFC 8707), which this PR now explicitly handles. I really appreciate that it was marked as an HPR and I took that as a sign that it might be reviewed soon. I also sent a (hopefully gentle) nudge to @ihrpr at the time, just to make sure it was on the radar. My main reason for commenting now is to ask for a bit of clarity: I’m more than happy to continue monitoring and updating this PR for as long as there’s a reasonable chance it might be reviewed and potentially merged. I sincerely believe it improves the SDK’s OAuth2 support and brings tangible value to the community. That said, I totally understand if this PR isn’t likely to be accepted either for technical or strategic reasons. However, in this case, I’d rather step back than keep chasing changes unnecessarily. Regardless, thanks again for all the work you do on this project! |
5c574af
to
af6fe5c
Compare
👋 Hello @pcarleton, Hope you had a great week off! We all need to recharge now and then - I’ll actually be off for the next two weeks starting Monday. If you get a chance to take a look at the changes before Friday and spot anything we should tweak, I’ll do my best to fit it in before I go. Let me know! |
1cab5a6
to
c536db1
Compare
Hey @m-paternostro sorry for the delay here, this is on my list, just didn't get to it this week. |
hey @m-paternostro thanks for the patience here. I had a long chat with some other folks (@ihrpr , @dsp-ant, @ochafik ) and we're thinking that an even higher level approach would be better here, and I wanted to see if it'd work for you and if you'd be up for adjusting this PR to tackle it. It'd look something like this:
The idea is then we could support any type of custom auth there, or other request/response munging. Let me know what you think. |
c536db1
to
c0b2c47
Compare
c0b2c47
to
8c1cca7
Compare
Hey @pcarleton - sorry for the delay (was out on PTO as mentioned 😊) I really like the direction this design is heading. I took a pass at implementing the default OAuth and logging wrappers you suggested. And as you were likely signaling, the logic now feels simple and flexible enough that writing custom wrappers is straightforward - no need for a dedicated Btw, for now I kept everything in a single file under shared - we should probably split it, placing the withOAuth in client. Let me know your thoughts! |
6ff7242
to
28d184f
Compare
Add fetchWrapper utilities to allow customization of fetch behavior in MCP transports: - withOAuth: handles authentication with automatic retry on 401 - withLogging: configurable HTTP request/response logging - composeFetchWrappers: utility for combining multiple wrappers
28d184f
to
f906891
Compare
- Rename FetchWrapper type to FetchMiddleware for clarity - Rename withWrappers() to applyMiddleware() following standard middleware patterns - Update parameter names from 'fetch' to 'next' aligning with middleware conventions - Update all test names and variables to use middleware terminology - Add deprecation aliases for backward compatibility This change makes the middleware pattern more recognizable to developers familiar with standard middleware systems like Express, Redux, etc.
- Implement createMiddleware helper that provides cleaner syntax - Separates next handler and request parameters for easier access - Supports all middleware patterns: conditional logic, short-circuiting, response transformation - Add comprehensive test coverage for all use cases - Maintains full compatibility with existing middleware patterns Example usage: const customMiddleware = createMiddleware(async (next, input, init) => { const headers = new Headers(init?.headers); headers.set('X-Custom', 'value'); return next(input, { ...init, headers }); });
- Renamed fetchWrapper.ts to middleware.ts for cleaner naming - Renamed FetchMiddleware type to Middleware (kept deprecated aliases) - Moved middleware files from src/shared/ to src/client/ since this is client-specific - Updated all imports to reflect new location - Fixed test for short-circuit responses The middleware is now properly located in the client directory where it belongs, separate from any server-side middleware. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
@m-paternostro Thank you. This is really good and nearly where we want it. I took the liberty to refactor this and call it middleware and move it to client/ to avoid confusion with middleware in servers. I think this fits the common terminology better. Let me know if that works for you. There is still a lint error around usage of |
@dsp-ant Great news! Your changes look good! Some comments:
Regarding the lint errors, the offending code is related to providing logging for fetch operations, so probably not related to stdio. Would the use of |
An optional provider that clients can use whenever the authentication should be delegated to an existing implementation.
This PR introduces a new optional
DelegatedAuthClientProvider
interface. It allows clients to delegate authentication to existing systems when they already manage authorization through another mechanism (e.g. platform tokens, ambient credentials, preexisting identity systems). When provided, this provider takes precedence over the standard OAuth flow and gives control to the host application for both header injection and authentication handling.Motivation and Context
Some applications embedding the MCP SDK already have fully functional authorization systems. In such cases, the SDK’s built-in OAuth flow can be redundant or even problematic - especially when the app simply needs to know when authorization is required, not how to perform it.
Prior to this change, the only way to hook into the authorization process was by subclassing
StreamableHTTPClientTransport
and/orSSEClientTransport
and overriding enough methods to reimplement the auth flow. However, because the relevant methods are private and deeply interwoven, doing so required replicating a significant amount of transport code - leading to maintenance burden and fragile overrides.This change introduces a clean, focused interface for delegating authentication to external systems without needing to reimplement transport logic. The
DelegatedAuthClientProvider
is implemented directly in both transport classes and takes precedence overOAuthClientProvider
when both are provided.How Has This Been Tested?
The implementation was validated with comprehensive unit tests covering both
StreamableHTTPClientTransport
andSSEClientTransport
. Tests verify header injection, precedence over OAuth providers, 401 handling with successful reauth, and error handling when authentication fails.Breaking Changes
No: the new method is purely opt-in, backward-compatible, and safely ignored if unimplemented. It’s designed to be as simple and low-friction as possible while avoiding the need to subclass transports or bypass internal behavior.
Types of changes
Checklist
Additional context
Notes about the changes:
DelegatedAuthClientProvider
interface is defined insrc/client/auth.ts
withheaders()
andauthorize()
methods.StreamableHTTPClientTransport
andSSEClientTransport
support the optionaldelegatedAuthProvider
option.delegatedAuthProvider
takes precedence overauthProvider
for all authentication operations.