Commit graph go-sdk/examples
Author SHA1 Message Date
Nick Masi
0edc5971cd
Update README.md (#896)
correct the default address of the locally hosted server, according to
`main.go:21` the default is `:8000` not `:8080`

Co-authored-by: Maciej Kisiel <mkisiel@google.com>
2026-04-24 11:47:17 +02:00
Maciej Kisiel
638d404e0d
all: stabilize client OAuth support (#861)
Also fix lint errors that were hidden because of the build tag.
2026-03-31 12:36:31 +02:00
Oleksandr Redko
a1f808c86e
all: modernize code (#868)
Use `go fix ./...` to modernize the code.
2026-03-31 10:58:02 +02:00
Oleksandr Redko
b71a8391a6
all: fix typos (#869)
Grammar issues in docs, comments, and error messages.
2026-03-30 18:43:01 +02:00
Pranav RK
2d43865b97
Enterprise managed authorization (#770)
`auth`, `oauthex`: implement Enterprise Managed Authorization (SEP-990)
This PR implements Enterprise Managed Authorization (SEP-990) for the Go
MCP SDK, enabling MCP Clients and Servers to leverage enterprise
Identity Providers for seamless authorization without requiring users to
authenticate separately to each MCP Server.
 Overview
Enterprise Managed Authorization follows the Identity Assertion
Authorization Grant specification
(draft-ietf-oauth-identity-assertion-authz-grant), implementing a
three-step flow:
1. **Single Sign-On (SSO)**: User authenticates to the MCP Client via
enterprise IdP (Okta, Auth0, Azure AD, etc.)
2. **Token Exchange (RFC 8693)**: Client exchanges ID Token for Identity
Assertion JWT Authorization Grant (ID-JAG) at the IdP
3. **JWT Bearer Grant (RFC 7523)**: Client exchanges ID-JAG for Access
Token at the MCP Server
This enables:
- **For end users**: Single sign-on across MCP Clients and Servers—no
manual connection/authorization per server
- **For enterprise admins**: Centralized visibility and control over
which MCP Servers can be used within the organization
- **For MCP clients**: Automatic token acquisition without user
interaction for each server

Closes:
[#628](https://github.com/modelcontextprotocol/go-sdk/issues/628)

---------

Co-authored-by: Maciej Kisiel <mkisiel@google.com>
2026-03-30 16:29:30 +02:00
Maciej Kisiel
4cdbaaf271
examples: add an example that display header forwarding. (#836)
Created to document the way it can be done discussed in #373.

Fixes #373
2026-03-10 10:57:55 +01:00
Maciej Kisiel
83f7e968f8
examples: fix OAuth client example after latest changes. (#820) 2026-02-27 17:04:25 +01:00
Maciej Kisiel
c9317fb5b7
all: client side OAuth support (#785)
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.
2026-02-27 15:30:13 +01:00
Theodor Nesfeldt Engøy
6a81e5da2a
examples: bind auth-middleware server to localhost by default (#784)
The auth-middleware example currently defaults to `-http :8080`, which
binds to all interfaces (LAN-exposed) by default.

This changes the default to `localhost:8080` and adds a short comment
noting `-http 0.0.0.0:8080` if you intentionally want to expose it.

Rationale: this example serves token-generation endpoints and
authenticated MCP routes; binding loopback by default avoids accidental
exposure while keeping the opt-in remote behavior.

---------

Co-authored-by: Theodor N. Engøy <theodornengoy@Mac.home>
Co-authored-by: Theodor N. Engøy <theodornengoy@eduroam-193-157-246-146.wlan.uio.no>
2026-02-11 10:02:17 +01:00
original-owl
86f8415122
mcp: use synctest for timing-dependent tests (#756)
Converted timing-based tests to use Go 1.25's synctest for instant,
deterministic execution with simulated time.

Moved converted tests to *_go125_test.go files. Tests using real I/O
(exec.Command, httptest) remain timing-based as they require actual
system operations.

Fixes #680

---------

Co-authored-by: i586147 <lakshana.goswami@sap.com>
2026-02-10 10:40:11 +01:00
Suraj Bobade
df4f0d56a4
mcp: use rand.Text and slog.DiscardHandler over internal implementation (#773)
Address TODOs in code requiring go 1.24 as minimum version

mcp/logging.go: use slog.DiscardHandler, over local implementation
mcp/util.go: use rand.Text, over local implementation

Fixes #772
2026-02-03 14:23:59 +01:00
Maciek Kisiel
367175d97b conformance: prepare the conformance test suite
- move the conformance related files to a dedicated directory
- simplify parts of the conformance script
- create a scaffolding for a new GitHub action to run conformance tests
- use the new --output-dir flag from the conformance suite for saving
  results on demand
2026-02-03 09:37:23 +01:00
Robert Findley
411d5a049a
mcp: switch icon theme to named string type (#733)
To be consistent with logging level, use a named string type for icon
themes. This improves readability / discoverability, and is more
consistent.

Updates #552
For #725
2025-12-19 16:44:10 -05:00
Robert Findley
b3399e6730
mcp: use args struct for CloseSSEStream (#718)
Change CloseSSEStream from func(time.Duration) to
func(CloseSSEStreamArgs) for forward compatibility, allowing new fields
to be added without breaking existing callers.
2025-12-11 15:13:38 -05:00
Robert Findley
afe8888129
examples: improve example for listfeatures (#701)
Use an example from the Go SDK, rather than something that requires
node.js.

Fixes #700
2025-12-10 10:26:22 -05:00
Eliya Sadan
d6d6edd6d4
auth: add OAuth 2.0 Protected Resource Metadata handler
This change adds support for RFC 9728 (OAuth 2.0 Protected Resource Metadata)
by introducing a `ProtectedResourceMetadataHandler`.

The handler includes built-in CORS support with `Access-Control-Allow-Origin: *`
by default, as OAuth metadata is public information meant for client discovery.

Documentation includes examples for using custom CORS policies with
popular middleware libraries (github.com/rs/cors and github.com/jub0bs/cors).

The implementation follows RFC 9728 §3.1 for OAuth 2.0 Authorization Server
Metadata discovery, enabling clients to discover protected resource capabilities
and authentication requirements.
2025-12-08 14:54:52 -05:00
Robert Findley
3b42db997c
examples: add a server for conformance testing (#681)
Add a server example for the new conformance test suite.

Passes all current conformance tests.

For #650
2025-12-08 10:32:21 -05:00
Robert Findley
21fb03dd1a
mcp: support url mode elicitation (#646)
Add initial support for URL mode elicitation, by introducing the new
types, as well as both server and client-side validation.

A follow-up CL will add support for ErrURLElicitationRequired.

For #623
2025-11-23 12:58:28 -05:00
Suraj Bobade
faddd764aa
Implement SEP-973 (#570)
mcp/protocol: Implement SEP-973

- Define Icon structure, which includes source, mimeType and sizes.
- sizes is any array of strings. refer
https://github.com/modelcontextprotocol/modelcontextprotocol/pull/1531
- Support setting websiteUrl, icons for mcp.Implementation
- Support setting icons for mcp.Prompt
- Support setting icons for mcp.Tool
- Support setting icons for mcp.Resource

Fixes #552
2025-11-12 16:52:44 -05:00
Spring_MT
35dfcf21c9
examples: Fix SSE streaming issue by moving logging from HTTP to MCP middlewarre (#614)
In `examples/http`, previous HTTP-level logging middleware blocked SSE
streaming because `handler.ServeHTTP()` does not return until the
connection closes for GET requests (SSE streams).
This prevented response headers from being sent to the client.

Changes:
- Replace HTTP-level logging handler with MCP middleware pattern
- Implement logging at the MCP protocol layer using mcp.Middleware
- Add middleware to server using AddReceivingMiddleware()
- Simplify main.go by removing HTTP handler wrapping

This allows SSE streams to work properly while still providing detailed
logging for all MCP protocol-level method calls.

Fixes #632
2025-11-11 11:56:52 -05:00
Robert Findley
8aee8d39bd
mcp: clean up stream metadata after completion (#592)
Address longstanding TODOs to clean up stream metadata after streams are
complete:

- Interpret a missing stream as a complete stream.
- Remove the request->stream mapping when the request completes. Any
writes after that point will fail as there can be no recipient.

Tested using examples/client/loadtest, and updating
TestStreamableTransports to check in-band and out-of-band behavior.
2025-10-20 14:57:56 -04:00
Bo-Yi Wu
920e5a39ba
docs: improve documentation clarity and client integration steps (#567)
- Fix typo in "TroubleShooting" heading, changing it to
"Troubleshooting"
- Improve CLI usage instructions by formatting commands as code blocks
and marking them with "bash"
- Change "Start the Server" to a third-level heading for clarity
- Add additional code examples for real-world client testing and
interaction steps
- Clarify and condense instructions for adding the tool to a popular MCP
client

---------

Signed-off-by: appleboy <appleboy.tw@gmail.com>
Co-authored-by: Robert Findley <rfindley@google.com>
2025-10-13 11:47:58 -04:00
Adriel Velazquez
7a89c31c7a
Correct go run commands to run the logging file (#566)
Readme update and clarification

Targeting only the main.go doesn't add the logging file and causes
errors when finding additional functions.

```
mcp-server-testing main*​ ☸ prod-3-d 33s 
❯ go run main.go server
# command-line-arguments
./main.go:127:24: undefined: LoggingHandler

mcp-server-testing main*​ ☸ prod-3-d 
❯ go run . server      
2025/10/09 11:33:13 MCP server listening on localhost:8000
2025/10/09 11:33:13 Available tool: cityTime (cities: nyc, sf, boston)
```
2025-10-11 10:21:16 -04:00
Robert Findley
964574b818
mcp: allow any value for schemas (#517)
As discussed at length in
https://github.com/modelcontextprotocol/go-sdk/issues/518, coupling our
schema fields to
jsonschema.Schema limits our user's ability to use a different schema
package, and makes it impossible for our client to talk to some
backends.

This CL relaxes the type of `*jsonschema.Schema` fields to be of type
`any`, which is a breaking change but is unlikely to affect most server
code. (It *is* a nontrivial change for clients).

Fixes https://github.com/modelcontextprotocol/go-sdk/issues/518
2025-09-26 11:55:54 -04:00
Robert Findley
07f6c490c6
mcp: make the streamable client transport less strict (#524)
In practice, the streamable client transport was having trouble
connecting to various backends, because they are nonconformant in
various ways.

While it would be nice if all servers conformed to the spec, in practice
there are certain spec violations that are recoverable, and we can and
should recover them. Specifically:

- tolerate 404 instead of 405 for the hanging GET (#393)
- tolerate (=ignore) spurious response body for notifications and
responses, since we know none are expected

Additionally, fix a bug that we weren't parsing Content-Type correctly.

Fixes #521
2025-09-24 14:07:27 -04:00
Jonathan Amsterdam
33ff851ef3
mcp: update to jsonschema that does not validate structs (#511)
Update to the latest jsonschema commit, which removes the ability to
validate structs and changes the type of ForOptions.TypeSchemas.
2025-09-22 15:28:04 -04:00
Suraj Bobade
8c42b69817
SSE: Add support for SSE handler options (#508)
mcp/sse: add support to provide for options for SSE transport

- Add SSEOptions struct to define SSE handler options.
- Update Signature of NewSSEHandler to accept SSEOptions [braking
change]
- Update unit test
- Update example test

Fixes https://github.com/modelcontextprotocol/go-sdk/issues/507,
https://github.com/modelcontextprotocol/go-sdk/issues/503
2025-09-19 13:01:57 -04:00
Robert Findley
28753c9f12
docs: document completion support (#495) 2025-09-18 14:27:35 -04:00
Jonathan Amsterdam
22f86c4dfd
internal/testing: add copyright header (#477) 2025-09-16 21:43:18 -04:00
Jonathan Amsterdam
a082e0764d
go.mod: update to jsonschema v0.2.1 2025-09-09 10:34:38 -04:00
Robert Findley
40b6bd30f1
all: add examples of customizing tool schemas, and clarify documentation (#421)
Add example/server/toolschemas, which demonstrates various ways to
customize tool schemas, and illustrates the differences between
ToolHandler and ToolHandlerFor.

Fixes #385
Fixes #386
For #368
2025-09-05 14:11:11 -04:00
Kason Braley
b774809086
examples: Update and fix outdated (#420)
Update examples/server/rate-limiting to use the same replace directive
strategy as the auth-middleware example, and fix the breakages.

Also remove the unneeded type parameters in examples/client/middleware.
2025-09-05 07:58:26 -04:00
ln-12
4257528dde
mcp: set default logging level to info (#411)
During initialization, the default logging level is set to info allowing
servers to emit logs immediately without waiting for a client to set a
log level.
The updated example shows how to send a notification in the context of
the request.

Fixes #387
2025-09-04 11:10:39 -04:00
Jonathan Amsterdam
92e19c1be8
examples/server/auth-middleware: remove custom middleware (#405)
The additional middleware added the TokenInfo the context.
RequireBearerToken already does that.
2025-09-03 17:27:38 -04:00
Jonathan Amsterdam
d0c5943f25
add HTTP Request to TokenVerifier (#404)
The request might be needed to verify the token.

Fixes #403.
2025-09-03 16:23:42 -04:00
Robert Findley
c76d991f05
examples/server/distributed: address comment in #380
I failed to push my branch before merging #380. Address one minor
comment from that PR.
2025-09-03 11:34:39 -04:00
Jonathan Amsterdam
0bb1a42b53
examples/server/middleware: log tool result (#400)
Log the result of a tool call in the middleware.

This example now fully demonstrates that receiving middleware can
effectively wrap a ToolHandler. That means that one reason for ToolFor
is moot: you don't need to get your hands on the returned ToolHandler in
order to wrap it.
2025-09-03 11:34:02 -04:00
Robert Findley
07b65d76a7
examples/server/distributed: a stateless distributed server
Add an example of a server that proxies HTTP requests to multiple
stateless streamable MCP backends.

For #148
2025-09-02 14:32:12 -04:00
Shusaku Yasoda
a3935c6be2
examples/server: add example MCP server with JWT and API key (#339)
This commit introduces a new example demonstrating the integration of
authentication middleware with an MCP server. The server supports both
JWT token and API key authentication, along with scope-based access
control for various MCP tools. Key features include token generation
endpoints, in-memory API key storage, and a health check endpoint.

New files added:
- `main.go`: Implements the MCP server and authentication logic.
- `go.mod` and `go.sum`: Manage dependencies for the project.
- `README.md`: Provides setup instructions, available endpoints, and
example usage.

This example serves as a reference for implementing secure access to MCP
tools.

Fixes #330
2025-09-02 11:49:46 -04:00
Jonathan Amsterdam
be0a00cd0a
examples/http: update to v0.3.0
Fix build breakage.

Fixes #383.
2025-09-01 09:24:30 -04:00
Adam Koszek
a617dcea31
mcp/examples: HTTP server example with a simple client built-in (#168)
I'm adding a practical example of an MCP with HTTP streaming: both
client and server. Those are useful for testing real-world applications.
2025-08-30 14:30:48 -04:00
Robert Findley
8f11a86898
examples/client: add a loadtest command
Add a loadtest client example, to help confirm performance of our
streamable transport implementation.

For #190
2025-08-29 15:28:05 -04:00
Sam Thanawalla
392f719bd1
mcp/examples: move server example into example folder (#357)
For better organization.
2025-08-26 09:13:30 -04:00
Jonathan Amsterdam
03c5113471
examples/server/memory: fix misleading code (#369)
Tools shouldn't both set StructuredContent and return a typed output.
Remove the assignment.
2025-08-25 16:48:10 -04:00
Rob Findley
9754a2aa86 examples: add an everything example, and simplify hello
Our 'hello' example should be as simple as possible. On the other hand,
we should have an 'everything' example that exercises (almost)
everything we offer.

Using the everything example, I did some final testing using the
inspector. This turned up a couple rough edges related to JSON null that
I addressed by preferring empty slices.

For #33
2025-08-22 14:00:37 -04:00
Sam Thanawalla
d16ce9c25f
mcp/examples: moves middleware examples into example folder (#356)
For better organization.
2025-08-22 11:18:05 -04:00
Sam Thanawalla
42f419fff4
mcp/examples: move elicitation example into example folder (#354)
Rename and move the example into the examples folder.
2025-08-22 11:01:48 -04:00
Jonathan Amsterdam
e3e8aaf024
mcp: align PromptHandler args with other handlers (#348)
The second arg is a GetPromptRequest.

Fixes #300.
2025-08-22 10:44:05 -04:00
Jonathan Amsterdam
6378df6f24
all: remove ServerRequest[T] for concrete T (#342)
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.
2025-08-21 12:10:53 -04:00
Jonathan Amsterdam
5b1f328fd4
mcp: uncomment test, change struct{} to any (#341)
Address comments on #325.
2025-08-21 10:18:52 -04:00