Skip to content
Draft
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
27 changes: 27 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -415,11 +415,38 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Pin Netty to match Dropwizard's version; prevents conflicts with reactor-netty
pulled in transitively by io.modelcontextprotocol.sdk:mcp -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-bom</artifactId>
<version>${netty.override.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>

<!-- Model Context Protocol Java SDK -->
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp</artifactId>
<version>0.14.1</version>
<exclusions>
<!-- mcp-json-jackson2 registers JacksonJsonSchemaValidatorSupplier via ServiceLoader,
which uses com.networknt:json-schema-validator 1.5.7. The project pins 3.0.2 and
the APIs are incompatible (SpecVersion$VersionFlag was removed in 3.x), causing
NoClassDefFoundError at startup. We exclude the module and supply McpJsonMapper
ourselves via ConsentMcpJsonMapper, which is Jackson-only and networknt-free. -->
<exclusion>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp-json-jackson2</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- Swagger Parser for OpenAPI bundling -->
<dependency>
<groupId>io.swagger.parser.v3</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@
import io.dropwizard.core.setup.Environment;
import io.dropwizard.forms.MultiPartBundle;
import io.dropwizard.jdbi3.bundles.JdbiExceptionsBundle;
import io.modelcontextprotocol.server.McpStatelessSyncServer;
import io.modelcontextprotocol.server.transport.HttpServletStatelessServerTransport;
import io.sentry.Sentry;
import io.sentry.SentryLevel;
import jakarta.servlet.DispatcherType;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.EnumSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
Expand All @@ -47,6 +51,8 @@
import org.broadinstitute.consent.http.health.GCSHealthCheck;
import org.broadinstitute.consent.http.health.SamHealthCheck;
import org.broadinstitute.consent.http.health.SendGridHealthCheck;
import org.broadinstitute.consent.http.mcp.ConsentMcpManaged;
import org.broadinstitute.consent.http.mcp.McpClaimsFilter;
import org.broadinstitute.consent.http.models.AuthUser;
import org.broadinstitute.consent.http.models.DuosUser;
import org.broadinstitute.consent.http.resources.DACAutomationRuleResource;
Expand Down Expand Up @@ -141,6 +147,20 @@ public void run(ConsentConfiguration config, Environment env) {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
env.jersey().register(JerseyGsonProvider.class);

// MCP stateless endpoint (POST /mcp)
// McpClaimsFilter must be registered BEFORE the servlet so it runs first.
// It reads OAUTH2_CLAIM_* headers set by Apache mod_oauth2 and populates ClaimsCache,
// mirroring what RequestHeaderCacheFilter does for Jersey requests on /api.
HttpServletStatelessServerTransport mcpTransport =
injector.getInstance(HttpServletStatelessServerTransport.class);
env.servlets()
.addFilter("mcp-claims-filter", new McpClaimsFilter())
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST), /* isMatchAfterFilter= */ false, "/mcp");
env.servlets().addServlet("mcp-stateless", mcpTransport).addMapping("/mcp");
McpStatelessSyncServer mcpServer = injector.getInstance(McpStatelessSyncServer.class);
env.lifecycle().manage(new ConsentMcpManaged(mcpServer));

// Metric Registry
MetricRegistry metricRegistry = new MetricRegistry();
env.jersey().register(new InstrumentedResourceMethodApplicationListener(metricRegistry));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import io.dropwizard.client.JerseyClientBuilder;
import io.dropwizard.core.Configuration;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.jdbi3.JdbiFactory;
import io.modelcontextprotocol.common.McpTransportContext;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpStatelessSyncServer;
import io.modelcontextprotocol.server.transport.HttpServletStatelessServerTransport;
import jakarta.ws.rs.client.Client;
import org.broadinstitute.consent.http.authentication.AuthorizationHelper;
import org.broadinstitute.consent.http.authentication.DuosUserAuthenticator;
Expand Down Expand Up @@ -47,6 +52,8 @@
import org.broadinstitute.consent.http.db.VoteDAO;
import org.broadinstitute.consent.http.mail.SendGridAPI;
import org.broadinstitute.consent.http.mail.freemarker.FreeMarkerTemplateHelper;
import org.broadinstitute.consent.http.mcp.ConsentMcpJsonMapper;
import org.broadinstitute.consent.http.mcp.ConsentMcpToolProvider;
import org.broadinstitute.consent.http.service.AcknowledgementService;
import org.broadinstitute.consent.http.service.CounterService;
import org.broadinstitute.consent.http.service.DACAutomationRuleService;
Expand Down Expand Up @@ -703,4 +710,47 @@ FeatureFlagDAO providesFeatureFlagDAO() {
OntologyDAO providesOntologyDAO() {
return ontologyDAO;
}

// ── MCP ──────────────────────────────────────────────────────────────────────────────────────

@Provides
@Singleton
HttpServletStatelessServerTransport providesMcpTransport() {
// HttpServletStatelessServerTransport (SDK 0.14.x non-deprecated transport):
// .jsonMapper(McpJsonMapper) – ConsentMcpJsonMapper (networknt-free Jackson impl)
// .messageEndpoint(String) – single endpoint for all MCP traffic (POST /mcp)
// .contextExtractor(extractor) – captures Bearer token per-request into
// McpTransportContext
//
// The contextExtractor stores the Bearer token under key "bearer". Tool handlers receive the
// McpTransportContext as their first BiFunction parameter and call McpAuthHelper.resolveUser()
// to authenticate the caller without relying on ThreadLocal propagation.
return HttpServletStatelessServerTransport.builder()
.jsonMapper(new ConsentMcpJsonMapper(new com.fasterxml.jackson.databind.ObjectMapper()))
.messageEndpoint("/mcp")
.contextExtractor(
req -> {
String auth = req.getHeader("Authorization");
String bearer = (auth != null && auth.startsWith("Bearer ")) ? auth.substring(7) : "";
return McpTransportContext.create(java.util.Map.of("bearer", bearer));
})
.build();
}

@Provides
@com.google.inject.Singleton
McpStatelessSyncServer providesMcpServer(
HttpServletStatelessServerTransport transport, ConsentMcpToolProvider toolProvider) {
// McpServer.sync() is overloaded: sync(McpStatelessServerTransport) →
// StatelessSyncSpecification
// → McpStatelessSyncServer. This overload (and its return type) are not deprecated.
return McpServer.sync(transport)
.serverInfo("consent-mcp", "1.0.0")
.capabilities(
io.modelcontextprotocol.spec.McpSchema.ServerCapabilities.builder()
.tools(/* listChanged= */ false)
.build())
.tools(toolProvider.allTools())
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,27 @@ protected Cache<String, Map<String, String>> getCache() {
return claimsCache.cache;
}

/**
* Resolve an AuthUser from a raw Bearer token. Looks up the token in the ClaimsCache (populated
* by RequestHeaderCacheFilter for Jersey requests, or McpClaimsFilter for MCP SSE requests), then
* builds the AuthUser from the cached OAUTH2_CLAIM headers.
*
* @param bearerToken raw token value without the "Bearer " prefix
* @return resolved AuthUser
* @throws NotAuthorizedException if the token is absent, blank, or not present in the cache
*/
public AuthUser resolveAuthUser(String bearerToken) {
if (bearerToken == null || bearerToken.isBlank()) {
throw new NotAuthorizedException("Missing Bearer token");
}
Map<String, String> headers = getCache().getIfPresent(bearerToken);
if (headers == null) {
throw new NotAuthorizedException(
"Token not recognized — ensure the /mcp path has AuthType oauth2 configured in Apache");
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure we want to return the internals to the user. A better error might be "Your browser sent something we could't understand" as the exception to the user, but maybe log that the condition was reached and decode the bearerToken that was provided so we know the user having the issue?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, this is not intended to be production ready yet. I fully intend to throw this code away if we do go down this path and instead implement this in much smaller phases.

}
return buildAuthUserFromHeaders(headers);
}

protected AuthUser buildAuthUserFromHeaders(Map<String, String> headers) {
String aud = headers.get(ClaimsCache.OAUTH2_CLAIM_aud);
String token = headers.get(ClaimsCache.OAUTH2_CLAIM_access_token);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.broadinstitute.consent.http.mcp;

import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
import java.util.Map;

/**
* No-op {@link JsonSchemaValidator} that accepts all tool-call inputs without validation.
*
* <p>The SDK requires a {@link JsonSchemaValidator} via ServiceLoader. The default implementation
* ({@code DefaultJsonSchemaValidator} in {@code mcp-json-jackson2}) uses {@code
* com.networknt:json-schema-validator 1.5.7}, which conflicts with the project's 3.0.2 pin. We
* register this pass-through instead.
*
* <p>MCP tool schemas in this service are simple Maps used for documentation only; runtime
* validation of tool arguments is not required.
*/
public class ConsentJsonSchemaValidator implements JsonSchemaValidator {

@Override
public ValidationResponse validate(Map<String, Object> schema, Object structuredContent) {
// Pass through — tool-argument validation is not required for DUOS MCP tools.
return ValidationResponse.asValid(String.valueOf(structuredContent));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.broadinstitute.consent.http.mcp;

import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
import io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier;

/**
* ServiceLoader registration for {@link JsonSchemaValidator}.
*
* <p>Registered in {@code
* META-INF/services/io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier}.
*/
public class ConsentJsonSchemaValidatorSupplier implements JsonSchemaValidatorSupplier {

@Override
public JsonSchemaValidator get() {
return new ConsentJsonSchemaValidator();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package org.broadinstitute.consent.http.mcp;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.json.TypeRef;
import java.io.IOException;

/**
* Network-free {@link McpJsonMapper} implementation backed by Jackson's {@link ObjectMapper}.
*
* <p>The SDK ships {@code mcp-json-jackson2} as the default Jackson adapter, but that module
* registers a {@code JacksonJsonSchemaValidatorSupplier} via ServiceLoader which depends on {@code
* com.networknt:json-schema-validator 1.5.7}. This project pins 3.0.2, whose API is incompatible
* (the {@code SpecVersion$VersionFlag} inner class was removed), causing a {@link
* NoClassDefFoundError} at startup.
*
* <p>This implementation provides only the JSON serialisation/deserialisation that the MCP server
* transport and tool dispatching actually need — no schema validation. {@code mcp-json-jackson2} is
* excluded from the Maven dependency tree entirely.
*/
public class ConsentMcpJsonMapper implements McpJsonMapper {

private final ObjectMapper mapper;

public ConsentMcpJsonMapper(ObjectMapper mapper) {
this.mapper = mapper;
}

@Override
public <T> T readValue(String content, Class<T> type) throws IOException {
return mapper.readValue(content, type);
}

@Override
public <T> T readValue(byte[] content, Class<T> type) throws IOException {
return mapper.readValue(content, type);
}

@Override
public <T> T readValue(String content, TypeRef<T> type) throws IOException {
return mapper.readValue(content, mapper.getTypeFactory().constructType(type.getType()));
}

@Override
public <T> T readValue(byte[] content, TypeRef<T> type) throws IOException {
return mapper.readValue(content, mapper.getTypeFactory().constructType(type.getType()));
}

@Override
public <T> T convertValue(Object fromValue, Class<T> type) {
return mapper.convertValue(fromValue, type);
}

@Override
public <T> T convertValue(Object fromValue, TypeRef<T> type) {
return mapper.convertValue(fromValue, mapper.getTypeFactory().constructType(type.getType()));
}

@Override
public String writeValueAsString(Object value) throws IOException {
return mapper.writeValueAsString(value);
}

@Override
public byte[] writeValueAsBytes(Object value) throws IOException {
return mapper.writeValueAsBytes(value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package org.broadinstitute.consent.http.mcp;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.json.McpJsonMapperSupplier;

/**
* ServiceLoader registration for {@link McpJsonMapper}.
*
* <p>The SDK discovers a default {@link McpJsonMapper} via {@code
* ServiceLoader<McpJsonMapperSupplier>} when {@link McpJsonMapper#getDefault()} is called
* internally. Because we excluded {@code mcp-json-jackson2} (to avoid its transitive dependency on
* {@code com.networknt:json-schema-validator 1.5.7} which conflicts with the project's 3.0.2 pin),
* we register this supplier instead so the SDK can find a mapper at runtime.
*
* <p>Registered in {@code META-INF/services/io.modelcontextprotocol.json.McpJsonMapperSupplier}.
*/
public class ConsentMcpJsonMapperSupplier implements McpJsonMapperSupplier {

@Override
public McpJsonMapper get() {
return new ConsentMcpJsonMapper(new ObjectMapper());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package org.broadinstitute.consent.http.mcp;

import io.dropwizard.lifecycle.Managed;
import io.modelcontextprotocol.server.McpStatelessSyncServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Dropwizard {@link Managed} wrapper for {@link McpStatelessSyncServer}.
*
* <p>Dropwizard calls {@link #start()} after all resources are registered and the HTTP server is
* running, and calls {@link #stop()} during graceful shutdown before the JVM exits.
*
* <p>{@code McpStatelessSyncServer} has no explicit {@code start()} method — it begins serving as
* soon as the transport servlet receives connections. {@code closeGracefully()} handles shutdown.
*/
public class ConsentMcpManaged implements Managed {

private static final Logger LOGGER = LoggerFactory.getLogger(ConsentMcpManaged.class);

private final McpStatelessSyncServer server;

public ConsentMcpManaged(McpStatelessSyncServer server) {
this.server = server;
}

@Override
public void start() {
// McpStatelessSyncServer starts automatically when the transport servlet receives connections.
LOGGER.info("Consent MCP server ready");
}

@Override
public void stop() {
LOGGER.info("Stopping Consent MCP server");
try {
server.closeGracefully();
LOGGER.info("Consent MCP server stopped");
} catch (Exception e) {
LOGGER.warn("MCP server did not shut down cleanly", e);
}
}
}
Loading
Loading