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.
163 lines
5.5 KiB
Markdown
163 lines
5.5 KiB
Markdown
<!-- Autogenerated by weave; DO NOT EDIT -->
|
|
# MCP Go SDK
|
|
|
|
[](https://codespaces.new/modelcontextprotocol/go-sdk)
|
|
|
|
[](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk)
|
|
[](https://scorecard.dev/viewer/?uri=github.com/modelcontextprotocol/go-sdk)
|
|
|
|
This repository contains an implementation of the official Go software
|
|
development kit (SDK) for the Model Context Protocol (MCP).
|
|
|
|
## Package / Feature documentation
|
|
|
|
The SDK consists of several importable packages:
|
|
|
|
- The
|
|
[`github.com/modelcontextprotocol/go-sdk/mcp`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/mcp)
|
|
package defines the primary APIs for constructing and using MCP clients and
|
|
servers.
|
|
- The
|
|
[`github.com/modelcontextprotocol/go-sdk/jsonrpc`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/jsonrpc) package is for users implementing
|
|
their own transports.
|
|
- The
|
|
[`github.com/modelcontextprotocol/go-sdk/auth`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/auth)
|
|
package provides some primitives for supporting OAuth.
|
|
- The
|
|
[`github.com/modelcontextprotocol/go-sdk/oauthex`](https://pkg.go.dev/github.com/modelcontextprotocol/go-sdk/oauthex)
|
|
package provides extensions to the OAuth protocol, such as ProtectedResourceMetadata.
|
|
|
|
The SDK endeavors to implement the full MCP spec. The [`docs/`](/docs/) directory
|
|
contains feature documentation, mapping the MCP spec to the packages above.
|
|
|
|
## Version Compatibility
|
|
|
|
The following table shows which versions of the Go SDK support which versions of the MCP specification:
|
|
|
|
| SDK Version | Latest MCP Spec | All Supported MCP Specs |
|
|
|-----------------|-------------------|----------------------------------------------------|
|
|
| v1.4.0+ | 2025-11-25\* | 2025-11-25\*, 2025-06-18, 2025-03-26, 2024-11-05 |
|
|
| v1.2.0 - v1.3.1 | 2025-11-25\*\* | 2025-11-25\*\*, 2025-06-18, 2025-03-26, 2024-11-05 |
|
|
| v1.0.0 - v1.1.0 | 2025-06-18 | 2025-06-18, 2025-03-26, 2024-11-05 |
|
|
|
|
\* Client side OAuth has experimental support.
|
|
|
|
\*\* Partial support for 2025-11-25 (client side OAuth and Sampling with tools not available).
|
|
|
|
New releases of the SDK target only supported versions of Go. See
|
|
https://go.dev/doc/devel/release#policy for more information.
|
|
|
|
## Getting started
|
|
|
|
To get started creating an MCP server, create an `mcp.Server` instance, add
|
|
features to it, and then run it over an `mcp.Transport`. For example, this
|
|
server adds a single simple tool, and then connects it to clients over
|
|
stdin/stdout:
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
)
|
|
|
|
type Input struct {
|
|
Name string `json:"name" jsonschema:"the name of the person to greet"`
|
|
}
|
|
|
|
type Output struct {
|
|
Greeting string `json:"greeting" jsonschema:"the greeting to tell to the user"`
|
|
}
|
|
|
|
func SayHi(ctx context.Context, req *mcp.CallToolRequest, input Input) (
|
|
*mcp.CallToolResult,
|
|
Output,
|
|
error,
|
|
) {
|
|
return nil, Output{Greeting: "Hi " + input.Name}, nil
|
|
}
|
|
|
|
func main() {
|
|
// Create a server with a single tool.
|
|
server := mcp.NewServer(&mcp.Implementation{Name: "greeter", Version: "v1.0.0"}, nil)
|
|
mcp.AddTool(server, &mcp.Tool{Name: "greet", Description: "say hi"}, SayHi)
|
|
// Run the server over stdin/stdout, until the client disconnects.
|
|
if err := server.Run(context.Background(), &mcp.StdioTransport{}); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
```
|
|
|
|
To communicate with that server, create an `mcp.Client` and connect it to the
|
|
corresponding server, by running the server command and communicating over its
|
|
stdin/stdout:
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"os/exec"
|
|
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
)
|
|
|
|
func main() {
|
|
ctx := context.Background()
|
|
|
|
// Create a new client, with no features.
|
|
client := mcp.NewClient(&mcp.Implementation{Name: "mcp-client", Version: "v1.0.0"}, nil)
|
|
|
|
// Connect to a server over stdin/stdout.
|
|
transport := &mcp.CommandTransport{Command: exec.Command("myserver")}
|
|
session, err := client.Connect(ctx, transport, nil)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer session.Close()
|
|
|
|
// Call a tool on the server.
|
|
params := &mcp.CallToolParams{
|
|
Name: "greet",
|
|
Arguments: map[string]any{"name": "you"},
|
|
}
|
|
res, err := session.CallTool(ctx, params)
|
|
if err != nil {
|
|
log.Fatalf("CallTool failed: %v", err)
|
|
}
|
|
if res.IsError {
|
|
log.Fatal("tool failed")
|
|
}
|
|
for _, c := range res.Content {
|
|
log.Print(c.(*mcp.TextContent).Text)
|
|
}
|
|
}
|
|
```
|
|
|
|
The [`examples/`](/examples/) directory contains more example clients and
|
|
servers.
|
|
|
|
## Contributing
|
|
|
|
We welcome contributions to the SDK! Please see
|
|
[CONTRIBUTING.md](/CONTRIBUTING.md) for details of how to contribute.
|
|
|
|
## Acknowledgements / Alternatives
|
|
|
|
Several third party Go MCP SDKs inspired the development and design of this
|
|
official SDK, and continue to be viable alternatives, notably
|
|
[mcp-go](https://github.com/mark3labs/mcp-go), originally authored by Ed Zynda.
|
|
We are grateful to Ed as well as the other contributors to mcp-go, and to
|
|
authors and contributors of other SDKs such as
|
|
[mcp-golang](https://github.com/metoro-io/mcp-golang) and
|
|
[go-mcp](https://github.com/ThinkInAIXYZ/go-mcp). Thanks to their work, there
|
|
is a thriving ecosystem of Go MCP clients and servers.
|
|
|
|
## License
|
|
|
|
This project is licensed under Apache 2.0 for new contributions, with existing
|
|
code under MIT - see the [LICENSE](./LICENSE) file for details.
|