Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions conformance-tests/VALIDATION_RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,12 @@
- **Resources (4/6):** list, read-text, read-binary, templates-read
- **Prompts (4/4):** list, simple, with-args, embedded-resource, with-image
- **SSE Transport (2/2):** Multiple streams
- **Security (1/2):** Localhost validation passes
- **Security (2/2):** Localhost validation passes, DNS rebinding protection

### Failing (3/40)

1. **resources-subscribe** - Not implemented in SDK
2. **resources-unsubscribe** - Not implemented in SDK
3. **dns-rebinding-protection** - Missing Host/Origin validation (1/2 checks)

## Client Test Results

Expand All @@ -44,7 +43,6 @@

1. **Resource Subscriptions:** SDK doesn't implement `resources/subscribe` and `resources/unsubscribe` handlers
2. **Client SSE Retry:** Client doesn't parse or respect the `retry:` field, reconnects immediately, and doesn't send Last-Event-ID header
3. **DNS Rebinding Protection:** Missing Host/Origin header validation in server transport

## Running Tests

Expand Down
3 changes: 0 additions & 3 deletions conformance-tests/conformance-baseline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,6 @@ server:
# Resource subscription not implemented in SDK
- resources-subscribe
- resources-unsubscribe

# DNS rebinding protection missing Host/Origin validation
- dns-rebinding-protection

client:
# SSE retry field handling not implemented
Expand Down
4 changes: 2 additions & 2 deletions conformance-tests/server-servlet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ The server has been validated against the official [MCP conformance test suite](
**SSE Transport** (2/2)
- Multiple streams support

⚠️ **Security** (1/2)
- ⚠️ DNS rebinding protection (SDK limitation)
**Security** (2/2)
- DNS rebinding protection

## Features

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,36 @@

import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.server.transport.DefaultServerTransportSecurityValidator;
import io.modelcontextprotocol.server.transport.HttpServletStreamableServerTransportProvider;
import io.modelcontextprotocol.spec.McpSchema.*;
import io.modelcontextprotocol.spec.McpSchema.AudioContent;
import io.modelcontextprotocol.spec.McpSchema.BlobResourceContents;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.CompleteResult;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageRequest;
import io.modelcontextprotocol.spec.McpSchema.CreateMessageResult;
import io.modelcontextprotocol.spec.McpSchema.ElicitRequest;
import io.modelcontextprotocol.spec.McpSchema.ElicitResult;
import io.modelcontextprotocol.spec.McpSchema.EmbeddedResource;
import io.modelcontextprotocol.spec.McpSchema.GetPromptResult;
import io.modelcontextprotocol.spec.McpSchema.ImageContent;
import io.modelcontextprotocol.spec.McpSchema.JsonSchema;
import io.modelcontextprotocol.spec.McpSchema.LoggingLevel;
import io.modelcontextprotocol.spec.McpSchema.LoggingMessageNotification;
import io.modelcontextprotocol.spec.McpSchema.ProgressNotification;
import io.modelcontextprotocol.spec.McpSchema.Prompt;
import io.modelcontextprotocol.spec.McpSchema.PromptArgument;
import io.modelcontextprotocol.spec.McpSchema.PromptMessage;
import io.modelcontextprotocol.spec.McpSchema.PromptReference;
import io.modelcontextprotocol.spec.McpSchema.ReadResourceResult;
import io.modelcontextprotocol.spec.McpSchema.Resource;
import io.modelcontextprotocol.spec.McpSchema.ResourceTemplate;
import io.modelcontextprotocol.spec.McpSchema.Role;
import io.modelcontextprotocol.spec.McpSchema.SamplingMessage;
import io.modelcontextprotocol.spec.McpSchema.ServerCapabilities;
import io.modelcontextprotocol.spec.McpSchema.TextContent;
import io.modelcontextprotocol.spec.McpSchema.TextResourceContents;
import io.modelcontextprotocol.spec.McpSchema.Tool;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
Expand Down Expand Up @@ -39,6 +67,8 @@ public static void main(String[] args) throws Exception {
.builder()
.mcpEndpoint(MCP_ENDPOINT)
.keepAliveInterval(Duration.ofSeconds(30))
.securityValidator(
DefaultServerTransportSecurityValidator.builder().allowedOrigin("http://localhost:*").build())
.build();

// Build server with all conformance test features
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/*
* Copyright 2026-2026 the original author or authors.
*/

package io.modelcontextprotocol.server.transport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.modelcontextprotocol.util.Assert;

/**
* Default implementation of {@link ServerTransportSecurityValidator} that validates the
* Origin header against a list of allowed origins.
*
* <p>
* Supports exact matches and wildcard port patterns (e.g., "http://example.com:*").
*
* @author Daniel Garnier-Moiroux
* @see ServerTransportSecurityValidator
* @see ServerTransportSecurityException
*/
public class DefaultServerTransportSecurityValidator implements ServerTransportSecurityValidator {

private static final String ORIGIN_HEADER = "Origin";

private static final ServerTransportSecurityException INVALID_ORIGIN = new ServerTransportSecurityException(403,
"Invalid Origin header");

private final List<String> allowedOrigins;

/**
* Creates a new validator with the specified allowed origins.
* @param allowedOrigins List of allowed origin patterns. Supports exact matches
* (e.g., "http://example.com:8080") and wildcard ports (e.g., "http://example.com:*")
*/
public DefaultServerTransportSecurityValidator(List<String> allowedOrigins) {
Assert.notNull(allowedOrigins, "allowedOrigins must not be null");
this.allowedOrigins = allowedOrigins;
}

@Override
public void validateHeaders(Map<String, List<String>> headers) throws ServerTransportSecurityException {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (ORIGIN_HEADER.equalsIgnoreCase(entry.getKey())) {
List<String> values = entry.getValue();
if (values != null && !values.isEmpty()) {
validateOrigin(values.get(0));
}
break;
}
}
}

/**
* Validates a single origin value against the allowed origins. Subclasses can
* override this method to customize origin validation logic.
* @param origin The origin header value, or null if not present
* @throws ServerTransportSecurityException if the origin is not allowed
*/
protected void validateOrigin(String origin) throws ServerTransportSecurityException {
// Origin absent = no validation needed (same-origin request)
if (origin == null || origin.isBlank()) {
return;
}

for (String allowed : allowedOrigins) {
if (allowed.equals(origin)) {
return;
}
else if (allowed.endsWith(":*")) {
// Wildcard port pattern: "http://example.com:*"
String baseOrigin = allowed.substring(0, allowed.length() - 2);
if (origin.equals(baseOrigin) || origin.startsWith(baseOrigin + ":")) {
return;
}
}

}

throw INVALID_ORIGIN;
}

/**
* Creates a new builder for constructing a DefaultServerTransportSecurityValidator.
* @return A new builder instance
*/
public static Builder builder() {
return new Builder();
}

/**
* Builder for creating instances of {@link DefaultServerTransportSecurityValidator}.
*/
public static class Builder {

private final List<String> allowedOrigins = new ArrayList<>();

/**
* Adds an allowed origin pattern.
* @param origin The origin to allow (e.g., "http://localhost:8080" or
* "http://example.com:*")
* @return this builder instance
*/
public Builder allowedOrigin(String origin) {
this.allowedOrigins.add(origin);
return this;
}

/**
* Adds multiple allowed origin patterns.
* @param origins The origins to allow
* @return this builder instance
*/
public Builder allowedOrigins(List<String> origins) {
Assert.notNull(origins, "origins must not be null");
this.allowedOrigins.addAll(origins);
return this;
}

/**
* Builds the validator instance.
* @return A new DefaultServerTransportSecurityValidator
*/
public DefaultServerTransportSecurityValidator build() {
return new DefaultServerTransportSecurityValidator(allowedOrigins);
}

}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2024 - 2024 the original author or authors.
* Copyright 2024 - 2026 the original author or authors.
*/

package io.modelcontextprotocol.server.transport;
Expand All @@ -8,6 +8,9 @@
import java.io.IOException;
import java.io.PrintWriter;
import java.time.Duration;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
Expand Down Expand Up @@ -142,6 +145,11 @@ public class HttpServletSseServerTransportProvider extends HttpServlet implement
*/
private KeepAliveScheduler keepAliveScheduler;

/**
* Security validator for validating HTTP requests.
*/
private final ServerTransportSecurityValidator securityValidator;

/**
* Creates a new HttpServletSseServerTransportProvider instance with a custom SSE
* endpoint.
Expand All @@ -153,23 +161,25 @@ public class HttpServletSseServerTransportProvider extends HttpServlet implement
* @param keepAliveInterval The interval for keep-alive pings, or null to disable
* keep-alive functionality
* @param contextExtractor The extractor for transport context from the request.
* @deprecated Use the builder {@link #builder()} instead for better configuration
* options.
* @param securityValidator The security validator for validating HTTP requests.
*/
private HttpServletSseServerTransportProvider(McpJsonMapper jsonMapper, String baseUrl, String messageEndpoint,
String sseEndpoint, Duration keepAliveInterval,
McpTransportContextExtractor<HttpServletRequest> contextExtractor) {
McpTransportContextExtractor<HttpServletRequest> contextExtractor,
ServerTransportSecurityValidator securityValidator) {

Assert.notNull(jsonMapper, "JsonMapper must not be null");
Assert.notNull(messageEndpoint, "messageEndpoint must not be null");
Assert.notNull(sseEndpoint, "sseEndpoint must not be null");
Assert.notNull(contextExtractor, "Context extractor must not be null");
Assert.notNull(securityValidator, "Security validator must not be null");

this.jsonMapper = jsonMapper;
this.baseUrl = baseUrl;
this.messageEndpoint = messageEndpoint;
this.sseEndpoint = sseEndpoint;
this.contextExtractor = contextExtractor;
this.securityValidator = securityValidator;

if (keepAliveInterval != null) {

Expand Down Expand Up @@ -246,6 +256,15 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
return;
}

try {
Map<String, List<String>> headers = extractHeaders(request);
this.securityValidator.validateHeaders(headers);
}
catch (ServerTransportSecurityException e) {
response.sendError(e.getStatusCode(), e.getMessage());
return;
}

response.setContentType("text/event-stream");
response.setCharacterEncoding(UTF_8);
response.setHeader("Cache-Control", "no-cache");
Expand Down Expand Up @@ -311,6 +330,15 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response)
return;
}

try {
Map<String, List<String>> headers = extractHeaders(request);
this.securityValidator.validateHeaders(headers);
}
catch (ServerTransportSecurityException e) {
response.sendError(e.getStatusCode(), e.getMessage());
return;
}

// Get the session ID from the request parameter
String sessionId = request.getParameter("sessionId");
if (sessionId == null) {
Expand Down Expand Up @@ -411,6 +439,21 @@ private void sendEvent(PrintWriter writer, String eventType, String data) throws
}
}

/**
* Extracts all headers from the HTTP servlet request into a map.
* @param request The HTTP servlet request
* @return A map of header names to their values
*/
private Map<String, List<String>> extractHeaders(HttpServletRequest request) {
Map<String, List<String>> headers = new HashMap<>();
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
headers.put(name, Collections.list(request.getHeaders(name)));
}
return headers;
}

/**
* Cleans up resources when the servlet is being destroyed.
* <p>
Expand Down Expand Up @@ -547,6 +590,8 @@ public static class Builder {

private Duration keepAliveInterval;

private ServerTransportSecurityValidator securityValidator = ServerTransportSecurityValidator.NOOP;

/**
* Sets the JsonMapper implementation to use for serialization/deserialization. If
* not specified, a JacksonJsonMapper will be created from the configured
Expand Down Expand Up @@ -621,6 +666,18 @@ public Builder keepAliveInterval(Duration keepAliveInterval) {
return this;
}

/**
* Sets the security validator for validating HTTP requests.
* @param securityValidator The security validator to use. Must not be null.
* @return This builder instance
* @throws IllegalArgumentException if securityValidator is null
*/
public Builder securityValidator(ServerTransportSecurityValidator securityValidator) {
Assert.notNull(securityValidator, "Security validator must not be null");
this.securityValidator = securityValidator;
return this;
}

/**
* Builds a new instance of HttpServletSseServerTransportProvider with the
* configured settings.
Expand All @@ -633,7 +690,7 @@ public HttpServletSseServerTransportProvider build() {
}
return new HttpServletSseServerTransportProvider(
jsonMapper == null ? McpJsonMapper.getDefault() : jsonMapper, baseUrl, messageEndpoint, sseEndpoint,
keepAliveInterval, contextExtractor);
keepAliveInterval, contextExtractor, securityValidator);
}

}
Expand Down
Loading