-
Notifications
You must be signed in to change notification settings - Fork 967
fix(mcp): load json providers with fallback classloader #2155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BobSong-dev
wants to merge
3
commits into
agentscope-ai:main
Choose a base branch
from
BobSong-dev:fix/913-mcp-service-loader
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+224
−11
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
70 changes: 70 additions & 0 deletions
70
agentscope-core/src/main/java/io/agentscope/core/tool/mcp/McpJsonDefaults.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| /* | ||
| * Copyright 2024-2026 the original author or authors. | ||
| * | ||
| * Licensed 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 io.agentscope.core.tool.mcp; | ||
|
|
||
| import io.modelcontextprotocol.json.McpJsonMapper; | ||
| import io.modelcontextprotocol.json.McpJsonMapperSupplier; | ||
| import io.modelcontextprotocol.json.schema.JsonSchemaValidator; | ||
| import io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier; | ||
| import java.util.Optional; | ||
| import java.util.ServiceLoader; | ||
| import java.util.function.Supplier; | ||
|
|
||
| /** | ||
| * Loads the default MCP JSON components using a class loader that can see their providers. | ||
| * | ||
| * <p>Worker threads in executable JARs may use a context class loader that cannot access nested | ||
| * dependencies. In that case, fall back to the AgentScope class loader. | ||
| */ | ||
| final class McpJsonDefaults { | ||
|
|
||
| private McpJsonDefaults() {} | ||
|
|
||
| static McpJsonMapper jsonMapper() { | ||
| return loadSupplier(McpJsonMapperSupplier.class, "McpJsonMapper").get(); | ||
| } | ||
|
|
||
| static JsonSchemaValidator jsonSchemaValidator() { | ||
| return loadSupplier(JsonSchemaValidatorSupplier.class, "JsonSchemaValidator").get(); | ||
| } | ||
|
|
||
| private static <T extends Supplier<?>> T loadSupplier( | ||
| Class<T> serviceType, String implementationType) { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [nitpick] The parameter name |
||
| ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); | ||
| Optional<T> supplier = loadFirst(serviceType, contextClassLoader); | ||
|
|
||
| ClassLoader agentScopeClassLoader = McpJsonDefaults.class.getClassLoader(); | ||
| if (supplier.isEmpty() && agentScopeClassLoader != contextClassLoader) { | ||
| supplier = loadFirst(serviceType, agentScopeClassLoader); | ||
| } | ||
|
|
||
| return supplier.orElseThrow( | ||
| () -> | ||
| new IllegalStateException( | ||
| "No default " + implementationType + " implementation found")); | ||
| } | ||
|
|
||
| private static <T> Optional<T> loadFirst(Class<T> serviceType, ClassLoader classLoader) { | ||
| if (classLoader == null) { | ||
| return Optional.empty(); | ||
| } | ||
| try { | ||
| return ServiceLoader.load(serviceType, classLoader).findFirst(); | ||
| } catch (java.util.ServiceConfigurationError | LinkageError e) { | ||
| return Optional.empty(); | ||
| } | ||
| } | ||
| } | ||
136 changes: 136 additions & 0 deletions
136
agentscope-core/src/test/java/io/agentscope/core/tool/mcp/McpJsonDefaultsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| /* | ||
| * Copyright 2024-2026 the original author or authors. | ||
| * | ||
| * Licensed 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 io.agentscope.core.tool.mcp; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertInstanceOf; | ||
| import static org.junit.jupiter.api.Assertions.assertNotNull; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| import io.modelcontextprotocol.json.McpJsonMapperSupplier; | ||
| import io.modelcontextprotocol.json.schema.JsonSchemaValidatorSupplier; | ||
| import java.lang.reflect.InvocationTargetException; | ||
| import java.lang.reflect.Method; | ||
| import java.net.URL; | ||
| import java.net.URLClassLoader; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.util.ServiceLoader; | ||
| import java.util.function.Supplier; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.io.TempDir; | ||
|
|
||
| class McpJsonDefaultsTest { | ||
|
|
||
| @Test | ||
| void shouldResolveProvidersFromContextClassLoader() { | ||
| assertNotNull(McpJsonDefaults.jsonMapper()); | ||
| assertNotNull(McpJsonDefaults.jsonSchemaValidator()); | ||
| } | ||
|
|
||
| @Test | ||
| void shouldFallbackWhenContextClassLoaderCannotSeeMcpProviders() { | ||
| ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); | ||
| ClassLoader isolatedClassLoader = new ClassLoader(null) {}; | ||
|
|
||
| assertTrue( | ||
| ServiceLoader.load(McpJsonMapperSupplier.class, isolatedClassLoader) | ||
| .findFirst() | ||
| .isEmpty()); | ||
| assertTrue( | ||
| ServiceLoader.load(JsonSchemaValidatorSupplier.class, isolatedClassLoader) | ||
| .findFirst() | ||
| .isEmpty()); | ||
|
|
||
| try { | ||
| Thread.currentThread().setContextClassLoader(isolatedClassLoader); | ||
|
|
||
| assertNotNull(McpJsonDefaults.jsonMapper()); | ||
| assertNotNull(McpJsonDefaults.jsonSchemaValidator()); | ||
| assertNotNull( | ||
| McpClientBuilder.create("isolated-loader") | ||
| .stdioTransport("echo", "test") | ||
| .buildSync()); | ||
| } finally { | ||
| Thread.currentThread().setContextClassLoader(originalClassLoader); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void shouldFallbackWhenContextClassLoaderIsNull() { | ||
| ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); | ||
| try { | ||
| Thread.currentThread().setContextClassLoader(null); | ||
|
|
||
| assertNotNull(McpJsonDefaults.jsonMapper()); | ||
| assertNotNull(McpJsonDefaults.jsonSchemaValidator()); | ||
| } finally { | ||
| Thread.currentThread().setContextClassLoader(originalClassLoader); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void shouldFallbackWhenContextClassLoaderHasBrokenServiceDeclaration(@TempDir Path tempDir) | ||
| throws Exception { | ||
| writeServiceFile(tempDir, McpJsonMapperSupplier.class.getName(), "missing.DoesNotExist"); | ||
|
|
||
| ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); | ||
| try (URLClassLoader brokenClassLoader = | ||
| new URLClassLoader(new URL[] {tempDir.toUri().toURL()}, null)) { | ||
| Thread.currentThread().setContextClassLoader(brokenClassLoader); | ||
|
|
||
| assertNotNull(McpJsonDefaults.jsonMapper()); | ||
| } finally { | ||
| Thread.currentThread().setContextClassLoader(originalClassLoader); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void shouldThrowWhenNoDefaultSupplierIsAvailable() throws Exception { | ||
| Method loadSupplier = | ||
| McpJsonDefaults.class.getDeclaredMethod("loadSupplier", Class.class, String.class); | ||
| loadSupplier.setAccessible(true); | ||
|
|
||
| ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); | ||
| try { | ||
| Thread.currentThread().setContextClassLoader(McpJsonDefaults.class.getClassLoader()); | ||
|
|
||
| InvocationTargetException exception = | ||
| assertThrows( | ||
| InvocationTargetException.class, | ||
| () -> | ||
| loadSupplier.invoke( | ||
| null, MissingSupplier.class, "MissingSupplier")); | ||
|
|
||
| IllegalStateException cause = | ||
| assertInstanceOf(IllegalStateException.class, exception.getCause()); | ||
| assertEquals("No default MissingSupplier implementation found", cause.getMessage()); | ||
| } finally { | ||
| Thread.currentThread().setContextClassLoader(originalClassLoader); | ||
| } | ||
| } | ||
|
|
||
| private static void writeServiceFile(Path root, String serviceName, String providerName) | ||
| throws Exception { | ||
| Path serviceDirectory = root.resolve("META-INF/services"); | ||
| Files.createDirectories(serviceDirectory); | ||
| Files.writeString( | ||
| serviceDirectory.resolve(serviceName), providerName + System.lineSeparator()); | ||
| } | ||
|
|
||
| private interface MissingSupplier extends Supplier<Object> {} | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick]
jsonMapper()andjsonSchemaValidator()invokeServiceLoader.load()on every call. Since builder methods are typically called once per client andServiceLoader.load()is lightweight, this is acceptable. However, if clients are created frequently, consider caching the resolved supplier with a lazy-holder orstatic finalfield to avoid repeated classpath scanning. Note:ServiceLoader.load()+findFirst()should be deterministic for a given classloader, so caching is safe.