Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ public Uni<CommandContext<?>> buildKeyspaceContext(String keyspace, KeyspaceComm
contextBuilderSupplier
.getBuilder(keyspaceSchemaObject)
.withCommandName(command.getClass().getSimpleName())
.withRequestContext(createRequestContext())
.withRequestContext(requestContext)
.build());
}

Expand Down Expand Up @@ -211,20 +211,24 @@ public Uni<ToolResponse> processCollectionCommand(
}

/**
* Process a general or keyspace command and return the CommandResult directly.
*
* <p>The Quarkus MCP Server framework automatically encodes the {@link CommandResult} to JSON via
* its built-in encoder (Jackson), so no manual serialization is needed.
* Process a command and map its result to an MCP tool response.
*
* @param contextUni The command context (from buildGeneralContext or buildKeyspaceContext)
* @param contextUni The command context
* @param command The command to execute
* @return Uni of CommandResult
* @return Uni of ToolResponse
*/
public Uni<ToolResponse> processCommand(Uni<CommandContext<?>> contextUni, Command command) {

return contextUni
.flatMap(
context -> {
.flatMap(context -> executeCommand(context, command))
.map(CommandResult::toToolResponse);
}

private Uni<CommandResult> executeCommand(CommandContext<?> context, Command command) {
// Defer the feature check and processor call so synchronous failures still close the context.
return Uni.createFrom()
.deferred(
() -> {
if (!context.apiFeatures().isFeatureEnabled(ApiFeature.MCP)) {
return Uni.createFrom()
.item(
Expand All @@ -234,7 +238,18 @@ public Uni<ToolResponse> processCommand(Uni<CommandContext<?>> contextUni, Comma
}
return meteredCommandProcessor.processCommand(context, command);
})
.map(CommandResult::toToolResponse);
.onTermination()
.invoke(
() -> {
try {
context.close();
} catch (Exception e) {
LOGGER.error(
"Error closing the command context for requestContext={}",
context.requestContext(),
e);
}
});
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
package io.stargate.sgv2.jsonapi.api.v1.mcp;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.micrometer.core.instrument.MeterRegistry;
import io.quarkiverse.mcp.server.ToolResponse;
import io.quarkus.security.identity.SecurityIdentity;
import io.smallrye.mutiny.Uni;
import io.stargate.sgv2.jsonapi.TestConstants;
import io.stargate.sgv2.jsonapi.api.model.command.CommandContext;
import io.stargate.sgv2.jsonapi.api.model.command.CommandResult;
import io.stargate.sgv2.jsonapi.api.model.command.KeyspaceCommand;
import io.stargate.sgv2.jsonapi.api.model.command.tracing.RequestTracing;
import io.stargate.sgv2.jsonapi.api.request.EmbeddingCredentialsResolver;
import io.stargate.sgv2.jsonapi.api.request.RequestContext;
import io.stargate.sgv2.jsonapi.api.request.tenant.RequestTenantResolver;
import io.stargate.sgv2.jsonapi.config.feature.ApiFeature;
import io.stargate.sgv2.jsonapi.config.feature.ApiFeatures;
import io.stargate.sgv2.jsonapi.metrics.JsonProcessingMetricsReporter;
import io.stargate.sgv2.jsonapi.service.cqldriver.CQLSessionCache;
import io.stargate.sgv2.jsonapi.service.cqldriver.CqlSessionCacheSupplier;
import io.stargate.sgv2.jsonapi.service.embedding.operation.EmbeddingProviderFactory;
import io.stargate.sgv2.jsonapi.service.processor.MeteredCommandProcessor;
import io.stargate.sgv2.jsonapi.service.reranking.operation.RerankingProviderFactory;
import io.stargate.sgv2.jsonapi.service.schema.SchemaObjectCache;
import io.stargate.sgv2.jsonapi.service.schema.SchemaObjectCacheSupplier;
import io.stargate.sgv2.jsonapi.service.schema.collections.CollectionSchemaObject;
import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.inject.Instance;
import java.security.Principal;
import java.time.Duration;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

/**
* Tests for the command context of an MCP tool call. Each call gets one context, and that context
* is closed once however the call ends.
*/
class McpResourceTest {

private static final TestConstants TEST_CONSTANTS = new TestConstants();
private static final Duration TIMEOUT = Duration.ofSeconds(5);
private static final CommandResult OK =
CommandResult.statusOnlyBuilder(RequestTracing.NO_OP).build();

private final MeteredCommandProcessor commandProcessor = mock(MeteredCommandProcessor.class);
private final SchemaObjectCache schemaObjectCache = mock(SchemaObjectCache.class);
private final KeyspaceCommand command = mock(KeyspaceCommand.class);
private final CommandContext<CollectionSchemaObject> context = commandContext();

@Test
void closesContextOnSuccess() throws Exception {
when(commandProcessor.processCommand(context, command)).thenReturn(Uni.createFrom().item(OK));

assertThat(callTool().isError()).isFalse();
verify(context).close();
}

@Test
void closesContextOnFailure() throws Exception {
when(commandProcessor.processCommand(context, command))
.thenReturn(Uni.createFrom().failure(new RuntimeException("processor failed")));

assertThatThrownBy(this::callTool).hasMessage("processor failed");
verify(context).close();
}

@Test
void closesContextWhenProcessorThrows() throws Exception {
// The processor throws before it returns a Uni.
var failure = new IllegalStateException("processor failed");
when(commandProcessor.processCommand(context, command)).thenThrow(failure);

assertThatThrownBy(this::callTool).isSameAs(failure);
verify(context).close();
}

@Test
void closesContextWhenFeatureCheckThrows() throws Exception {
// An unparseable flag value makes the feature check itself throw.
when(context.apiFeatures())
.thenReturn(ApiFeatures.fromConfigAndRequest(Map.of(ApiFeature.MCP, "invalid"), null));

assertThatThrownBy(this::callTool).isInstanceOf(IllegalArgumentException.class);
verifyNoInteractions(commandProcessor);
verify(context).close();
}

@Test
void closesContextWhenFeatureDisabled() throws Exception {
when(context.apiFeatures()).thenReturn(ApiFeatures.empty());

assertThat(callTool().isError()).isTrue();
verifyNoInteractions(commandProcessor);
verify(context).close();
}

@Test
void closesContextOnCancellation() throws Exception {
// A Uni that never emits keeps the call open until the client cancels it.
when(commandProcessor.processCommand(context, command)).thenReturn(Uni.createFrom().nothing());

mcpResource()
.processCommand(Uni.createFrom().item(context), command)
.subscribe()
.with(response -> {}, failure -> {})
.cancel();

verify(context).close();
}

@Test
void closeFailureDoesNotReplaceResult() throws Exception {
doThrow(new Exception("close failed")).when(context).close();
when(commandProcessor.processCommand(context, command)).thenReturn(Uni.createFrom().item(OK));

assertThat(callTool().isError()).isFalse();
verify(context).close();
}

@Test
void closeFailureDoesNotReplaceError() throws Exception {
doThrow(new Exception("close failed")).when(context).close();
when(commandProcessor.processCommand(context, command))
.thenReturn(Uni.createFrom().failure(new RuntimeException("processor failed")));

assertThatThrownBy(this::callTool).hasMessage("processor failed");
verify(context).close();
}

@Test
void keyspaceContextUsesOneRequestContext() {
// The schema lookup and the command context share one request, so the call keeps one
// request ID from start to finish.
var lookupRequest = ArgumentCaptor.forClass(RequestContext.class);
when(schemaObjectCache.getKeyspace(lookupRequest.capture(), any(), any(), eq(true)))
.thenReturn(Uni.createFrom().item(TEST_CONSTANTS.KEYSPACE_SCHEMA_OBJECT));

var keyspaceContext =
mcpResource()
.buildKeyspaceContext(TEST_CONSTANTS.KEYSPACE_NAME, command)
.await()
.atMost(TIMEOUT);

assertThat(keyspaceContext.requestContext()).isSameAs(lookupRequest.getValue());
}

/** Runs one tool call with {@link #context} and {@link #command} and waits for the response. */
private ToolResponse callTool() {
return mcpResource()
.processCommand(Uni.createFrom().item(context), command)
.await()
.atMost(TIMEOUT);
}

@SuppressWarnings("unchecked")
private static CommandContext<CollectionSchemaObject> commandContext() {
CommandContext<CollectionSchemaObject> context = mock(CommandContext.class);
when(context.apiFeatures())
.thenReturn(ApiFeatures.fromConfigAndRequest(Map.of(ApiFeature.MCP, "true"), null));
when(context.requestTracing()).thenReturn(RequestTracing.NO_OP);
return context;
}

/** An {@link McpResource} with enough of an HTTP request to build a real request context. */
private McpResource mcpResource() {
var httpRequest = mock(HttpServerRequest.class);
when(httpRequest.headers()).thenReturn(mock(MultiMap.class));
var routingContext = mock(RoutingContext.class);
when(routingContext.request()).thenReturn(httpRequest);

var principal = mock(Principal.class);
when(principal.getName()).thenReturn("test-token");
var securityIdentity = mock(SecurityIdentity.class);
when(securityIdentity.getPrincipal()).thenReturn(principal);

var tenantResolver = mock(RequestTenantResolver.class);
when(tenantResolver.resolve(any(), any())).thenReturn(TEST_CONSTANTS.TENANT);

var sessionCacheSupplier = mock(CqlSessionCacheSupplier.class);
when(sessionCacheSupplier.get()).thenReturn(mock(CQLSessionCache.class));
var schemaCacheSupplier = mock(SchemaObjectCacheSupplier.class);
when(schemaCacheSupplier.get()).thenReturn(schemaObjectCache);

return new McpResource(
mock(ObjectMapper.class),
commandProcessor,
mock(MeterRegistry.class),
mock(JsonProcessingMetricsReporter.class),
sessionCacheSupplier,
mock(EmbeddingProviderFactory.class),
mock(RerankingProviderFactory.class),
schemaCacheSupplier,
() -> routingContext,
() -> securityIdentity,
instanceOf(tenantResolver),
instanceOf(mock(EmbeddingCredentialsResolver.class)));
}

@SuppressWarnings("unchecked")
private static <T> Instance<T> instanceOf(T value) {
Instance<T> instance = mock(Instance.class);
when(instance.get()).thenReturn(value);
return instance;
}
}