## Summary
Add DNS rebinding protection that is automatically enabled when requests
arrive via localhost (127.0.0.1, [::1]). This protects against malicious
websites using DNS rebinding to interact with local MCP servers.
(note: this was a claude assisted PR, mostly wanted to see how difficult
passing this test would be for this SDK)
## Design Goal: Secure by Default
The primary goal is to make it difficult to run a localhost server
without these protections by mistake. There are other approaches that
could provide secure defaults (e.g., a helper for `ListenAndServe` that
does the localhost check), but using `http.LocalAddrContextKey` for
runtime detection seemed like the most backwards compatible approach and
least likely to be disabled by accident.
With this implementation:
- **No code changes required** - existing servers get protection
automatically
- **No opt-in needed** - protection activates based on the connection's
local address
- **Explicit opt-out** - users must deliberately set
`DisableLocalhostProtection: true`
## Changes
- Add `DisableLocalhostProtection` option to `StreamableHTTPOptions`
- Add `isLocalhostAddr` and `isLocalhostHost` helper functions
- Validate Host header at start of `ServeHTTP`, rejecting non-localhost
Host headers with 403 Forbidden
## How it works
The protection uses `http.LocalAddrContextKey` to detect the
connection's local address at runtime. When a request arrives via
localhost (127.0.0.1 or [::1]), the handler validates that the Host
header also matches a localhost value. If not, the request is rejected
with 403 Forbidden.
This approach means:
- Protection is enabled for requests arriving via localhost, regardless
of whether the server listens on `127.0.0.1` or `0.0.0.0`
- Requests arriving via non-localhost IPs (e.g., external network
requests) are **not** affected
### Edge case: Reverse proxies
If a reverse proxy (e.g., Envoy, nginx) runs on the same host and
forwards requests to the MCP server via localhost while preserving the
original Host header, those requests would be rejected. In this case,
users should either:
1. Set `DisableLocalhostProtection: true`
2. Configure the proxy to rewrite the Host header to localhost
## Testing
- Added unit tests for `isLocalhostAddr` and `isLocalhostHost` helper
functions
- Added integration tests for the full protection flow
- Verified against the MCP conformance test suite:
- `localhost-host-rebinding-rejected`: PASS
- `localhost-host-valid-accepted`: PASS
## Related
- Spec:
https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise
- TypeScript SDK implementation: `localhostHostValidation()` middleware
- Conformance test: `dns-rebinding-protection` scenario
---------
Co-authored-by: Maciek Kisiel <mkisiel@google.com>
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>
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>
We have a use case for messages larger than 1MB, hence making this
configurable would help.
In order to discover the source of our problems we had to spend some
time investigating, as errors were silently discarded. So we also
included changes to improving surfacing errors .
---------
Co-authored-by: Maciej Kisiel <macio92@gmail.com>
The Form and URL fields in ElicitationCapabilities were missing JSON
struct tags, causing them to serialize as "Form" and "URL" (capitalized)
instead of the lowercase "form" and "url" required by the MCP protocol.
This caused initialization failures when clients advertised elicitation
capabilities, as servers would not recognize the incorrectly-cased keys.
Discovered via downstream issue: https://github.com/docker/cagent/issues/1574
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
Fixes#679
## Changes
- Track last event ID to detect progress in SSE streams
- Only reset retry counter when Last-Event-ID advances
- Fail connection after exceeding maxRetries without progress
This implements Option 2 from the issue: progress-based retry limiting
that prevents infinite retry loops while allowing long-running streams
to continue as long as progress is made.
---------
Signed-off-by: majiayu000 <1835304752@qq.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Maciej Kisiel <mkisiel@google.com>
- implement all non-auth scenarios (client OAuth is not yet supported)
- sse-retry is also implemented, but failing due to a bug in the SDK
- configure client-conformance job in the conformance GitHub action
- create a client-conformance.sh script and rename conformance.sh to server-conformance.sh
- 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
It's causing some servers to fail: #767. I checked with Typescript
implementation and it doesn't do any escaping.
It's still a behavior change, so we'll expose a way to bring back the previous behavior via an env var.
Fixes#238Fixes#767
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>
405 Method Not Allowed responses MUST include an Allow header listing
supported methods, per RFC 9110 Section 15.5.6. This fixes issues with
strict HTTP gateways (like Apigee) that treat 405 responses without an
Allow header as malformed, returning 502 Bad Gateway errors.
## Changes
- **SSEHandler**: Add `Allow: GET, POST` header for unsupported methods
- **StreamableHTTPHandler**: Add Allow header for GET-without-session case:
- Stateless mode: `Allow: POST, DELETE` (GET is never valid)
- Stateful mode: `Allow: GET, POST, DELETE` (GET is valid once you have
a session)
- Add tests to verify Allow header presence in all 405 responses
## RFC 9110 Reference
[Section 15.5.6 (405 Method Not
Allowed)](https://httpwg.org/specs/rfc9110.html#status.405):
> The origin server MUST generate an Allow header field in a 405
response containing a list of the target resource's currently supported
methods.
## Testing
All existing tests pass, plus new tests added:
- `TestSSE405AllowHeader` - verifies SSE handler compliance
- `TestStreamable405AllowHeader` - verifies Streamable handler
compliance in both stateful and stateless modes
---------
Co-authored-by: omgitsads <4619+omgitsads@users.noreply.github.com>
Add a conformance test job to the nightly GitHub workflow that runs
the SDK conformance tests using ./scripts/conformance.sh.
The job:
- Runs on ubuntu-latest
- Sets up Go 1.25
- Sets up Node.js 20 (required for npx)
- Executes the conformance test script
This ensures the SDK is regularly tested against the official MCP
conformance test suite to catch regressions early.
mcp: add DisableStandaloneSSE option to control standalone SSE stream
Currently, StreamableClientTransport always establishes a standalone SSE
connection after initialization to receive server-initiated messages.
While this is useful for receiving notifications like
ToolListChangedNotification, it causes problems in several real-world
scenarios:
1. **Unnecessary resource usage**: Many use cases (for me), especially
in scientific computing scenarios, only require simple request-response
communication. Clients don't need server-initiated notifications, making
the persistent SSE connection wasteful.
2. **Server compatibility issues**: Some third-party MCP servers don't
properly handle GET requests for SSE streams. When the client
automatically tries to establish the SSE connection, it fails or hangs,
blocking the entire connection process. This is particularly problematic
when using third-party servers that cannot be modified. This issue is
similar to what was discussed in issue #634.
3. **Lack of user control**: The MCP specification states that the
standalone SSE stream is optional ("The client MAY issue an HTTP GET"),
but the current SDK implementation doesn't provide a way to opt out.
This implementation is also inconsistent with other MCP SDKs like
github.com/mark3labs/mcp-go, which provides getListeningEnabled control
(defaults to false, requires explicit enablement).
Fixes#728
Co-authored-by: zhaoxin <zhaoxin@pjlab.org.cn>
Issue encountered: the MCP server request was unexpectedly redirected to
an HTML page. Because the client didn’t validate the response
Content-Type, it still entered handleSSE, which then kept treating the
HTML as an SSE stream and repeatedly re-requesting the same
page—creating an infinite request loop.
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>
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
When POST requests in the streamableClientConn return a transient error,
return this error to the caller rather than permanently breaking the
connection.
This is achieved by using the special sentinel ErrRejected error to the
jsonrpc2 layer. In doing so, the change revealed a pre-existing bug:
ErrRejected had the same code as ErrConnectionClosing, and
jsonrpc2.WireError implements errors.Is, so the two sentinel values
could be conflated. This is fixed by using a new internal code.
There's more to do for #683: we should also retry transient errors in
handleSSE.
For #683
The content type header contains full mimetype string which might
contain parameters. The getJSON function doesn't account for this and so
some responses fail to parse although they are perfectly acceptable. For
example
```
curl -vv 'https://github.com/.well-known/oauth-authorization-server/login/oauth'
```
returns a content type header with the value
```
content-type: application/json; charset=utf-8
```
which is perfectly valid but fails in the current logic.
Change CloseSSEStream from func(time.Duration) to
func(CloseSSEStreamArgs) for forward compatibility, allowing new fields
to be added without breaking existing callers.
Debounce and batch notifications for changes in server feature sets
(adding or removing tools, prompts, resources, or resource templates).
This PR handles server-side change notifications only. We could do the
same for client-side notifications (e.g. roots changed), but at the
moment we don't need to.
Fixes#649.
Use URL scheme validation for remaining URL fields in auth
datastructures (AuthServerMeta and ClientRegistrationMetadata), to
prevent XSS attacks.
By comparison, the typescript SDK doesn't validate
introspection_endpoint, and I don't know why. Otherwise the
implementations align.
Fixes#526
I encountered these logs, and they were distracting and noisy. We
shouldn't log to stderr unless configured by the user. Thread through
the logger.
Also, use ensureLogger in the streamable client to simplify call sites.
Updates #708
Updates #684
I am seeing a bug where connections with a Streamable HTTP client are
not reused at all. This makes performance terrible, since each request
establishes a new TCP connection.
I was able to root cause this down to behavior of the `processStream`
function. This sets up a bufio.NewScanner, and waits to get data. Once
we get a message, we abort and *close the connection*.
At this point, there are two paths:
* The bufio reader read the *full* response body to EOF, and then we
closed. This case is fine; we can re-use the idle connection.
* The bufio reader *did not* real the full response body. It may have
read the entire actual data that *would be sent*, but since its
streaming happened to not yet be delivered. In this case, we call
`body.Close()` before an EOF, which causes the HTTP client to not
attempt to re-use the connection.
In my case, the server I am using reliable sends the response over 2 TCP
packets (one with the event, and the other with the closure of the
`chunked` encoding (`0`)). This causes the body to never be fully read.
This PR fixes that case by unconditionally reading the full body before
we close the connection. With this change, I am able to reliably re-use
connections for future requests.
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.