This PR introduces client-side OAuth support.
# Overall design philosophy
The main new interface introduced to support client-side OAuth is the
`OAuthHandler`. Contrary to its counter-parts in some other SDKs, it is
intentionally small and generic so that it can support most of the OAuth
authorization flow variants. The main `mcp` package purposefully
delegates almost all auth handling to `OAuthHandler` implementations.
This way, the `mcp` package continues to be largely OAuth agnostic.
The `auth` package comes with a default `OAuthHandler` implementation –
`AuthorizationCodeHandler`, which implements the authorization flow
for the `authorization_code` grant type, as defined in the [MCP
specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
It is expected that the `OAuthHandler` implementation granularity will
be roughly per grant type, as this parameter influences the
authorization flow the most.
# Detailed design
## `OAuthHandler` (auth/client.go)
The main interface for the integration consists of two methods:
```go
type OAuthHandler interface {
// TokenSource returns a token source to be used for outgoing requests.
// Returned token source might be nil. In that case, the transport will not
// add any authorization headers to the request.
TokenSource(context.Context) (oauth2.TokenSource, error)
// Authorize is called when an HTTP request results in an error that may
// be addressed by the authorization flow (currently 401 Unauthorized and 403 Forbidden).
// It is responsible for performing the OAuth flow to obtain an access token.
// The arguments are the request that failed and the response that was received for it.
// The headers of the request are available, but the body will have already been consumed
// when Authorize is called.
// If the returned error is nil, TokenSource is expected to return a non-nil token source.
// After a successful call to Authorize, the HTTP request will be retried by the transport.
// The function is responsible for closing the response body.
Authorize(context.Context, *http.Request, *http.Response) error
}
```
`StreamableClientTransport` accepts this interface as a field and uses
the `TokenSource` method to add an `Authorization: Bearer` header to
outgoing requests to the MCP server. If the request fails with `401:
Unauthorized` or `403: Forbidden`, the transport calls `Authorize` to
perform the authorization flow. If `Authorize` returns a non-nil error,
the request is retried once. `Authorize` errors do not result in
termination of the client session (unless they happen during
connection initialization), as some OAuth flows are multi-legged and it should be
acceptable to retry for example when the authorization grant was
received.
*Note:* There was already an `OAuthHandler` type defined as part of a
previous iteration of OAuth support. It was renamed to
`OAuthHandlerLegacy`. This is the only backwards incompatible API change
in the experimental client `auth` part (protected by the
`mcp_go_client_oauth` Go build tag). The cost of replacing previous
usages is deemed worthwhile to maintain clear naming, under the
assumption that the experimental client `auth` part was not widely used.
## `AuthorizationCodeHandler` (auth/authorization_code.go)
This is the `OAuthHandler` implementation that fulfills the [MCP
specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
In particular, in supports:
- Protected Resource Metadata discovery and fetching
- Authorization Server Metadata discovery and fetching
- Client registration
- OpenID Connect metadata document
- Pre-registration
- Dynamic Client Registration
- PKCE
- `client_secret_post`, `client_secret_basic` token endpoint
auth methods
- Automatic refresh of tokens
### Authorization Server redirect
As part of the flow for the `authorization_code` grant type, the client
needs to point the user to the authorization URL, so that they confirm
the access request. This design proposes that it will be supported via a
pluggable dependency that will initiate this process in an
application-specific way:
```go
type AuthorizationCodeHandler struct {
...
// AuthorizationCodeFetcher is a required function called to initiate the authorization flow.
// It is responsible for opening the URL in a browser for the user to start the authorization process.
// It should return the authorization code and state once the Authorization Server
// redirects back to the RedirectURL.
AuthorizationCodeFetcher func(ctx context.Context, args *AuthorizationArgs) (*AuthorizationResult, error)
...
}
```
The function is supposed perform any application specific logic to handle the redirect
from the Authorization Server and return the resulting code and state.
## `oauthex` changes
Some additional/adjusted building blocks that may be useful when
creating `OAuthHandler` implementations are present in the `oauthex`
package:
- `auth_meta.go`: Authorization Server Metadata utilities:
- `GetAuthServerMeta`: get Authorization Server Metadata from a URL
- `dcr.go`: Dynamic Client Registration utilities (unchanged)
- `resource_meta.go`: Protected Resource Metadata utilities:
- `GetProtectedResourceMetadata`: get Protected Resource Metadata from a
URL
- `ParseWWWAuthenticate` – as per name (unchanged)
- [deprecated] `GetProtectedResourceMetadataFromID` and
`GetProtectedResourceMetadataFromHeader` in favor of more generic
`GetProtectedResourceMetadata`. They will be kept under the Go build tag
and removed one version of the SDK in the future.
As part of MCP joining the Linux Foundation, this PR updates licensing
to Apache 2.0 for new contributions while grandfathering existing MIT
code. See modelcontextprotocol/modelcontextprotocol#1994
---------
Co-authored-by: Maciek Kisiel <mkisiel@google.com>
Adds a version compatibility table to the README documenting which SDK
versions support which MCP spec versions.
Fixes#674
---------
Co-authored-by: i586147 <lakshana.goswami@sap.com>
This change adjusts the code example in readme so if you view it in
github it won't show a horizontal scroll bar in code example.
It's trivial change, but I believe it's still an improvement.
Also significantly lessen our warnings, and note that this is a release
candidate, rewrite Acknowledgements to be Acknowledgements /
Alternatives, since other MCP SDKs continue to be actively developed.
This package will hold externally visible parts of internal/oauthex.
For now, just add an alias to the ProtectedResourceMetadata struct. This
lets one write MCP-compliant servers.
Add a framework for feature documentation, and start populating it with
our SDK documentation.
This framework is as follows:
- internal/docs/**.src.md is the markdown source for the docs/
directory.
- The x/example/internal/cmd/weave tool is used to compile these docs to
the top-level docs, supporting both linked code samples and generated
tables of contents.
- The readme-check workflow is updated to check these docs as well.
- The structure of these docs follows the MCP spec.
- Wherever possible, example code is linked from actual Go documentation
examples, so that it is testable.
Some minor modifications to the weave tool were made to support this
framework.
Additionally, partially fill out this documentation with content on
base protocol and client features, as well as troubleshooting help.
Along the way, a bug was encountered that our LoggingTransport was not
concurrency safe. This is fixed with a mutex.
Fixes https://github.com/modelcontextprotocol/go-sdk/issues/466
Fixes https://github.com/modelcontextprotocol/go-sdk/issues/409
Updates https://github.com/modelcontextprotocol/go-sdk/issues/442
Simplify the readme generation to just use go:generate, no longer
depending on Make or bash.
Subsequent CLs will generate more documentation in a similar manner.
For #442
Add example/server/toolschemas, which demonstrates various ways to
customize tool schemas, and illustrates the differences between
ToolHandler and ToolHandlerFor.
Fixes#385Fixes#386
For #368
Replace all occurrences of ServerRequest[*CallToolParams] and other
concrete instantiations with CallToolRequest and the like.
Make the XXXRequest types aliases, to preserve the convenience of
generics for the internal machinery (see shared.go, for example.)
I will expand the aliases in a followup PR.
Change the design of tool handlers by removing genericity from the common path.
- `ToolHandler` gets the args as a `json.RawMessage`. Using Server.AddTool does no unmarshaling or schema validation.
- `ToolHandlerFor`, installed with `AddTool`, are the only generic pieces.
TODO:
uncomment and fix some tests
Handlers and client/server methods take a single request argument
combining the session and params. This slightly simplifies the signature
for handlers, since there is no longer an often-ignored session
argument.
But more importantly, it opens the door to adding more information in
requests, such as auth info and HTTP request headers.
For #243.
As described in #272, there is really no reason for transports to be
closed structs with constructors, since their state must be established
by a call to Connect. Making them open structs simplifies their APIs,
and means that all transports can be extended in the future: we don't
have to create empty Options structs just for the purpose of future
compatibility.
For now, the related constructors and options structs are simply
deprecated (with go:fix directives where possible). A future CL will
remove them prior to the v1.0.0 release.
For #272
Support stateless streamable sessions by adding a GetSessionID function
to StreamableHTTPOptions. If GetSessionID returns "", the session is
stateless, and no validation is performed. This is implemented by
providing the session a trivial initialization state.
To implement this, some parts of #232 (distributed sessions) are copied
over, since they add an API for creating an already-initialized session.
In total, the following new API is added:
- StreamableHTTPOptions.GetSessionID
- ServerSessionOptions (a new parameter to Server.Connect)
- ServerSessionState
- ClientSessionOptions (a new parameter to Client.Connect, for symmetry)
For #10
This fixes#151, which makes it easier for users to easily use GitHub
Codespaces, providing them with a VS Code like environment with their
preferred settings/themes and the required dependencies, all within the
browser.
This PR improves the formatting and internal link structure of both the
main `README.md` and the source file at `internal/readme/README.src.md`.
Changes include:
### 🛠 Changes Made
* Replaced plain-text warning with a GitHub-style admonition block (`>
[!WARNING]`) for improved visibility and consistency with other docs.
Example:
> [!WARNING]
> The SDK should be considered unreleased, and is currently unstable
> and subject to breaking changes. Please test it out and file bug
reports or API
> proposals, but don't use it in real projects. See the issue tracker
for known
> issues and missing features. We aim to release a stable version of the
SDK in
> August, 2025.
* Updated markdown links to use cleaner relative paths:
* Changed `CONTRIBUTING.md` reference to
`[CONTRIBUTING.md](/CONTRIBUTING.md)`
* Updated `examples/` reference to `[examples/](/examples/)`
* Ensured that all updates were mirrored in both the generated and
source README files.
### 📌 Why It Matters
These changes improve the readability and usability of the
documentation, especially when viewed on GitHub. The updated formatting
helps call attention to important warnings, and fixing relative paths
ensures that links work reliably across platforms and contexts.
BREAKING CHANGE
Change the API for adding tools, prompts, resources and resource
templates to a server.
The ServerXXX types are gone along with the plural Add methods
(AddTools, AddPrompts etc.)
Instead there are single Add methods (AddTool, AddPrompt).
In addition, instead of NewServerTool, there is AddTool[In, Out].
Fixes#73.
Fix an example using params.Name instead of params.Arguments.Name. All
credit due to @A11Might for noticing this. Sending a separate PR to keep
the internal/readme source consistent.
After some experience with the flattened version of Content, we see that
it can easily lead to incorrect usage and is a harder API to read.
Therefore, this CL changes back to a design similar to what we had prior
to https://go.dev/cl/672415, though opting to promote content
unmarshalling to the protocol types that use it, which leads to an
overall simpler api.
* mcp: move to 2025-06-18 schema
Add types and fields for the latest MCP schema.
The main challenge here was dealing with the presence of _meta fields
on many types, like Tool, Prompt and Resource.
- Distinguish between the _meta field of a request's params, which
includes a progress token, from the _meta field on other types,
which is simply a map.
- Redefine GetMeta to return a pointer to the map. We wanted to avoid
that, but I don't see a clean way to do so. An alternative would be
to have GetMeta return a map, and SetMeta to set it.
- Provide GetProgressToken for requests only (not notifications or other
types).
- Still to do: deal with the meta and annotation fields of ContentBlock,
which are currently duplicated for Resource and ResourceContents.
* Meta and progress token redesign
Update the README to remove the table of contents, and update the target
stability date from 'mid July' to 'August': mid July does not allow
enough time for testing.
In CL 682976, Alan Donovan correctly points out that the term in the MCP
spec is 'stdio', and therefore the correct capitalization is Stdio.
Change-Id: Ib5bbe04f1a61de886298b4d0adc13aefd6aadd9c
Reviewed-on: https://go-review.googlesource.com/c/tools/+/683075
Reviewed-by: Alan Donovan <adonovan@google.com>
Auto-Submit: Robert Findley <rfindley@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Change CONTRIBUTING.md and README.md to reflect that the MCP SDK is
being moved to github.com/modelcontextprotocol/go-sdk, and to include
content from the 'Governance' section of the design doc. Also, include
the antitrust policy as a section in CONTRIBUTING.md.
Change-Id: I46784d8e57b2a2cab8895593f633d20a2e15c8ba
Reviewed-on: https://go-review.googlesource.com/c/tools/+/682976
Reviewed-by: Sam Thanawalla <samthanawalla@google.com>
Auto-Submit: Robert Findley <rfindley@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
The NewTool and NewPrompt constructors were unidiomatic, because they
returned a ServerTool and ServerPrompt, respectively, rather than a Tool
and Prompt. Rename to be consistent with the constructed object name.
Change-Id: Ife3f16f783368401f792660c4272e1bb5ae61638
Reviewed-on: https://go-review.googlesource.com/c/tools/+/682375
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
CallToolParams.Arguments is any.
Clients can send whatever they want.
Tool authors who create their own ToolHandler (bypassing NewTool)
will receive the arguments as a map[string]any which has been
validated against the input schema.
Tool authors who call NewTool can choose the type that the arguments
unmarshal into.
There is no double-unmarshaling and no downcasting.
There is no way for tool authors to avoid the unmarshal, and no way to
avoid the validation unless the omit an input schema, which is probably
bad for LLMs. If tool authors want this optimization, we can provide
it later.
Change-Id: Ieb201e56c7fb8a23bb1a93b27e946630ec9e79ad
Reviewed-on: https://go-review.googlesource.com/c/tools/+/679595
TryBot-Bypass: Jonathan Amsterdam <jba@google.com>
Auto-Submit: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Robert Findley <rfindley@google.com>