This is an automated email from the ASF dual-hosted git repository.
rombert pushed a commit to branch master
in repository
https://gitbox.apache.org/repos/asf/sling-org-apache-sling-mcp-server.git
The following commit(s) were added to refs/heads/master by this push:
new 8df7aab SLING-13423 : update MCP Java SDK to 2.1.0 (#22)
8df7aab is described below
commit 8df7aabb1263e5f57d818644563f2193aee00064
Author: Rishabh Kumar <[email protected]>
AuthorDate: Tue Nov 17 14:11:12 2026 +0530
SLING-13423 : update MCP Java SDK to 2.1.0 (#22)
Co-authored-by: Rishabh Kumar <[email protected]>
Co-authored-by: Copilot <[email protected]>
---
README.md | 20 +++
pom.xml | 15 +-
src/main/features/main.json | 6 +-
.../server/impl/LogSafeJsonSchemaValidator.java | 60 ++++++++
.../apache/sling/mcp/server/impl/McpServlet.java | 20 ++-
.../impl/contribs/DiscoveredPromptBuilder.java | 72 +++++----
.../org/apache/sling/mcp/server/McpServerIT.java | 52 ++++++-
.../impl/LogSafeJsonSchemaValidatorTest.java | 70 +++++++++
.../sling/mcp/server/impl/McpServletTest.java | 103 +++++++++++++
.../impl/contribs/DiscoveredPromptBuilderTest.java | 164 ++++++++++++++++++++-
.../mcp/server/itbundle/ItToolContribution.java | 36 ++++-
.../mcp/server/itbundle/McpItSupportBundle.java | 9 ++
.../server/itbundle/McpItSupportBundleTest.java | 84 +++++++++++
13 files changed, 661 insertions(+), 50 deletions(-)
diff --git a/README.md b/README.md
index 0e8ab77..5187c14 100644
--- a/README.md
+++ b/README.md
@@ -46,6 +46,26 @@ To obtain a ready to use target file:
- copy the file `target/slingfeature-tmp/main.json` to your own project
- adjust the metadata from the feature file as needed ( id, title, etc )
+## Contribution compatibility
+
+The server uses the stable MCP Java SDK 2.1.0. Existing contribution bundles
built against SDK 1.x
+must be migrated and rebuilt together with the server; replacing the server
alone does not upgrade
+their OSGi SDK imports. In particular, deploy a compatible build of the MCP
server contributions bundle.
+
+When migrating contributions:
+
+- Supply tool input schemas as maps using `McpSchema.Tool.builder(name,
schema)` instead of the SDK 1.x
+ `JsonSchema` record. Access schema properties through the map API.
+- Use the SDK 2.x required-field builders for prompt arguments, messages, and
tool results.
+- Supply structurally valid JSON schemas. SDK 2.1.0 checks schemas during tool
registration and validates
+ call arguments before invoking handlers. Incorrect types, missing required
properties, and forbidden
+ extra properties return tool errors; null arguments are validated as an
empty object. Correct schemas
+ or client arguments rather than disabling validation.
+- Use nonblank prompt and argument names in repository prompt front matter.
+
+SDK 2.1.0 also requires Jackson annotations/core/databind 2.21 or newer (below
3.0) and Reactor 3.7
+package exports, including `reactor.adapter`. These are provided by the
supplied Sling Starter feature.
+
## Legacy artifact
For applications still using the older slf4j 1.x and javax.servlet APIs a
bundle with the 'legacy' classifier is built.
diff --git a/pom.xml b/pom.xml
index 50572b5..a7de5be 100644
--- a/pom.xml
+++ b/pom.xml
@@ -42,6 +42,7 @@
<properties>
<sling.java.version>17</sling.java.version>
<sling.starter.version>14</sling.starter.version>
+ <mcp.sdk.version>2.1.0</mcp.sdk.version>
<!-- Run with
-Dslingfeature.app.vmOption=-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=30303
for debug mode-->
<slingfeature.app.vmOption />
<!-- Directory for legacy variant classes -->
@@ -137,7 +138,7 @@
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp-core</artifactId>
- <version>1.0.1</version>
+ <version>${mcp.sdk.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
@@ -165,6 +166,16 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.vintage</groupId>
+ <artifactId>junit-vintage-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
@@ -213,7 +224,7 @@
<dependency>
<groupId>io.modelcontextprotocol.sdk</groupId>
<artifactId>mcp-json-jackson2</artifactId>
- <version>1.0.0</version>
+ <version>${mcp.sdk.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/src/main/features/main.json b/src/main/features/main.json
index 5ad6bbc..14123db 100644
--- a/src/main/features/main.json
+++ b/src/main/features/main.json
@@ -5,11 +5,11 @@
"start-order": 25
},
{
- "id": "io.modelcontextprotocol.sdk:mcp-core:1.1.0",
+ "id": "io.modelcontextprotocol.sdk:mcp-core:2.1.0",
"start-order": 25
},
{
- "id": "io.modelcontextprotocol.sdk:mcp-json-jackson2:1.1.0",
+ "id": "io.modelcontextprotocol.sdk:mcp-json-jackson2:2.1.0",
"start-order": 25
},
{
@@ -21,7 +21,7 @@
"start-order": 25
},
{
- "id": "com.networknt:json-schema-validator:2.0.0",
+ "id": "com.networknt:json-schema-validator:2.0.4",
"start-order": 25
},
{
diff --git
a/src/main/java/org/apache/sling/mcp/server/impl/LogSafeJsonSchemaValidator.java
b/src/main/java/org/apache/sling/mcp/server/impl/LogSafeJsonSchemaValidator.java
new file mode 100644
index 0000000..44306fb
--- /dev/null
+++
b/src/main/java/org/apache/sling/mcp/server/impl/LogSafeJsonSchemaValidator.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.mcp.server.impl;
+
+import java.util.Map;
+import java.util.Objects;
+
+import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
+
+/**
+ * Escapes caller-controlled line breaks before the SDK logs validation
diagnostics.
+ */
+record LogSafeJsonSchemaValidator(JsonSchemaValidator delegate) implements
JsonSchemaValidator {
+
+ LogSafeJsonSchemaValidator {
+ Objects.requireNonNull(delegate, "JSON schema validator must not be
null");
+ }
+
+ /**
+ * Preserves input validation while keeping its diagnostic on one log line.
+ */
+ @Override
+ public ValidationResponse validate(Map<String, Object> schema, Object
structuredContent) {
+ return escapeDiagnostic(delegate.validate(schema, structuredContent));
+ }
+
+ /**
+ * Retains meta-schema checks when validating contributed tool schemas.
+ */
+ @Override
+ public ValidationResponse validateSchema(Map<String, Object> schema) {
+ return escapeDiagnostic(delegate.validateSchema(schema));
+ }
+
+ private static ValidationResponse escapeDiagnostic(ValidationResponse
response) {
+ if (response.errorMessage() == null) {
+ return response;
+ }
+ return new ValidationResponse(
+ response.valid(),
+ response.errorMessage().replace("\r", "\\r").replace("\n",
"\\n"),
+ response.jsonStructuredOutput());
+ }
+}
diff --git a/src/main/java/org/apache/sling/mcp/server/impl/McpServlet.java
b/src/main/java/org/apache/sling/mcp/server/impl/McpServlet.java
index 2cdfc72..3e8c954 100644
--- a/src/main/java/org/apache/sling/mcp/server/impl/McpServlet.java
+++ b/src/main/java/org/apache/sling/mcp/server/impl/McpServlet.java
@@ -149,7 +149,7 @@ public class McpServlet extends SlingAllMethodsServlet {
syncServer = McpServer.sync(transportProvider)
.serverInfo(serverName, serverVersion)
.jsonMapper(jsonMapperSupplier.get())
- .jsonSchemaValidator(jsonSchemaValidatorSupplier.get())
+ .jsonSchemaValidator(new
LogSafeJsonSchemaValidator(jsonSchemaValidatorSupplier.get()))
.instructions(config.instructions())
.completions(completions)
.capabilities(ServerCapabilities.builder()
@@ -164,10 +164,18 @@ public class McpServlet extends SlingAllMethodsServlet {
// cursor tries to register for resource updates even if we don't
advertise that capability
tryRegisterNoopResourcesSubscribeHandler();
- contributions.stream()
- .map(McpServerContribution::getSyncToolSpecification)
- .flatMap(List::stream)
- .forEach(syncTool -> syncServer.addTool(syncTool));
+ for (var contribution : contributions) {
+ for (var tool : contribution.getSyncToolSpecification()) {
+ try {
+ syncServer.addTool(tool);
+ } catch (IllegalArgumentException e) {
+ logger.error(
+ "Rejected MCP tool from contribution {}: {}",
+ contribution.getClass().getName(),
+ String.valueOf(e.getMessage()).replace("\r",
"\\r").replace("\n", "\\n"));
+ }
+ }
+ }
contributions.stream()
.map(McpServerContribution::getSyncResourceSpecification)
@@ -211,7 +219,7 @@ public class McpServlet extends SlingAllMethodsServlet {
protected void bindPrompt(DiscoveredPrompt prompt, Map<String, Object>
properties) {
syncServer.addPrompt(new SyncPromptSpecification(prompt.asPrompt(),
(c, r) -> {
var messages = prompt.getPromptMessages(c, r);
- return new McpSchema.GetPromptResult(null, messages);
+ return McpSchema.GetPromptResult.builder(messages).build();
}));
}
diff --git
a/src/main/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilder.java
b/src/main/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilder.java
index 99f2335..06b8165 100644
---
a/src/main/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilder.java
+++
b/src/main/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilder.java
@@ -49,6 +49,10 @@ class DiscoveredPromptBuilder {
public DiscoveredPrompt buildPrompt(Resource prompt, String promptName)
throws IOException {
+ if (promptName == null || promptName.isBlank()) {
+ throw new IOException("Prompt name must not be blank");
+ }
+
Parser parser = Parser.builder()
.extensions(List.of(YamlFrontMatterExtension.create()))
.build();
@@ -70,32 +74,39 @@ class DiscoveredPromptBuilder {
List<PromptArgument> arguments = new ArrayList<>();
- visitor.getData().entrySet().stream()
- .filter(e -> e.getKey().startsWith("argument."))
- .forEach(e -> {
- String argName =
e.getKey().substring("argument.".length());
- List<String> values = e.getValue();
- String argTitle = null;
- String argDesc = null;
- boolean argRequired = false;
- for (String value : values) {
-
- if (value.startsWith("title:")) {
- argTitle =
value.substring("title:".length()).trim();
- } else if (value.startsWith("description:")) {
- argDesc =
-
value.substring("description:".length()).trim();
- } else if (value.startsWith("required:")) {
- String argRequiredRaw =
-
value.substring("required:".length()).trim();
- argRequired = Boolean.valueOf(argRequiredRaw);
- } else {
- logger.warn("Unknown argument property in
prompt {}: {}", promptName, value);
- }
- }
+ for (var e : visitor.getData().entrySet()) {
+ if (!e.getKey().startsWith("argument.")) {
+ continue;
+ }
+ String argName = e.getKey().substring("argument.".length());
+ if (argName.isBlank()) {
+ throw new IOException("Prompt argument name must not be
blank; use argument.<name>");
+ }
+ List<String> values = e.getValue();
+ String argTitle = null;
+ String argDesc = null;
+ boolean argRequired = false;
+ for (String value : values) {
+
+ if (value.startsWith("title:")) {
+ argTitle = value.substring("title:".length()).trim();
+ } else if (value.startsWith("description:")) {
+ argDesc =
value.substring("description:".length()).trim();
+ } else if (value.startsWith("required:")) {
+ String argRequiredRaw =
+ value.substring("required:".length()).trim();
+ argRequired = Boolean.valueOf(argRequiredRaw);
+ } else {
+ logger.warn("Unknown argument property in prompt {}:
{}", promptName, value);
+ }
+ }
- arguments.add(new PromptArgument(argName, argTitle,
argDesc, argRequired));
- });
+ arguments.add(PromptArgument.builder(argName)
+ .title(argTitle)
+ .description(argDesc)
+ .required(argRequired)
+ .build());
+ }
return new RepositoryPrompt(prompt.getPath(), promptName, title,
description, arguments);
}
@@ -156,7 +167,10 @@ class DiscoveredPromptBuilder {
}
}
- return List.of(new PromptMessage(Role.ASSISTANT, new
TextContent(contents)));
+ return List.of(PromptMessage.builder(
+ Role.ASSISTANT,
+ TextContent.builder(contents).build())
+ .build());
}
} catch (IOException e) {
return List.of();
@@ -165,7 +179,11 @@ class DiscoveredPromptBuilder {
@Override
public Prompt asPrompt() {
- return new Prompt(promptName, promptTitle, promptDescription,
arguments);
+ return Prompt.builder(promptName)
+ .title(promptTitle)
+ .description(promptDescription)
+ .arguments(arguments)
+ .build();
}
}
}
diff --git a/src/test/java/org/apache/sling/mcp/server/McpServerIT.java
b/src/test/java/org/apache/sling/mcp/server/McpServerIT.java
index c4c5637..7144246 100644
--- a/src/test/java/org/apache/sling/mcp/server/McpServerIT.java
+++ b/src/test/java/org/apache/sling/mcp/server/McpServerIT.java
@@ -19,6 +19,7 @@
package org.apache.sling.mcp.server;
import java.net.URI;
+import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
@@ -80,7 +81,7 @@ class McpServerIT {
private McpSyncClient initializeMcpClient(String basicAuthHeader) {
- return await("mcp client initializes")
+ return await("mcp client initializes with the IT contribution")
.atMost(AWAIT_TIMEOUT)
.pollInterval(AWAIT_POLL_INTERVAL)
.ignoreExceptions()
@@ -90,6 +91,11 @@ class McpServerIT {
try {
candidate.initialize();
+ if (candidate.listTools().tools().stream()
+ .noneMatch(tool ->
ItToolContribution.TOOL_NAME.equals(tool.name()))) {
+ candidate.close();
+ return null;
+ }
return candidate;
} catch (RuntimeException e) {
candidate.close();
@@ -103,11 +109,12 @@ class McpServerIT {
HttpClientStreamableHttpTransport transport =
HttpClientStreamableHttpTransport.builder(
"http://localhost:" + slingPort)
.endpoint(MCP_ENDPOINT)
- .customizeRequest(rb -> rb.header("Authorization",
basicAuthHeader))
+
.requestBuilder(HttpRequest.newBuilder().header("Authorization",
basicAuthHeader))
.build();
return McpClient.sync(transport)
- .clientInfo(new McpSchema.Implementation("mcp-server-it",
"1.0"))
+ .clientInfo(
+ McpSchema.Implementation.builder("mcp-server-it",
"1.0").build())
.requestTimeout(Duration.ofSeconds(30))
.build();
}
@@ -148,5 +155,44 @@ class McpServerIT {
.first()
.isInstanceOfSatisfying(McpSchema.TextContent.class, tc ->
assertThat(tc.text())
.isEqualTo(ItToolContribution.TOOL_RESPONSE));
+
+ McpSchema.CallToolResult invalidResult = mcpClient.callTool(
+ new McpSchema.CallToolRequest(ItToolContribution.TOOL_NAME,
Map.of("unexpected", "value")));
+
+ assertThat(invalidResult.isError())
+ .as("SDK rejects arguments that do not match the tool input
schema")
+ .isTrue();
+ }
+
+ @Test
+ void typedToolArgumentsAreValidated() {
+ McpSchema.CallToolResult valid = mcpClient.callTool(
+ new
McpSchema.CallToolRequest(ItToolContribution.TYPED_TOOL_NAME, Map.of("name",
"Sling")));
+ assertThat(valid.isError()).isFalse();
+ assertThat(valid.content())
+ .singleElement()
+ .isInstanceOfSatisfying(McpSchema.TextContent.class, text ->
assertThat(text.text())
+ .isEqualTo(ItToolContribution.TOOL_RESPONSE + "
Sling"));
+
+ McpSchema.CallToolResult wrongType = mcpClient.callTool(
+ new
McpSchema.CallToolRequest(ItToolContribution.TYPED_TOOL_NAME, Map.of("name",
42)));
+ assertThat(wrongType.isError()).isTrue();
+
+ McpSchema.CallToolResult missing =
+ mcpClient.callTool(new
McpSchema.CallToolRequest(ItToolContribution.TYPED_TOOL_NAME, null));
+ assertThat(missing.isError()).isTrue();
+ }
+
+ @Test
+ void validationDiagnosticsEscapeCallerControlledLineBreaks() {
+ McpSchema.CallToolResult result = mcpClient.callTool(
+ new McpSchema.CallToolRequest(ItToolContribution.TOOL_NAME,
Map.of("unexpected\r\nFORGED", "value")));
+
+ assertThat(result.isError()).isTrue();
+ assertThat(result.content())
+ .singleElement()
+ .isInstanceOfSatisfying(McpSchema.TextContent.class, text ->
assertThat(text.text())
+ .contains("unexpected\\r\\nFORGED")
+ .doesNotContain("\r", "\n"));
}
}
diff --git
a/src/test/java/org/apache/sling/mcp/server/impl/LogSafeJsonSchemaValidatorTest.java
b/src/test/java/org/apache/sling/mcp/server/impl/LogSafeJsonSchemaValidatorTest.java
new file mode 100644
index 0000000..7bd976b
--- /dev/null
+++
b/src/test/java/org/apache/sling/mcp/server/impl/LogSafeJsonSchemaValidatorTest.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.mcp.server.impl;
+
+import java.util.Map;
+import java.util.ServiceLoader;
+
+import io.modelcontextprotocol.json.schema.JsonSchemaValidator;
+import io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Tests for {@link LogSafeJsonSchemaValidator}.
+ */
+public class LogSafeJsonSchemaValidatorTest {
+
+ private final JsonSchemaValidator validator =
+ new
LogSafeJsonSchemaValidator(ServiceLoader.load(JsonSchemaValidatorSupplier.class)
+ .findFirst()
+ .orElseThrow()
+ .get());
+
+ /** Ensures argument names cannot forge lines in the SDK's warning log. */
+ @Test
+ public void escapesCallerControlledLineBreaks() {
+ var result = validator.validate(
+ Map.of("type", "object", "properties", Map.of(),
"additionalProperties", false),
+ Map.of("unexpected\r\nFORGED", "value"));
+
+ Assert.assertFalse(result.valid());
+ Assert.assertFalse(result.errorMessage().contains("\r"));
+ Assert.assertFalse(result.errorMessage().contains("\n"));
+
Assert.assertTrue(result.errorMessage().contains("unexpected\\r\\nFORGED"));
+ }
+
+ /** Verifies that successful validation and structured output are
unchanged. */
+ @Test
+ public void preservesSuccessfulValidation() {
+ var result = validator.validate(Map.of("type", "object"),
Map.of("value", 1));
+
+ Assert.assertTrue(result.valid());
+ Assert.assertNull(result.errorMessage());
+ }
+
+ /** Ensures the decorator does not lose the SDK's tool-schema registration
checks. */
+ @Test
+ public void rejectsInvalidSchema() {
+ Assert.assertFalse(validator
+ .validateSchema(Map.of("type", "object", "required", true))
+ .valid());
+ Assert.assertTrue(validator.validateSchema(Map.of("type",
"object")).valid());
+ }
+}
diff --git a/src/test/java/org/apache/sling/mcp/server/impl/McpServletTest.java
b/src/test/java/org/apache/sling/mcp/server/impl/McpServletTest.java
new file mode 100644
index 0000000..6cf1d3f
--- /dev/null
+++ b/src/test/java/org/apache/sling/mcp/server/impl/McpServletTest.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.mcp.server.impl;
+
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Map;
+
+import io.modelcontextprotocol.json.McpJsonMapperSupplier;
+import io.modelcontextprotocol.json.jackson2.JacksonMcpJsonMapperSupplier;
+import io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier;
+import
io.modelcontextprotocol.json.schema.jackson2.JacksonJsonSchemaValidatorSupplier;
+import
io.modelcontextprotocol.server.McpStatelessServerFeatures.SyncToolSpecification;
+import io.modelcontextprotocol.server.McpStatelessSyncServer;
+import io.modelcontextprotocol.spec.McpSchema;
+import org.apache.sling.mcp.server.spi.McpServerContribution;
+import org.apache.sling.mcp.server.spi.McpServerDescription;
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.osgi.framework.BundleContext;
+
+/**
+ * Tests for {@link McpServlet}.
+ */
+public class McpServletTest {
+
+ /**
+ * Keeps valid tools from the same and subsequent contributions when the
SDK rejects schemas.
+ */
+ @Test
+ public void activationIsolatesInvalidToolSchemas() throws Exception {
+ var first = tool("first", Map.of("type", "object"));
+ var invalidInput = tool("invalid\r\ninput", Map.of("type",
"not-a-json-schema-type"));
+ var invalidOutput = new SyncToolSpecification(
+ McpSchema.Tool.builder("invalid-output", Map.of("type",
"object"))
+ .outputSchema(Map.of("required", "not-an-array"))
+ .build(),
+ (context, request) ->
McpSchema.CallToolResult.builder().build());
+ var last = tool("last", Map.of("type", "object"));
+ var later = tool("later", Map.of("type", "object"));
+
+ McpServlet servlet = createServlet(
+ List.of(contribution(List.of(first, invalidInput,
invalidOutput, last)), contribution(List.of(later))));
+ try {
+ Field serverField =
McpServlet.class.getDeclaredField("syncServer");
+ serverField.setAccessible(true);
+ var server = (McpStatelessSyncServer) serverField.get(servlet);
+
+ Assert.assertEquals(
+ List.of("first", "last", "later"),
+
server.listTools().stream().map(McpSchema.Tool::name).toList());
+ } finally {
+ servlet.close();
+ }
+ }
+
+ private static SyncToolSpecification tool(String name, Map<String, Object>
inputSchema) {
+ return new SyncToolSpecification(
+ McpSchema.Tool.builder(name, inputSchema).build(),
+ (context, request) ->
McpSchema.CallToolResult.builder().build());
+ }
+
+ private static McpServerContribution
contribution(List<SyncToolSpecification> tools) {
+ McpServerContribution contribution =
Mockito.mock(McpServerContribution.class);
+
Mockito.when(contribution.getSyncToolSpecification()).thenReturn(tools);
+ return contribution;
+ }
+
+ private static McpServlet createServlet(List<McpServerContribution>
contributions)
+ throws IllegalAccessException, NoSuchMethodException {
+ McpJsonMapperSupplier mapperSupplier =
Mockito.mock(McpJsonMapperSupplier.class);
+ Mockito.when(mapperSupplier.get()).thenReturn(new
JacksonMcpJsonMapperSupplier().get());
+ JsonSchemaValidatorSupplier validatorSupplier =
Mockito.mock(JsonSchemaValidatorSupplier.class);
+ Mockito.when(validatorSupplier.get()).thenReturn(new
JacksonJsonSchemaValidatorSupplier().get());
+ McpServerDescription description =
Mockito.mock(McpServerDescription.class);
+ Mockito.when(description.name()).thenReturn("test-server");
+ Mockito.when(description.version()).thenReturn("1.0");
+ return new McpServlet(
+ Mockito.mock(BundleContext.class),
+ Mockito.mock(McpServlet.Config.class),
+ mapperSupplier,
+ validatorSupplier,
+ description,
+ contributions);
+ }
+}
diff --git
a/src/test/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilderTest.java
b/src/test/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilderTest.java
index cd8d58e..66a1d1c 100644
---
a/src/test/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilderTest.java
+++
b/src/test/java/org/apache/sling/mcp/server/impl/contribs/DiscoveredPromptBuilderTest.java
@@ -23,13 +23,27 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
+import java.util.Map;
+import io.modelcontextprotocol.common.McpTransportContext;
+import io.modelcontextprotocol.spec.McpSchema.GetPromptRequest;
import io.modelcontextprotocol.spec.McpSchema.Prompt;
import io.modelcontextprotocol.spec.McpSchema.PromptArgument;
+import io.modelcontextprotocol.spec.McpSchema.TextContent;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.observation.ResourceChange;
+import org.apache.sling.api.resource.observation.ResourceChange.ChangeType;
+import org.apache.sling.api.resource.observation.ResourceChangeListener;
import org.apache.sling.mcp.server.impl.DiscoveredPrompt;
+import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.ServiceRegistration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@@ -123,7 +137,153 @@ class DiscoveredPromptBuilderTest {
"Basic Prompt",
null,
List.of(
- new PromptArgument("first", "First Argument",
"This is the first argument", true),
- new PromptArgument("second", "Second
Argument", null, false)));
+ PromptArgument.builder("first")
+ .title("First Argument")
+ .description("This is the first
argument")
+ .required(true)
+ .build(),
+ PromptArgument.builder("second")
+ .title("Second Argument")
+ .required(false)
+ .build()));
+ }
+
+ @Test
+ void emptyArgumentNameRejectsEntirePrompt() {
+ Resource resource = promptResource("invalid", """
+ ---
+ argument.valid:
+ - required: true
+ argument.:
+ - required: true
+ ---
+ # Invalid Prompt
+ """);
+
+ Assertions.assertThatThrownBy(() -> new
DiscoveredPromptBuilder().buildPrompt(resource, "invalid"))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("argument.<name>");
+ }
+
+ @Test
+ void promptMessagesSubstituteArgumentsAndStripFrontMatter() throws
IOException {
+ String markdown = """
+ ---
+ title: Greeting
+ argument.person:
+ - title: Person
+ - required: true
+ ---
+ Hello {person}
+ """;
+ Resource resource = promptResource("greeting", markdown);
+ ResourceResolver resolver = mock(ResourceResolver.class);
+ when(resolver.getResource(resource.getPath())).thenReturn(resource);
+ when(resource.adaptTo(InputStream.class))
+ .thenAnswer(invocation -> new
ByteArrayInputStream(markdown.getBytes(StandardCharsets.UTF_8)));
+ DiscoveredPrompt prompt = new
DiscoveredPromptBuilder().buildPrompt(resource, "greeting");
+
+ var messages = prompt.getPromptMessages(
+ McpTransportContext.create(Map.of("resourceResolver",
resolver)),
+ GetPromptRequest.builder("greeting")
+ .arguments(Map.of("person", "Ada"))
+ .build());
+
+ assertThat(messages).hasSize(1);
+ assertThat(((TextContent)
messages.get(0).content()).text()).isEqualTo("Hello Ada\n");
+ }
+
+ @Test
+ void blankPromptNamesAreRejectedBeforeRegistration() {
+ for (String name : List.of("", " \t")) {
+ Resource resource = promptResource(name, "# Invalid Prompt");
+
+ Assertions.assertThatThrownBy(() -> new
DiscoveredPromptBuilder().buildPrompt(resource, name))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("Prompt name must not be blank");
+ }
+ }
+
+ @Test
+ void malformedPromptsDoNotPreventValidPeersDuringActivation() throws
Exception {
+ Resource invalidArgument = promptResource("invalid", """
+ ---
+ argument.:
+ - required: true
+ ---
+ # Invalid Prompt
+ """);
+ Resource invalidName = promptResource("", "# Invalid Name");
+ Resource valid = promptResource("valid", "# Valid Prompt");
+ ResourceResolver resolver = mock(ResourceResolver.class);
+ ResourceResolverFactory factory = mock(ResourceResolverFactory.class);
+ BundleContext context = mock(BundleContext.class);
+
when(factory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resolver);
+ when(resolver.findResources(Mockito.anyString(), Mockito.eq("xpath")))
+ .thenReturn(List.of(invalidArgument, invalidName,
valid).iterator());
+ when(context.registerService(
+ Mockito.eq(DiscoveredPrompt.class),
Mockito.any(DiscoveredPrompt.class), Mockito.any()))
+ .thenAnswer(invocation -> mock(ServiceRegistration.class));
+
+ new RepositoryPromptsRegistrar(factory, null, context);
+
+ ArgumentCaptor<DiscoveredPrompt> prompts =
ArgumentCaptor.forClass(DiscoveredPrompt.class);
+
Mockito.verify(context).registerService(Mockito.eq(DiscoveredPrompt.class),
prompts.capture(), Mockito.any());
+ assertThat(prompts.getValue().asPrompt().name()).isEqualTo("valid");
+ }
+
+ @Test
+ void invalidUpdateUnregistersPreviousPromptAndContinuesBatch() throws
Exception {
+ Resource original = promptResource("updated", "# Original Prompt");
+ Resource invalidUpdate = promptResource("updated", """
+ ---
+ argument.:
+ - required: true
+ ---
+ # Invalid Update
+ """);
+ Resource invalidName = promptResource("", "# Invalid Name");
+ Resource validPeer = promptResource("peer", "# Valid Peer");
+ ResourceResolver resolver = mock(ResourceResolver.class);
+ ResourceResolverFactory factory = mock(ResourceResolverFactory.class);
+ BundleContext context = mock(BundleContext.class);
+ ServiceRegistration<?> registration = mock(ServiceRegistration.class);
+
when(factory.getServiceResourceResolver(Mockito.anyMap())).thenReturn(resolver);
+ when(resolver.findResources(Mockito.anyString(), Mockito.eq("xpath")))
+ .thenReturn(List.of(original).iterator());
+
when(resolver.getResource(invalidUpdate.getPath())).thenReturn(invalidUpdate);
+
when(resolver.getResource(invalidName.getPath())).thenReturn(invalidName);
+ when(resolver.getResource(validPeer.getPath())).thenReturn(validPeer);
+ when(context.registerService(
+ Mockito.eq(DiscoveredPrompt.class),
Mockito.any(DiscoveredPrompt.class), Mockito.any()))
+ .thenAnswer(invocation -> registration);
+
+ new RepositoryPromptsRegistrar(factory, null, context);
+ ArgumentCaptor<ResourceChangeListener> listener =
ArgumentCaptor.forClass(ResourceChangeListener.class);
+ Mockito.verify(context)
+ .registerService(Mockito.eq(ResourceChangeListener.class),
listener.capture(), Mockito.any());
+
+ listener.getValue()
+ .onChange(List.of(
+ new ResourceChange(ChangeType.CHANGED,
invalidUpdate.getPath(), false),
+ new ResourceChange(ChangeType.ADDED,
invalidName.getPath(), false),
+ new ResourceChange(ChangeType.ADDED,
validPeer.getPath(), false)));
+
+ Mockito.verify(registration).unregister();
+ ArgumentCaptor<DiscoveredPrompt> prompts =
ArgumentCaptor.forClass(DiscoveredPrompt.class);
+ Mockito.verify(context, Mockito.times(2))
+ .registerService(Mockito.eq(DiscoveredPrompt.class),
prompts.capture(), Mockito.any());
+ assertThat(prompts.getAllValues())
+ .extracting(prompt -> prompt.asPrompt().name())
+ .containsExactly("updated", "peer");
+ }
+
+ private Resource promptResource(String name, String contents) {
+ Resource resource = mock(Resource.class);
+ when(resource.getPath()).thenReturn("/libs/sling/mcp/prompts/" + name
+ ".md");
+ when(resource.getResourceMetadata()).thenReturn(new
ResourceMetadata());
+ when(resource.adaptTo(InputStream.class))
+ .thenReturn(new
ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8)));
+ return resource;
}
}
diff --git
a/src/test/java/org/apache/sling/mcp/server/itbundle/ItToolContribution.java
b/src/test/java/org/apache/sling/mcp/server/itbundle/ItToolContribution.java
index c71878c..381511b 100644
--- a/src/test/java/org/apache/sling/mcp/server/itbundle/ItToolContribution.java
+++ b/src/test/java/org/apache/sling/mcp/server/itbundle/ItToolContribution.java
@@ -35,18 +35,40 @@ public class ItToolContribution implements
McpServerContribution {
public static final String TOOL_NAME = "it-hello";
public static final String TOOL_RESPONSE = "Hello from IT";
+ public static final String TYPED_TOOL_NAME = "it-hello-person";
@Override
public List<SyncToolSpecification> getSyncToolSpecification() {
- McpSchema.Tool tool = McpSchema.Tool.builder()
- .name(TOOL_NAME)
+ McpSchema.Tool tool = McpSchema.Tool.builder(
+ TOOL_NAME, Map.of("type", "object", "properties",
Map.of(), "additionalProperties", false))
.description("Integration test tool that returns a fixed
greeting")
- .inputSchema(new McpSchema.JsonSchema("object", Map.of(),
null, null, null, null))
.build();
- return List.of(new SyncToolSpecification(
- tool,
- (ctx, req) -> new McpSchema.CallToolResult(
- List.of(new McpSchema.TextContent(TOOL_RESPONSE)),
Boolean.FALSE, null, null)));
+ McpSchema.Tool typedTool = McpSchema.Tool.builder(
+ TYPED_TOOL_NAME,
+ Map.of(
+ "type",
+ "object",
+ "properties",
+ Map.of("name", Map.of("type", "string",
"minLength", 1)),
+ "required",
+ List.of("name"),
+ "additionalProperties",
+ false))
+ .description("Integration test tool with a required, typed
argument")
+ .build();
+
+ return List.of(
+ new SyncToolSpecification(tool, (ctx, req) ->
McpSchema.CallToolResult.builder()
+ .content(List.of(
+
McpSchema.TextContent.builder(TOOL_RESPONSE).build()))
+ .isError(false)
+ .build()),
+ new SyncToolSpecification(typedTool, (ctx, req) ->
McpSchema.CallToolResult.builder()
+ .content(List.of(McpSchema.TextContent.builder(
+ TOOL_RESPONSE + " " +
req.arguments().get("name"))
+ .build()))
+ .isError(false)
+ .build()));
}
}
diff --git
a/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundle.java
b/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundle.java
index 40bb782..954198e 100644
--- a/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundle.java
+++ b/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundle.java
@@ -22,11 +22,13 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.sling.testing.clients.ClientException;
import org.apache.sling.testing.clients.osgi.OsgiConsoleClient;
+import org.awaitility.Awaitility;
import org.ops4j.pax.tinybundles.TinyBundles;
import org.osgi.framework.Constants;
@@ -69,6 +71,13 @@ public class McpItSupportBundle {
if (bundlePath == null) {
throw new IllegalStateException("Bundle not generated; call
generate() first");
}
+ Awaitility.await("Sling Web Console is ready for bundle installation")
+ .atMost(Duration.ofSeconds(30))
+ .pollInterval(Duration.ofMillis(500))
+ .until(() -> client.doGet("/system/console/bundles.json", 200,
503)
+ .getStatusLine()
+ .getStatusCode()
+ == 200);
client.waitInstallBundle(bundlePath.toFile(), true, 10,
TimeUnit.SECONDS.toMillis(10), 500);
}
diff --git
a/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundleTest.java
b/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundleTest.java
new file mode 100644
index 0000000..ef4ad53
--- /dev/null
+++
b/src/test/java/org/apache/sling/mcp/server/itbundle/McpItSupportBundleTest.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.mcp.server.itbundle;
+
+import java.nio.file.Path;
+
+import org.apache.http.HttpVersion;
+import org.apache.http.message.BasicStatusLine;
+import org.apache.sling.testing.clients.SlingHttpResponse;
+import org.apache.sling.testing.clients.exceptions.TestingValidationException;
+import org.apache.sling.testing.clients.osgi.OsgiConsoleClient;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
+
+/**
+ * Tests for {@link McpItSupportBundle}.
+ */
+public class McpItSupportBundleTest {
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ private McpItSupportBundle bundle;
+ private Path bundlePath;
+ private OsgiConsoleClient client;
+
+ @Before
+ public void setUp() throws Exception {
+ bundle = new McpItSupportBundle(temporaryFolder.getRoot().toPath());
+ bundlePath = bundle.generate();
+ client = Mockito.mock(OsgiConsoleClient.class);
+ }
+
+ @Test
+ public void installationWaitsForStartupBeforeUploadingBundle() throws
Exception {
+ SlingHttpResponse starting = Mockito.mock(SlingHttpResponse.class);
+ SlingHttpResponse ready = Mockito.mock(SlingHttpResponse.class);
+ Mockito.when(starting.getStatusLine()).thenReturn(new
BasicStatusLine(HttpVersion.HTTP_1_1, 503, "Starting"));
+ Mockito.when(ready.getStatusLine()).thenReturn(new
BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
+ Mockito.when(client.doGet("/system/console/bundles.json", 200,
503)).thenReturn(starting, ready);
+
+ bundle.install(client);
+
+ InOrder requests = Mockito.inOrder(client);
+ requests.verify(client,
Mockito.times(2)).doGet("/system/console/bundles.json", 200, 503);
+ requests.verify(client).waitInstallBundle(bundlePath.toFile(), true,
10, 10000, 500);
+ requests.verifyNoMoreInteractions();
+ }
+
+ @Test
+ public void
installationPropagatesUnexpectedReadinessFailureWithoutUploading() throws
Exception {
+ TestingValidationException failure = new
TestingValidationException("Web Console returned HTTP 401");
+ Mockito.when(client.doGet("/system/console/bundles.json", 200,
503)).thenThrow(failure);
+
+ TestingValidationException actual =
+ Assert.assertThrows(TestingValidationException.class, () ->
bundle.install(client));
+
+ Assert.assertSame(failure, actual);
+ Mockito.verify(client, Mockito.never())
+ .waitInstallBundle(
+ Mockito.any(), Mockito.anyBoolean(), Mockito.anyInt(),
Mockito.anyLong(), Mockito.anyLong());
+ }
+}