Replace closure-based deliver and closeLocked fields with explicit
state:
- pendingJSONMessages: signals JSON mode and collects messages
- w: indicates stream is claimed by HTTP request
- done: signals stream completion (non-nil implies w is non-nil)
- lastIdx, supportsPrimeClose, logger: moved from closures to fields
Add stream methods to consolidate logic:
- close: sends close event and closes done channel
- release: releases stream from HTTP request for resumption
- deliverLocked: writes/stores messages, handles request accounting
Factor out hangResponse to document HTTP response lifecycle.
Inline writeEvent to eliminate confusing pointer-based index
management.
After a deep dive with the team, document areas of the codebase
identified as unclear. For now, this is a documentation-only commit (apart
from one switch of jsonrpc2.Request.ID.IsValid->Request.IsCall). Special
TODO(cleanup) comments are added for additional code changes in
follow-up commits.
Also, include high level doc comments for server and client transports,
in new streamable_server.go and streamable_client.go. Eventually, the
server and client transport logic should be migrated to these files, as
streamable.go has gotten too large. However, we can do that at a future
date, to minimize diff.
Update our Session Hijacking mitigation documentation to describe the
new TokenInfo.UserID field and how the streamable transport uses it to
bind sessions to users.
Fixes#571
The prime and close SSE events (SEP-1699) were added in protocol version
2025-11-25. Only send these events when the client negotiates that
version or later.
- In servePOST, extract protocol version from InitializeParams for
initialize requests, otherwise use the Mcp-Protocol-Version header
- In serveGET/acquireStream, read protocol version from header
- Only set closeLocked callback when prime/close is supported
- Add unexported protocolVersion field to ClientSessionOptions for
testing
Fixes#686
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.
Add a UserID field to auth.TokenInfo that TokenVerifiers can populate
from JWT "sub" claims or token introspection. The streamable HTTP
transport uses this to bind sessions to users, rejecting requests where
the user ID doesn't match the session's original user.
Fixes#589
Add a script to run the official MCP conformance tests against the SDK's
conformance server. The script supports saving results to a custom
directory (--result_dir) and running against a local checkout of the
conformance repo (--conformance_repo).
Document the script in CONTRIBUTING.md.
For #650
Consistent with other SDKs (typescript, python, csharp), add a
SECURITY.md file citing Anthropic's overarching security policy.
This is not specialized to the Go SDK, but seems better than not having
a policy.
After walking through our handling of streamable client context
cancellation (due to encountering a shutdown deadlock), I think I've
settled on a more coherent strategy for handling call cancellation:
- In our call handler, retire the request if the call exits due to
cancellation: the caller will never see the actual result anyway.
- In connectSSE, use the actual request context (the same context used
in Write) for the client request, so that it terminates when the context
is cancelled. Thread through the initialization context for the
standalone SSE request.
Also, a couple minor improvements:
- Use a detached context for the background context of the client
connection. We want to preserve context values (see #513), but it is not
right to cancel the connection after Connect has already returned, if
the context times out.
- Don't use Last-Event-ID != "" as the signal for whether the connectSSE
call is initial: if the standalone SSE stream disconnects without an
event ID, we'll still reconnect it, and don't want to do so without a
delay.
+ tests, updating the streamable client connection test harness to
accomodate the new aspects being exercised.
Fixes#662
Add a section the our CONTRIBUTING.md describing when and how
dependencies should be updated, and the criteria for adding a new
dependency.
Also, add a nightly workflow to run vulncheck.
Fixes#635
This adds a simple schema and checks that the content returned by an
elicitation handler is validated against the schema. Previously, we had
no test coverage checking if the content was validated (i.e., we would
see no test failures if we removed content validation against the
schema).
The bulk of the actual validation logic is handled by the jsonschema
library so adding comprehensive tests covering different schema-features
is redundant, we simply need to see that some validation is happening.
See https://github.com/modelcontextprotocol/go-sdk/issues/625 for more
details on the motivation of this change.
Fixes#625
---------
Co-authored-by: Markus Kusano <kusano@google.com>
This CL implements support for SEP-1699, adding the following new API:
- Event.Retry corresponds to the 'retry' field of a server sent event.
This is used to signal client retry behavior.
- RequestExtra.CloseStream is set by the streamable transport to allow
closing a stream.
The streamable server transport is updated to set CloseStream for calls,
allowing server operations or middleware to close the underlying stream.
If the configured 'reconnectAfter' delay is set, a 'retry' message is
sent prior to terminating the stream.
The streamable client transport is updated to read the configured delay.
Fixes#630
This change updates the MCP client stdio JSON decoder to correctly
handle
both Unix (`\n`) and Windows (`\r\n`) line endings.
Fixes#664
Co-authored-by: qysz <i_zf@qq.com>
Expose the jsonrpc.Error type to allow access to underlying JSON-RPC
error codes. Also, expose common JSON-RPC error codes in the jsonrpc
package, and MCP error codes in the mcp package.
Also, implement support for the MCP URL elicitation required error
(-32042), enabling servers to request out-of-band user authorization and
clients to automatically handle these requests with retry logic.
Server-side:
- Add CodeURLElicitationRequired constant
- Add URLElicitationRequiredError() constructor.
Client-side:
- Add urlElicitationMiddleware to intercept URLElicitationRequired
errors and retry calls.
- Update callElicitationCompleteHandler to signal waiting operations.
- Fix capability advertisement to support both form and URL modes.
Fixes#452Fixes#623
AudioContent should have had a non-pointer receiver, to be consistent
with other content types. Add this to our log of rough edges to
reconsider for v2.
Fixes#641
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
Implement SEP 986, enforcing restrictions on tool names. Since we're
already at v1 we couldn't turn this into a panic, so use an error log
instead. This is consistent with the typescript SDK. A note is left in
our 'rough edges' doc to panic in v2.
Fixes#621
Fixes#636
## Problem
The StreamableClientTransport tries to JSON-decode ALL SSE events,
including ping events sent by servers for keep-alive purposes. This
causes errors like 'invalid character 'p' looking for beginning of
value' when encountering non-JSON event data.
## Solution
Modified processStream to check evt.Name and skip events that are not
'message' events (or unnamed events, which default to 'message' per SSE
spec).
## Changes
- Added event name check in processStream before attempting JSON decode
- Added test case for ping event filtering
- Added test for scanning multiple events including ping events
## Testing
- All existing tests pass
- New tests verify ping events are properly filtered
- Tested with DeepWiki MCP server which sends ping events
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
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
Some MCP servers do not support SSE, but when receiving a request, they
return 400 Bad Request or 404 Not Found instead of the standard 405
Method Not Allowed. The TypeScript and Python SDK ignore this error,
while the Go SDK terminates the session. This patch addresses the issue
in the non-strict mode.
Fixes#610
---------
Signed-off-by: Xie Zhihao <zhihao.xie@bytedance.com>
Start keeping a log of rough edges we've discovered post v1.0.0, so that
they're discoverable (along with their workarounds), and so that we can
fix them in v2.
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
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
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.
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
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
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.
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.
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
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
```
- 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>
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)
```
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