Commit graph

502 commits

Author SHA1 Message Date
Ruturaj Dattatray Kadam
72afbc91bd
auth: change OAuthHandler to take http Request and Response (#603) v1.1.0 v1.1.0-pre.2
Change OAuthHandler signature from func(context.Context,
OAuthHandlerArgs) to func(req *http.Request, res *http.Response).

- Remove OAuthHandlerArgs struct
- Update HTTPTransport to pass req and resp to handler
- Update tests to use new signature
- Handler can now call oauthex.GetProtectedResourceMetadataFromHeader
with proper validation against request URL

This change fixes an impedance mismatch between OAuthHandler and the
protected resource metadata functions of the oauthex package. The new
signature allows handlers to properly validate resource metadata against
the request URL, as required by RFC 9728.

Fixes #600
2025-10-29 10:08:40 -04:00
Robert Findley
d256a9c109
mcp: don't persist failed streamable sessions (#605)
If a stateful streamable session fails to initialize, it is unusable.
Avoid allocating resources by closing the session immediately.

Also:
- Fix a bug where InitializeParams is not guarded with its mutex.
- Fix a resource leak where sessions are persisted with session id "",
even though they are unaddressable.
- Add a relevant benchmark, and update tests.

Fixes #578
2025-10-27 16:29:16 -04:00
Robert Findley
ae6bda692b
mcp: establish the streamable client standalone SSE stream in Connect (#604)
When Connect returns, client should be guaranteed that the streamable
SSE stream is connected.

Fixes #583
2025-10-27 14:03:22 -04:00
Robert Findley
80abbe6171
docs: document support for resumability and redelivery (#606)
Add missing documentation on resumability and redelivery in the
streamable transport.

Indirectly, also update stale transcluded examples. Example changes
weren't causing CI failure as we only trigger the docs check on changes
to the raw docs.
2025-10-27 14:00:58 -04:00
Robert Findley
1a907bcd6f
auth: clone the client request body before roundtripping (#597) v1.1.0-pre.1
RoundTrippers may read and close the body, so be careful to clone before
roundtripping during client oauth, as the request may be issued multiple
times.

Fixes #590
2025-10-23 09:29:53 -04:00
Robert Findley
f01e7faaf5
mcp: add StreamableHTTPOptions.SessionTimeout (#594)
Add a timeout option for the streamable HTTP handler that automatically
cleans up idle sessions.

Also, fix a bug in the streamable client, where we hang on a request
even though the client can never get a response (because the HTTP
request terminated without a response or Last-Event-Id).

Fixes #499
2025-10-23 09:17:20 -04:00
Robert Findley
a5dae3e054
.github: fix staticcheck linting (#599)
Update the test.yml lint job to run linting with Go 1.25, and use the
ambient Go command to run staticcheck. This seems to fix a mysterious
bug where staticcheck was failing, presumably in the Go installation
step. Using the ambient Go command resulted in staticcheck failures,
since some symbols are detected as unused at Go 1.23 due to build tags.
Upgrading the Go version for this job avoids those errors.

Also, use a pinned version of staticcheck (as recommended), to avoid
future failures when new versions are released.
2025-10-22 14:34:51 -04:00
Robert Findley
cfa7a515a9
mcp: add StreamableHTTPOptions.EventStore (#593)
Allow users to enable streamable replay by setting a non-nil event
store.

Updates #587
2025-10-20 14:58:24 -04: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
Robert Findley
8fe64fc389
mcp: fix stale comment on StreamableServerTransport.EventStore (#588)
This was missed in #585.

Updates #580
2025-10-16 13:48:39 -04:00
Robert Findley
104d39c609
mcp: allow disabling stream replay; disable by default (#585)
This CL implements two changes that must be logically connected.

The first is to provide a mechanism for disabling stream replay.
Previously, our documentation stated that if
StreamableServerTransport.EventStore was nil, a default in-memory event
store would be used. In that case, there would be no way to completely
disable stream replay, and as described in #576, there are many cases
where replay is undesirable.

But of course changing the behavior of the transport zero value
implicitly affects its default behavior, and so this CL also implements
the proposal #580: stream replay is disabled by default.

Implementing this change required a significant refactoring, as
previously we were relying on the event store for serialized message
delivery from the JSON-RPC layer to the MCP layer: the connection would
write to the event store, and independently the stream (be it an
incoming POST or replay GET) would iterate and serve messages in the
stream.

In order to achieve the goals of this CL, it was necessary to decouple
storage from delivery. The 'stream' abstraction now tracks a delivery
callback that writes straight to the HTTP response. It would have been
convenient to store the ongoing http.ResponseWriter directly in the
stream (this is how typescript does it), but due to the design of our
EventStore API, only the HTTP handler knows the next event index, so a
'deliver' abstraction was an unfortunate requirement (suggestions for
how to further simplify this are welcome).

More simplification is possible: in particular, as a result of this
refactoring it should be entirely possible to clean up streams once
we've received all responses. Any replay would only need access to the
EventStore, if at all. This is left to a follow-up CL, to limit this
already significant change.

Furthermore, a nice consequence of this refactoring is that, when not
using event storage, servers can get synchronous feedback that message
delivery failed, which should avoid unnecessary work. We can
additionally cancel ongoing requests on early client termination, but
that is also left to a follow-up CL.

Throughout, the terminology 'standalone SSE stream' replaced 'hanging
GET' when referring to the non-replay GET request issued by the client.
This is consistent with other SDKs.

Fixes #576
Updates #580
2025-10-16 12:11:49 -04:00
Friedrich Große
010bdbc64d
mcp: fix goroutine leaks in unit tests (#496)
This PR fixes goroutine leaks in all unit tests.

To find the leaks I integrated https://github.com/uber-go/goleak and I
suggest to keep using it to catch any future regressions.

I used the folowing script to more easily find individual tests which
were leaking goroutines:

```
for t in $(go test -run=Nothing -list=. ./mcp | grep -v ok); do go test ./mcp -run="$t" > /dev/null && echo -n . || echo -e "\nDetected leak: $t"; done
```
2025-10-16 11:13:30 -04:00
Haokun Tang
14e776db6f
mcp: optimize re-marshalling of jsonschema.Schema (#581)
mcp: optimize re-marshalling of jsonschema.Schema

Avoid going through function remarshal when InputSchema/OutputSchema is
of type *jsonschema.Schema.
2025-10-16 09:06:15 -04:00
Robert Findley
9d6e3074f9
mcp: add a explicit test for concurrent streamable sessions (#584)
We seem not to have a test that explicitly exercises concurrent
streamable sessions. Add one.
2025-10-15 14:43:45 -04:00
Ryo Kusnadi
31e97ad69e
Add Check PCKE Support (#563)
Refer To [Issue
473](https://github.com/modelcontextprotocol/go-sdk/issues/473)
Changes:
- Add check for PKCE support via server metadata and return an error if
not supported.
2025-10-14 11:09:28 -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
4c0a015394
.github: fix quoting in docs check error message (#568)
See
https://github.com/modelcontextprotocol/go-sdk/actions/runs/18410542710/job/52464273952?pr=567

Apparently, back-ticked code snippets are not rendered, leading to
non-sensical suggestions from the docs check failure.

Remove back-ticks for now.
2025-10-10 12:03:22 -04:00
Sam Thanawalla
770dbdfe0f
oauthex: update fake oauth server (#564)
This PR adds /mcp, /.well-known/oauth-protected-resource, and /register
to the fake server setup. This will be useful for future tests.

For: #19
2025-10-09 10:38:54 -04:00
Jakub Hrozek
1059f59a27
internal/oauthex: fix GetProtectedResourceMetadataFromHeader validation (#561)
GetProtectedResourceMetadataFromHeader was validating the resource field
against the metadata endpoint URL instead of the original server URL.
Per RFC 9728 section 3.3, the resource field must match the URL that the
client used to make the request to the resource server.

Fixes: #560
2025-10-08 09:30:51 -04:00
Robert Findley
e8685b3022
mcp: don't close stdout when shutting down the stdio transport (#562)
We need to close stdin when the stdio transport is shut down, to unblock
its read loop. However, we don't technically need to close stdout.

Fixes #548
2025-10-07 11:08:38 -04:00
Sam Thanawalla
9348d33b75
oauthex: move internal/oauthex to oauthex (#559)
This PR relocates oauthex and moves DCR logic into dcr.go.

Fixes #558
2025-10-07 08:39:49 -04:00
Robert Findley
547b5c1426
mcp: fix panics with nil logger; ensure test handlers do not panic (#557)
PR 501 added logging to the streamable server, but didn't pass a non-nil
logger to the streamable transport (an oversight). However, tests still
passed due to net/http's panic recovery.

Update test servers to enforce that handlers do not panic, and fix the
panic by:
1. Passing along the configured logger to the session transport.
2. Using ensureLogger in Connect, since we technically allow
StreamableServerTransports to be constructed by the user.

Fixes #556
2025-10-06 13:34:20 -04:00
Adam
4439658dc4 Update readme generation instructions 2025-10-06 10:57:13 -04:00
Suraj Bobade
1dcbf62661
mcp/server: enable server logging (#501)
mcp/server.go: implement server‑side logging

- Thread a *slog.Logger through server paths to improve debuggability
- Introduce no‑op discard handler + ensureLogger so loggers are never
nil
- Use ensured loggers in Server
- address todo comments related to adding logging support

All tests are passing and no functionality should change with this PR

Fixes https://github.com/modelcontextprotocol/go-sdk/issues/170
2025-10-02 14:44:32 -04:00
Konstantin Alikhanov
49047aebe8
Add IOTransport for separate reader/writer (#376)
This commit adds ability to create a mcp.Transport with specific
io.ReadCloser and io.WriteCloser.
Ii is needed when you need create an mcp.Client for mcp.Server launched
in separate process and you need to communicate with it with it's own
stdin/stdout.
2025-09-30 16:24:07 -04:00
Sam Thanawalla
069aae16df
mcp: add client-side OAuth flow (#544)
This is a preliminary implementation of OAuth 2.1 for the client.

When a StreamableClientTransport encounters a 401 Unauthorized response
from the server, it initiates the OAuth flow described in thec
authorization section of the MCP spec

(https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization).
On success, the transport obtains an access token which it passes
to all subsequent requests.

Much remains to be done here:

* Resource Indicators, as described in section 2.5.1 of the MCP spec.

* All of this is unexported, so it is available only to our own
StreamingClientTransport. We should add API so people can use it
with their own transports.

* And, of course, tests. We should test against fake implementations
but also, if we can find any, real reference implementations.

For #19
Co-authored-by: Jonathan Amsterdam <jba@google.com>

---------

Co-authored-by: Jonathan Amsterdam <jba@google.com>
2025-09-30 16:16:30 -04:00
Robert Findley
1c3f38f777
all: more minor cleanup (#547) v1.0.0
Fix broken / missing links.
2025-09-30 16:07:07 -04:00
Robert Findley
6dbf6c6450
all: minor cleanup (#545)
Also fix a flaky test case in TestStreamableServerTransport.
2025-09-30 15:53:00 -04:00
Jonathan Amsterdam
fd0dc9d741
internal/oauthex: address URL attacks in PRM (#539)
Fix Protected Resource Metadata to prevent URL attacks, as described in
the issue.

For #526
2025-09-30 07:33:59 -04:00
Robert Findley
af4bddf3ea
README: remove caveats (#543)
In preparation for the v1.0.0 release, remove caveats from the README.

For #328
2025-09-29 15:33:35 -04:00
Robert Findley
c2381a3fa5
docs: fix broken links (#542) 2025-09-29 14:45:47 -04:00
Chuck Ha
b835e07c26
mcp: fix inconsistent logging new lines (#541)
This change keeps the logging consistent with a new line after each log
whether an error or not.

Fixes #540

Co-authored-by: Chuck Ha <cha@nvidia.com>
2025-09-29 14:19:05 -04:00
Sam Thanawalla
294e1f360c
internal/oauthex: add dynamic client registration (#519)
This CL implements https://www.rfc-editor.org/rfc/rfc7591.html

See
https://github.com/modelcontextprotocol/typescript-sdk/blob/main/src/client/auth.ts
as a reference.

For #493
2025-09-29 09:29:12 -04:00
Robert Findley
ab092510d2
mcp: fix inaccurate package doc (#534) v0.8.0 2025-09-26 14:16:10 -04:00
Robert Findley
1489ba7681
README: update for v0.8.0 (#532)
To be submitted right before the release.
2025-09-26 14:15:59 -04:00
Robert Findley
b2048cd73a
mcp: unexport incidentally exported error codes (#536)
Unexport error codes that were accidentally exported. I don't think it's
possible that they could be useful for users (see #535).

Fixes #535
2025-09-26 14:04:28 -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
Jonathan Amsterdam
5f05f8a43a
many: minor cosmetic changes (#529) 2025-09-25 16:06:24 -04:00
Robert Findley
b9c1419ab0
README: update for v0.7.0 (#528) 2025-09-25 14:23:35 -04:00
Robert Findley
07f6c490c6
mcp: make the streamable client transport less strict (#524) v0.7.0
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
Manuel Ibar
5d64d61974
mcp: fix context propagation in StreamableClientTransport (#514)
## Problem
Context propagation was broken in `StreamableClientTransport` because:
1. `Connect()` used `context.Background()` instead of the parent context
2. `Close()` created a race condition where DELETE requests were
cancelled before completion

## Solution  
- Use parent context when creating the connection context in `Connect()`
- Reorder `Close()` operations to perform cleanup DELETE before
cancelling context

## Impact
- Request-scoped values (auth tokens, trace IDs) now propagate correctly
to background HTTP operations
- Eliminates race condition in cleanup operations  
- Maintains proper Go context semantics

Fixes #513
2025-09-23 12:27:39 -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
Griffin
ef2fc60b5c
docs: adjust example code to remove horizontal scroll bar (#509)
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.
2025-09-22 09:07:17 -04:00
Suraj Bobade
8c42b69817
SSE: Add support for SSE handler options (#508) v0.6.0
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
Jonathan Amsterdam
4e9a387d04
doc: document logging (#497)
For #442.
2025-09-19 11:58:58 -04:00
Robert Findley
84a568bf89
readme: update README for v0.6.0 (#506)
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.
2025-09-19 11:54:10 -04:00
Jonathan Amsterdam
8b6391b173
docs: explain how to get TokenInfo (#502) 2025-09-19 11:50:42 -04:00
Jonathan Amsterdam
4fa725857c
docs: document resources (#505) 2025-09-19 11:46:50 -04:00
Robert Findley
5985a7cbba
docs: document tool support (#498)
Document tool support, and tweak the wording for prompts.

For #442
2025-09-19 10:48:59 -04:00