Skip to content

feat: MCP tools support ToolContext #3831

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
wants to merge 1 commit into
base: main
Choose a base branch
from
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 @@ -51,16 +51,24 @@ public class McpToolCallbackAutoConfiguration {
@Bean
@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "SYNC",
matchIfMissing = true)
public SyncMcpToolCallbackProvider mcpToolCallbacks(ObjectProvider<List<McpSyncClient>> syncMcpClients) {
public SyncMcpToolCallbackProvider mcpToolCallbacks(ObjectProvider<List<McpSyncClient>> syncMcpClients,
McpClientCommonProperties commonProperties) {
List<McpSyncClient> mcpClients = syncMcpClients.stream().flatMap(List::stream).toList();
return new SyncMcpToolCallbackProvider(mcpClients);
return SyncMcpToolCallbackProvider.builder()
.addMcpClients(mcpClients)
.addExcludedToolContextKeys(commonProperties.getToolcallback().getExcludedToolContextKeys())
.build();
}

@Bean
@ConditionalOnProperty(prefix = McpClientCommonProperties.CONFIG_PREFIX, name = "type", havingValue = "ASYNC")
public AsyncMcpToolCallbackProvider mcpAsyncToolCallbacks(ObjectProvider<List<McpAsyncClient>> mcpClientsProvider) {
public AsyncMcpToolCallbackProvider mcpAsyncToolCallbacks(ObjectProvider<List<McpAsyncClient>> mcpClientsProvider,
McpClientCommonProperties commonProperties) {
List<McpAsyncClient> mcpClients = mcpClientsProvider.stream().flatMap(List::stream).toList();
return new AsyncMcpToolCallbackProvider(mcpClients);
return AsyncMcpToolCallbackProvider.builder()
.addMcpClients(mcpClients)
.addExcludedToolContextKeys(commonProperties.getToolcallback().getExcludedToolContextKeys())
.build();
}

public static class McpToolCallbackAutoConfigurationCondition extends AllNestedConditions {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@
package org.springframework.ai.mcp.client.common.autoconfigure.properties;

import java.time.Duration;
import java.util.Set;

import org.springframework.boot.context.properties.ConfigurationProperties;

import static org.springframework.ai.chat.model.ToolContext.TOOL_CALL_HISTORY;

/**
* Common Configuration properties for the Model Context Protocol (MCP) clients shared for
* all transport types.
Expand Down Expand Up @@ -190,6 +193,14 @@ public static class Toolcallback {
*/
private boolean enabled = true;

/**
* The keys that will not be sent to the MCP Server inside the `_meta` field of
* {@link io.modelcontextprotocol.spec.McpSchema.CallToolRequest}
*/
// Remember to update META-INF/additional-spring-configuration-metadata.json if
// you change this default values.
private Set<String> excludedToolContextKeys = Set.of(TOOL_CALL_HISTORY);

public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
Expand All @@ -198,6 +209,14 @@ public boolean isEnabled() {
return this.enabled;
}

public Set<String> getExcludedToolContextKeys() {
return excludedToolContextKeys;
}

public void setExcludedToolContextKeys(Set<String> excludedToolContextKeys) {
this.excludedToolContextKeys = excludedToolContextKeys;
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{"properties": [
{
"name": "spring.ai.mcp.client.toolcallback.excluded-tool-context-keys",
"defaultValue": ["TOOL_CALL_HISTORY"]
}
]}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package org.springframework.ai.mcp.client.common.autoconfigure.properties;

import java.time.Duration;
import java.util.Set;

import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -47,6 +48,9 @@ void defaultValues() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(20));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.SYNC);
assertThat(properties.isRootChangeNotification()).isTrue();
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand All @@ -56,7 +60,9 @@ void customValues() {
.withPropertyValues("spring.ai.mcp.client.enabled=false", "spring.ai.mcp.client.name=custom-client",
"spring.ai.mcp.client.version=2.0.0", "spring.ai.mcp.client.initialized=false",
"spring.ai.mcp.client.request-timeout=30s", "spring.ai.mcp.client.type=ASYNC",
"spring.ai.mcp.client.root-change-notification=false")
"spring.ai.mcp.client.root-change-notification=false",
"spring.ai.mcp.client.toolcallback.enabled=false",
"spring.ai.mcp.client.toolcallback.excluded-tool-context-keys=foo,bar")
.run(context -> {
McpClientCommonProperties properties = context.getBean(McpClientCommonProperties.class);
assertThat(properties.isEnabled()).isFalse();
Expand All @@ -66,6 +72,9 @@ void customValues() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(30));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.ASYNC);
assertThat(properties.isRootChangeNotification()).isFalse();
assertThat(properties.getToolcallback().isEnabled()).isFalse();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("foo", "bar"));
});
}

Expand Down Expand Up @@ -101,6 +110,14 @@ void setterGetterMethods() {
// Test rootChangeNotification property
properties.setRootChangeNotification(false);
assertThat(properties.isRootChangeNotification()).isFalse();

// Test toolcallback property
properties.getToolcallback().setEnabled(false);
assertThat(properties.getToolcallback().isEnabled()).isFalse();

properties.getToolcallback().setExcludedToolContextKeys(Set.of("foo", "bar"));
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("foo", "bar"));
}

@Test
Expand All @@ -125,7 +142,9 @@ void propertiesFileBinding() {
.withPropertyValues("spring.ai.mcp.client.enabled=false", "spring.ai.mcp.client.name=test-mcp-client",
"spring.ai.mcp.client.version=0.5.0", "spring.ai.mcp.client.initialized=false",
"spring.ai.mcp.client.request-timeout=45s", "spring.ai.mcp.client.type=ASYNC",
"spring.ai.mcp.client.root-change-notification=false")
"spring.ai.mcp.client.root-change-notification=false",
"spring.ai.mcp.client.toolcallback.enabled=false",
"spring.ai.mcp.client.toolcallback.excluded-tool-context-keys=foo,bar")
.run(context -> {
McpClientCommonProperties properties = context.getBean(McpClientCommonProperties.class);
assertThat(properties.isEnabled()).isFalse();
Expand All @@ -135,6 +154,9 @@ void propertiesFileBinding() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(45));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.ASYNC);
assertThat(properties.isRootChangeNotification()).isFalse();
assertThat(properties.getToolcallback().isEnabled()).isFalse();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("foo", "bar"));
});
}

Expand Down Expand Up @@ -165,7 +187,9 @@ void yamlConfigurationBinding() {
.withPropertyValues("spring.ai.mcp.client.enabled=false", "spring.ai.mcp.client.name=test-mcp-client-yaml",
"spring.ai.mcp.client.version=0.6.0", "spring.ai.mcp.client.initialized=false",
"spring.ai.mcp.client.request-timeout=60s", "spring.ai.mcp.client.type=ASYNC",
"spring.ai.mcp.client.root-change-notification=false")
"spring.ai.mcp.client.root-change-notification=false",
"spring.ai.mcp.client.toolcallback.enabled=false",
"spring.ai.mcp.client.toolcallback.excluded-tool-context-keys=foo,bar")
.run(context -> {
McpClientCommonProperties properties = context.getBean(McpClientCommonProperties.class);
assertThat(properties.isEnabled()).isFalse();
Expand All @@ -175,6 +199,9 @@ void yamlConfigurationBinding() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(60));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.ASYNC);
assertThat(properties.isRootChangeNotification()).isFalse();
assertThat(properties.getToolcallback().isEnabled()).isFalse();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("foo", "bar"));
});
}

Expand All @@ -201,6 +228,9 @@ void disabledProperties() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(20));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.SYNC);
assertThat(properties.isRootChangeNotification()).isTrue();
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand All @@ -216,6 +246,9 @@ void notInitializedProperties() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(20));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.SYNC);
assertThat(properties.isRootChangeNotification()).isTrue();
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand All @@ -231,6 +264,9 @@ void rootChangeNotificationDisabled() {
assertThat(properties.isInitialized()).isTrue();
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(20));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.SYNC);
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand All @@ -246,6 +282,9 @@ void customRequestTimeout() {
assertThat(properties.isInitialized()).isTrue();
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.SYNC);
assertThat(properties.isRootChangeNotification()).isTrue();
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand All @@ -261,6 +300,9 @@ void asyncClientType() {
assertThat(properties.isInitialized()).isTrue();
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(20));
assertThat(properties.isRootChangeNotification()).isTrue();
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand All @@ -278,6 +320,9 @@ void customNameAndVersion() {
assertThat(properties.getRequestTimeout()).isEqualTo(Duration.ofSeconds(20));
assertThat(properties.getType()).isEqualTo(McpClientCommonProperties.ClientType.SYNC);
assertThat(properties.isRootChangeNotification()).isTrue();
assertThat(properties.getToolcallback().isEnabled()).isTrue();
assertThat(properties.getToolcallback().getExcludedToolContextKeys())
.containsExactlyInAnyOrderElementsOf(Set.of("TOOL_CALL_HISTORY"));
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/*
* Copyright 2025-2025 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
*
* https://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.springframework.ai.mcp;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import static io.modelcontextprotocol.spec.McpSchema.Tool;

/**
* Implementation of {@link ToolCallback} that adapts MCP tools to Spring AI's tool
* interface with asynchronous execution support.
* <p>
* This class acts as a bridge between the Model Context Protocol (MCP) and Spring AI's
* tool system, allowing MCP tools to be used seamlessly within Spring AI applications.
* It:
* <ul>
* <li>Converts MCP tool definitions to Spring AI tool definitions</li>
* <li>Handles the asynchronous execution of tool calls through the MCP client</li>
* <li>Manages JSON serialization/deserialization of tool inputs and outputs</li>
* </ul>
* <p>
*
* @author YunKui Lu
* @see ToolCallback
* @see AsyncMcpToolCallback
* @see SyncMcpToolCallback
* @see Tool
*/
public abstract class AbstractMcpToolCallback implements ToolCallback {

public static final String DEFAULT_MCP_META_TOOL_CONTEXT_KEY = McpToolUtils.DEFAULT_MCP_META_TOOL_CONTEXT_KEY;

protected final Tool tool;

/**
* the keys that will not be sent to the MCP Server inside the `_meta` field of
* {@link io.modelcontextprotocol.spec.McpSchema.CallToolRequest}
*/
protected final Set<String> excludedToolContextKeys;

/**
* Creates a new {@code AbstractMcpToolCallback} instance.
* @param tool the MCP tool definition to adapt
* @param excludedToolContextKeys the keys that will not be sent to the MCP Server
* inside the `_meta` field of
* {@link io.modelcontextprotocol.spec.McpSchema.CallToolRequest}
*/
protected AbstractMcpToolCallback(Tool tool, Set<String> excludedToolContextKeys) {
Assert.notNull(tool, "tool cannot be null");
Assert.notNull(excludedToolContextKeys, "excludedToolContextKeys cannot be null");

this.tool = tool;
this.excludedToolContextKeys = excludedToolContextKeys;
}

/**
* Executes the tool with the provided input.
* <p>
* This method:
* <ol>
* <li>Converts the JSON input string to a map of arguments</li>
* <li>Calls the tool through the MCP client</li>
* <li>Converts the tool's response content to a JSON string</li>
* </ol>
* @param functionInput the tool input as a JSON string
* @return the tool's response as a JSON string
*/
@Override
public String call(String functionInput) {
return this.call(functionInput, null);
}

/**
* Converts the tool context to a mcp meta map
* @param toolContext the context for tool execution in a function calling scenario
* @return the mcp meta map
*/
protected Map<String, Object> getAdditionalToolContextToMeta(@Nullable ToolContext toolContext) {
if (toolContext == null || toolContext.getContext().isEmpty()) {
return Map.of();
}

Map<String, Object> meta = new HashMap<>(toolContext.getContext().size() - excludedToolContextKeys.size());
for (var toolContextEntry : toolContext.getContext().entrySet()) {
if (excludedToolContextKeys.contains(toolContextEntry.getKey())) {
continue;
}
meta.put(toolContextEntry.getKey(), toolContextEntry.getValue());
}
return meta;
}

}
Loading