package name refactoring
This commit is contained in:
parent
39310c2010
commit
9978c25865
21 changed files with 88 additions and 89 deletions
|
|
@ -0,0 +1,246 @@
|
|||
package org.springframework.ai.mcp.client;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import reactor.core.publisher.Mono;
|
||||
import org.springframework.ai.mcp.spec.DefaultMcpSession;
|
||||
import org.springframework.ai.mcp.spec.McpTransport;
|
||||
import org.springframework.ai.mcp.spec.McpError;
|
||||
import org.springframework.ai.mcp.spec.McpSchema;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.GetPromptRequest;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.GetPromptResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListPromptsResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.PaginatedRequest;
|
||||
|
||||
/**
|
||||
* @author Dariusz Jędrzejczyk
|
||||
* @author Christian Tzolov
|
||||
*/
|
||||
public class McpAsyncClient extends DefaultMcpSession {
|
||||
|
||||
private static TypeReference<Void> VOID_TYPE_REFERENCE = new TypeReference<Void>() {
|
||||
};
|
||||
|
||||
public McpAsyncClient(McpTransport transport) {
|
||||
this(transport, Duration.ofSeconds(10), new ObjectMapper());
|
||||
}
|
||||
|
||||
public McpAsyncClient(McpTransport transport, Duration requestTimeout, ObjectMapper objectMapper) {
|
||||
super(requestTimeout, objectMapper, transport);
|
||||
}
|
||||
|
||||
/**
|
||||
* The initialization phase MUST be the first interaction between client and
|
||||
* server.
|
||||
* During this phase, the client and server:
|
||||
* <ul>
|
||||
* <li>Establish protocol version compatibility</li>
|
||||
* <li>Exchange and negotiate capabilities</li>
|
||||
* <li>Share implementation details</li>
|
||||
* </ul>
|
||||
* <br/>
|
||||
* The client MUST initiate this phase by sending an initialize request
|
||||
* containing:
|
||||
* <ul>
|
||||
* <li>The protocol version the client supports</li>
|
||||
* <li>The client's capabilities</li>
|
||||
* <li>Client implementation information</li>
|
||||
* </ul>
|
||||
*
|
||||
* The server MUST respond with its own capabilities and information:
|
||||
* {@link McpSchema.ServerCapabilities}. <br/>
|
||||
* After successful initialization, the client MUST send an initialized
|
||||
* notification
|
||||
* to indicate it is ready to begin normal operations.
|
||||
*
|
||||
* <br/>
|
||||
*
|
||||
* <a href=
|
||||
* "https://github.com/modelcontextprotocol/specification/blob/main/docs/specification/basic/lifecycle.md#initialization">Initialization
|
||||
* Spec</a>
|
||||
*
|
||||
* @return the initialize result.
|
||||
*/
|
||||
public Mono<McpSchema.InitializeResult> initialize() {
|
||||
McpSchema.InitializeRequest initializeRequest = new McpSchema.InitializeRequest(// @formatter:off
|
||||
McpSchema.LATEST_PROTOCOL_VERSION,
|
||||
new McpSchema.ClientCapabilities(null, new McpSchema.ClientCapabilities.RootCapabilities(true), null),
|
||||
new McpSchema.Implementation("mcp-java-client", "0.0.1")); // @formatter:on
|
||||
|
||||
Mono<McpSchema.InitializeResult> result = this.sendRequest("initialize", initializeRequest,
|
||||
new TypeReference<McpSchema.InitializeResult>() {
|
||||
});
|
||||
|
||||
return result.flatMap(initializeResult -> {
|
||||
if (!McpSchema.LATEST_PROTOCOL_VERSION.equals(initializeResult.protocolVersion())) {
|
||||
return Mono.error(
|
||||
new McpError("Unsupported protocol version from the server: "
|
||||
+ initializeResult.protocolVersion()));
|
||||
} else {
|
||||
return this.sendNotification("notifications/initialized", null)
|
||||
.thenReturn(initializeResult);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a roots/list_changed notification.
|
||||
*/
|
||||
public Mono<Void> sendRootsListChanged() {
|
||||
return this.sendNotification("notifications/roots/list_changed");
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a synchronous ping request.
|
||||
*/
|
||||
public Mono<Void> ping() {
|
||||
return this.sendRequest("ping", null, VOID_TYPE_REFERENCE);
|
||||
}
|
||||
|
||||
// --------------------------
|
||||
// Tools
|
||||
// --------------------------
|
||||
private static TypeReference<McpSchema.CallToolResult> CALL_TOOL_RESULT_TYPE_REF = new TypeReference<McpSchema.CallToolResult>() {
|
||||
};
|
||||
private static TypeReference<McpSchema.ListToolsResult> LIST_TOOLS_RESULT_TYPE_REF = new TypeReference<McpSchema.ListToolsResult>() {
|
||||
};
|
||||
|
||||
/**
|
||||
* Send a tools/call request.
|
||||
*
|
||||
* @param callToolRequest the call tool request.
|
||||
* @return the call tool result.
|
||||
*/
|
||||
public Mono<McpSchema.CallToolResult> callTool(McpSchema.CallToolRequest callToolRequest) {
|
||||
return this.sendRequest("tools/call", callToolRequest, CALL_TOOL_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a tools/list request.
|
||||
*
|
||||
* @return the list of tools result.
|
||||
*/
|
||||
public Mono<McpSchema.ListToolsResult> listTools(String cursor) {
|
||||
return this.sendRequest("tools/list", new McpSchema.PaginatedRequest(cursor), LIST_TOOLS_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
// --------------------------
|
||||
// Resources
|
||||
// --------------------------
|
||||
|
||||
private static TypeReference<McpSchema.ListResourcesResult> LIST_RESOURCES_RESULT_TYPE_REF = new TypeReference<McpSchema.ListResourcesResult>() {
|
||||
};
|
||||
private static TypeReference<McpSchema.ReadResourceResult> READ_RESOURCE_RESULT_TYPE_REF = new TypeReference<McpSchema.ReadResourceResult>() {
|
||||
};
|
||||
private static TypeReference<McpSchema.ListResourceTemplatesResult> LIST_RESOURCE_TEMPLATES_RESULT_TYPE_REF = new TypeReference<McpSchema.ListResourceTemplatesResult>() {
|
||||
};
|
||||
|
||||
/**
|
||||
* Send a resources/list request.
|
||||
*
|
||||
* @param cursor the cursor
|
||||
* @return the list of resources result.
|
||||
*/
|
||||
public Mono<McpSchema.ListResourcesResult> listResources(String cursor) {
|
||||
return this.sendRequest("resources/list", new McpSchema.PaginatedRequest(cursor),
|
||||
LIST_RESOURCES_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a resources/read request.
|
||||
*
|
||||
* @param resource the resource to read
|
||||
* @return the resource content.
|
||||
*/
|
||||
public Mono<McpSchema.ReadResourceResult> readResource(McpSchema.Resource resource) {
|
||||
return this.readResource(new McpSchema.ReadResourceRequest(resource.uri()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a resources/read request.
|
||||
*
|
||||
* @param readResourceRequest the read resource request.
|
||||
* @return the resource content.
|
||||
*/
|
||||
public Mono<McpSchema.ReadResourceResult> readResource(McpSchema.ReadResourceRequest readResourceRequest) {
|
||||
return this.sendRequest("resources/read", readResourceRequest, READ_RESOURCE_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resource templates allow servers to expose parameterized resources using URI
|
||||
* templates. Arguments may be auto-completed through the completion API.
|
||||
*
|
||||
* Request a list of resource templates the server has.
|
||||
*
|
||||
* @param cursor the cursor
|
||||
* @return the list of resource templates result.
|
||||
*/
|
||||
public Mono<McpSchema.ListResourceTemplatesResult> listResourceTemplates(String cursor) {
|
||||
return this.sendRequest("resources/templates/list", new McpSchema.PaginatedRequest(cursor),
|
||||
LIST_RESOURCE_TEMPLATES_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* List Changed Notification. When the list of available resources changes,
|
||||
* servers that declared the listChanged capability SHOULD send a notification:
|
||||
*/
|
||||
public Mono<Void> sendResourcesListChanged() {
|
||||
return this.sendNotification("notifications/resources/list_changed");
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscriptions. The protocol supports optional subscriptions to resource
|
||||
* changes.
|
||||
* Clients can subscribe to specific resources and receive notifications when
|
||||
* they change.
|
||||
*
|
||||
* Send a resources/subscribe request.
|
||||
*
|
||||
* @param subscribeRequest the subscribe request contains the uri of the
|
||||
* resource to subscribe to.
|
||||
*/
|
||||
public Mono<Void> subscribeResource(McpSchema.SubscribeRequest subscribeRequest) {
|
||||
return this.sendRequest("resources/subscribe", subscribeRequest, VOID_TYPE_REFERENCE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a resources/unsubscribe request.
|
||||
*
|
||||
* @param unsubscribeRequest the unsubscribe request contains the uri of the
|
||||
* resource to unsubscribe from.
|
||||
*/
|
||||
public Mono<Void> unsubscribeResource(McpSchema.UnsubscribeRequest unsubscribeRequest) {
|
||||
return this.sendRequest("resources/unsubscribe", unsubscribeRequest, VOID_TYPE_REFERENCE);
|
||||
}
|
||||
|
||||
// --------------------------
|
||||
// Prompts
|
||||
// --------------------------
|
||||
private static TypeReference<McpSchema.ListPromptsResult> LIST_PROMPTS_RESULT_TYPE_REF = new TypeReference<McpSchema.ListPromptsResult>() {
|
||||
};
|
||||
private static TypeReference<McpSchema.GetPromptResult> GET_PROMPT_RESULT_TYPE_REF = new TypeReference<McpSchema.GetPromptResult>() {
|
||||
};
|
||||
|
||||
public Mono<ListPromptsResult> listPrompts(String cursor) {
|
||||
return this
|
||||
.sendRequest("prompts/list", new PaginatedRequest(cursor), LIST_PROMPTS_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
public Mono<GetPromptResult> getPrompt(GetPromptRequest getPromptRequest) {
|
||||
return this.sendRequest("prompts/get", getPromptRequest, GET_PROMPT_RESULT_TYPE_REF);
|
||||
}
|
||||
|
||||
/**
|
||||
* (Server) An optional notification from the server to the client, informing it
|
||||
* that
|
||||
* the list of prompts it offers has changed. This may be issued by servers
|
||||
* without
|
||||
* any previous subscription from the client.
|
||||
*/
|
||||
public Mono<Void> promptListChangedNotification() {
|
||||
return this.sendNotification("notifications/prompts/list_changed");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.client;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.ai.mcp.spec.McpTransport;
|
||||
|
||||
/**
|
||||
* Factory class providing static methods for creating Model Context Protocol (MCP) clients.
|
||||
* This class serves as the main entry point for establishing connections with MCP servers,
|
||||
* offering both synchronous and asynchronous client implementations.
|
||||
*
|
||||
* <p>The class provides factory methods to create either:
|
||||
* <ul>
|
||||
* <li>{@link McpAsyncClient} for non-blocking operations
|
||||
* <li>{@link McpSyncClient} for blocking operations
|
||||
* </ul>
|
||||
*
|
||||
* <p>Each client type can be instantiated with default settings or with custom configuration
|
||||
* including request timeout and JSON object mapping.
|
||||
*
|
||||
* <p>Future implementations will introduce a builder pattern for more flexible client configuration.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
public class McpClient {
|
||||
|
||||
/**
|
||||
* Private constructor to prevent instantiation as this is a utility class
|
||||
* containing only static factory methods.
|
||||
*/
|
||||
private McpClient() {
|
||||
}
|
||||
|
||||
// TODO: introduce a builder like:
|
||||
// McpClient.using(transport)
|
||||
// .withRequestTimeout(Duration.ofSeconds(5))
|
||||
// .withObjectMapper(objectMapper); <- or even a more sophisticated
|
||||
// JSONtoPOJOCodec type
|
||||
// .sync();
|
||||
|
||||
/**
|
||||
* Creates an asynchronous MCP client with default configuration.
|
||||
*
|
||||
* @param transport The transport layer implementation for MCP communication
|
||||
* @return A new instance of {@link McpAsyncClient}
|
||||
*/
|
||||
public static McpAsyncClient async(McpTransport transport) {
|
||||
return new McpAsyncClient(transport);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an asynchronous MCP client with custom configuration.
|
||||
*
|
||||
* @param transport The transport layer implementation for MCP communication
|
||||
* @param requestTimeout The duration to wait before timing out requests
|
||||
* @param objectMapper The Jackson object mapper for JSON serialization/deserialization
|
||||
* @return A new instance of {@link McpAsyncClient}
|
||||
*/
|
||||
public static McpAsyncClient async(McpTransport transport, Duration requestTimeout,
|
||||
ObjectMapper objectMapper) {
|
||||
return new McpAsyncClient(transport, requestTimeout, objectMapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a synchronous MCP client with default configuration.
|
||||
* This method wraps an asynchronous client to provide synchronous operations.
|
||||
*
|
||||
* @param transport The transport layer implementation for MCP communication
|
||||
* @return A new instance of {@link McpSyncClient}
|
||||
*/
|
||||
public static McpSyncClient sync(McpTransport transport) {
|
||||
return new McpSyncClient(async(transport));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a synchronous MCP client with custom configuration.
|
||||
* This method wraps an asynchronous client to provide synchronous operations.
|
||||
*
|
||||
* @param transport The transport layer implementation for MCP communication
|
||||
* @param requestTimeout The duration to wait before timing out requests
|
||||
* @param objectMapper The Jackson object mapper for JSON serialization/deserialization
|
||||
* @return A new instance of {@link McpSyncClient}
|
||||
*/
|
||||
public static McpSyncClient sync(McpTransport transport, Duration requestTimeout,
|
||||
ObjectMapper objectMapper) {
|
||||
return new McpSyncClient(async(transport, requestTimeout, objectMapper));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,208 @@
|
|||
package org.springframework.ai.mcp.client;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import org.springframework.ai.mcp.client.util.Assert;
|
||||
import org.springframework.ai.mcp.spec.McpSchema;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.GetPromptRequest;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.GetPromptResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListPromptsResult;
|
||||
|
||||
/**
|
||||
* @author Dariusz Jędrzejczyk
|
||||
* @author Christian Tzolov
|
||||
*/
|
||||
public class McpSyncClient implements AutoCloseable {
|
||||
|
||||
// TODO: Consider providing a client config to set this properly
|
||||
// this is currently a concern only because AutoCloseable is used - perhaps it
|
||||
// is not a requirement?
|
||||
private static final long DEFAULT_CLOSE_TIMEOUT_MS = 10_000L;
|
||||
|
||||
private final McpAsyncClient delegate;
|
||||
|
||||
public McpSyncClient(McpAsyncClient delegate) {
|
||||
Assert.notNull(delegate, "The delegate can not be null");
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
this.delegate.closeGracefully(Duration.ofMillis(DEFAULT_CLOSE_TIMEOUT_MS)).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* The initialization phase MUST be the first interaction between client and
|
||||
* server.
|
||||
* During this phase, the client and server:
|
||||
* <ul>
|
||||
* <li>Establish protocol version compatibility</li>
|
||||
* <li>Exchange and negotiate capabilities</li>
|
||||
* <li>Share implementation details</li>
|
||||
* </ul>
|
||||
* <br/>
|
||||
* The client MUST initiate this phase by sending an initialize request
|
||||
* containing:
|
||||
* <ul>
|
||||
* <li>The protocol version the client supports</li>
|
||||
* <li>The client's capabilities</li>
|
||||
* <li>Client implementation information</li>
|
||||
* </ul>
|
||||
*
|
||||
* The server MUST respond with its own capabilities and information:
|
||||
* {@link McpSchema.ServerCapabilities}. <br/>
|
||||
* After successful initialization, the client MUST send an initialized
|
||||
* notification
|
||||
* to indicate it is ready to begin normal operations.
|
||||
*
|
||||
* <br/>
|
||||
*
|
||||
* <a href=
|
||||
* "https://github.com/modelcontextprotocol/specification/blob/main/docs/specification/basic/lifecycle.md#initialization">Initialization
|
||||
* Spec</a>
|
||||
*
|
||||
* @return the initialize result.
|
||||
*/
|
||||
public McpSchema.InitializeResult initialize() {
|
||||
// TODO: block takes no argument here as we assume the async client is
|
||||
// configured with a requestTimeout at all times
|
||||
return this.delegate.initialize().block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a roots/list_changed notification.
|
||||
*/
|
||||
public void sendRootsListChanged() {
|
||||
this.delegate.sendRootsListChanged().block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a synchronous ping request.
|
||||
*/
|
||||
public void ping() {
|
||||
this.delegate.ping().block();
|
||||
}
|
||||
|
||||
// --------------------------
|
||||
// Tools
|
||||
// --------------------------
|
||||
/**
|
||||
* Send a tools/call request.
|
||||
*
|
||||
* @param callToolRequest the call tool request.
|
||||
* @return the call tool result.
|
||||
*/
|
||||
public McpSchema.CallToolResult callTool(McpSchema.CallToolRequest callToolRequest) {
|
||||
return this.delegate.callTool(callToolRequest).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a tools/list request.
|
||||
*
|
||||
* @return the list of tools result.
|
||||
*/
|
||||
public McpSchema.ListToolsResult listTools(String cursor) {
|
||||
return this.delegate.listTools(cursor).block();
|
||||
}
|
||||
|
||||
// --------------------------
|
||||
// Resources
|
||||
// --------------------------
|
||||
|
||||
/**
|
||||
* Send a resources/list request.
|
||||
*
|
||||
* @param cursor the cursor
|
||||
* @return the list of resources result.
|
||||
*/
|
||||
public McpSchema.ListResourcesResult listResources(String cursor) {
|
||||
return this.delegate.listResources(cursor).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a resources/read request.
|
||||
*
|
||||
* @param resource the resource to read
|
||||
* @return the resource content.
|
||||
*/
|
||||
public McpSchema.ReadResourceResult readResource(McpSchema.Resource resource) {
|
||||
return this.delegate.readResource(resource).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a resources/read request.
|
||||
*
|
||||
* @param readResourceRequest the read resource request.
|
||||
* @return the resource content.
|
||||
*/
|
||||
public McpSchema.ReadResourceResult readResource(McpSchema.ReadResourceRequest readResourceRequest) {
|
||||
return this.delegate.readResource(readResourceRequest).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resource templates allow servers to expose parameterized resources using URI
|
||||
* templates. Arguments may be auto-completed through the completion API.
|
||||
*
|
||||
* Request a list of resource templates the server has.
|
||||
*
|
||||
* @param cursor the cursor
|
||||
* @return the list of resource templates result.
|
||||
*/
|
||||
public McpSchema.ListResourceTemplatesResult listResourceTemplates(String cursor) {
|
||||
return this.delegate.listResourceTemplates(cursor).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* List Changed Notification. When the list of available resources changes,
|
||||
* servers
|
||||
* that declared the listChanged capability SHOULD send a notification:
|
||||
*/
|
||||
public void sendResourcesListChanged() {
|
||||
this.delegate.sendResourcesListChanged().block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscriptions. The protocol supports optional subscriptions to resource
|
||||
* changes. Clients can subscribe to specific resources and receive
|
||||
* notifications when they change.
|
||||
*
|
||||
* Send a resources/subscribe request.
|
||||
*
|
||||
* @param subscribeRequest the subscribe request contains the uri of the
|
||||
* resource to subscribe to.
|
||||
*/
|
||||
public void subscribeResource(McpSchema.SubscribeRequest subscribeRequest) {
|
||||
this.delegate.subscribeResource(subscribeRequest).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a resources/unsubscribe request.
|
||||
*
|
||||
* @param unsubscribeRequest the unsubscribe request contains the uri of the
|
||||
* resource
|
||||
* to unsubscribe from.
|
||||
*/
|
||||
public void unsubscribeResource(McpSchema.UnsubscribeRequest unsubscribeRequest) {
|
||||
this.delegate.unsubscribeResource(unsubscribeRequest).block();
|
||||
}
|
||||
|
||||
// --------------------------
|
||||
// Prompts
|
||||
// --------------------------
|
||||
public ListPromptsResult listPrompts(String cursor) {
|
||||
return this.delegate.listPrompts(cursor).block();
|
||||
}
|
||||
|
||||
public GetPromptResult getPrompt(GetPromptRequest getPromptRequest) {
|
||||
return this.delegate.getPrompt(getPromptRequest).block();
|
||||
}
|
||||
|
||||
/**
|
||||
* (Server) An optional notification from the server to the client, informing it
|
||||
* that the list of prompts it offers has changed. This may be issued by servers
|
||||
* without any previous subscription from the client.
|
||||
*/
|
||||
public void promptListChangedNotification() {
|
||||
this.delegate.promptListChangedNotification().block();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,133 @@
|
|||
package org.springframework.ai.mcp.client.stdio;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import org.springframework.ai.mcp.client.util.Assert;
|
||||
|
||||
/**
|
||||
* Server parameters for stdio client.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public class ServerParameters {
|
||||
|
||||
// Environment variables to inherit by default
|
||||
private static final List<String> DEFAULT_INHERITED_ENV_VARS = System.getProperty("os.name")
|
||||
.toLowerCase()
|
||||
.contains("win")
|
||||
? Arrays.asList("APPDATA", "HOMEDRIVE", "HOMEPATH", "LOCALAPPDATA", "PATH",
|
||||
"PROCESSOR_ARCHITECTURE", "SYSTEMDRIVE", "SYSTEMROOT", "TEMP", "USERNAME", "USERPROFILE")
|
||||
: Arrays.asList("HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER");
|
||||
|
||||
@JsonProperty("command")
|
||||
private String command;
|
||||
|
||||
@JsonProperty("args")
|
||||
private List<String> args = new ArrayList<>();
|
||||
|
||||
@JsonProperty("env")
|
||||
private Map<String, String> env;
|
||||
|
||||
private ServerParameters(String command, List<String> args, Map<String, String> env) {
|
||||
Assert.notNull(command, "The command can not be null");
|
||||
Assert.notNull(args, "The args can not be null");
|
||||
|
||||
this.command = command;
|
||||
this.args = args;
|
||||
this.env = new HashMap<>(getDefaultEnvironment());
|
||||
if (env != null && !env.isEmpty()) {
|
||||
this.env.putAll(env);
|
||||
}
|
||||
}
|
||||
|
||||
public String getCommand() {
|
||||
return this.command;
|
||||
}
|
||||
|
||||
public List<String> getArgs() {
|
||||
return this.args;
|
||||
}
|
||||
|
||||
public Map<String, String> getEnv() {
|
||||
return this.env;
|
||||
}
|
||||
|
||||
public static Builder builder(String command) {
|
||||
return new Builder(command);
|
||||
}
|
||||
|
||||
public static class Builder {
|
||||
|
||||
private String command;
|
||||
|
||||
private List<String> args = new ArrayList<>();
|
||||
|
||||
private Map<String, String> env = new HashMap<>();
|
||||
|
||||
public Builder(String command) {
|
||||
Assert.notNull(command, "The command can not be null");
|
||||
this.command = command;
|
||||
}
|
||||
|
||||
public Builder args(String... args) {
|
||||
Assert.notNull(args, "The args can not be null");
|
||||
this.args = Arrays.asList(args);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder args(List<String> args) {
|
||||
Assert.notNull(args, "The args can not be null");
|
||||
this.args = new ArrayList<>(args);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder arg(String arg) {
|
||||
Assert.notNull(arg, "The arg can not be null");
|
||||
this.args.add(arg);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder env(Map<String, String> env) {
|
||||
if (env != null && !env.isEmpty()) {
|
||||
this.env.putAll(env);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder addEnvVar(String key, String value) {
|
||||
Assert.notNull(key, "The key can not be null");
|
||||
Assert.notNull(value, "The value can not be null");
|
||||
this.env.put(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
public ServerParameters build() {
|
||||
return new ServerParameters(command, args, env);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a default environment object including only environment variables
|
||||
* deemed safe to inherit.
|
||||
*/
|
||||
private static Map<String, String> getDefaultEnvironment() {
|
||||
return System.getenv()
|
||||
.entrySet()
|
||||
.stream()
|
||||
.filter(entry -> DEFAULT_INHERITED_ENV_VARS.contains(entry.getKey()))
|
||||
.filter(entry -> entry.getValue() != null)
|
||||
.filter(entry -> !entry.getValue().startsWith("()"))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.client.stdio;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.ai.mcp.client.stdio.ServerParametersParser.McpServerConfigurations.McpServerConfiguration;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
|
||||
public class ServerParametersParser {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record McpServerConfigurations(// @formatter:off
|
||||
@JsonProperty("mcpServers") Map<String, McpServerConfiguration> mcpServers) {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record McpServerConfiguration(
|
||||
@JsonProperty("command") String command,
|
||||
@JsonProperty("args") List<String> args,
|
||||
@JsonProperty("env") Map<String, String> env) {
|
||||
}
|
||||
} // @formatter:on
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// Assuming the JSON is in a file named "servers.json"
|
||||
String jsonInput = """
|
||||
{
|
||||
"mcpServers": {
|
||||
"filesystem": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
|
||||
},
|
||||
"git": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-git", "--repository", "path/to/git/repo"]
|
||||
},
|
||||
"github": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-github"],
|
||||
"env": {
|
||||
"GITHUB_PERSONAL_ACCESS_TOKEN": "<YOUR_TOKEN>"
|
||||
}
|
||||
},
|
||||
"postgres": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
// Deserialize JSON into McpServers
|
||||
McpServerConfigurations servers = objectMapper.readValue(jsonInput, McpServerConfigurations.class);
|
||||
|
||||
// Access individual servers
|
||||
for (Map.Entry<String, McpServerConfiguration> entry : servers.mcpServers().entrySet()) {
|
||||
System.out.println("Key: " + entry.getKey());
|
||||
System.out.println("Command: " + entry.getValue().command());
|
||||
System.out.println("Arguments: " + String.join(", ", entry.getValue().args()));
|
||||
System.out.println("Environment Variables: " + entry.getValue().env());
|
||||
System.out.println("-----------");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,245 @@
|
|||
package org.springframework.ai.mcp.client.stdio;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.scheduler.Scheduler;
|
||||
import reactor.core.scheduler.Schedulers;
|
||||
import org.springframework.ai.mcp.client.util.Assert;
|
||||
import org.springframework.ai.mcp.spec.AbstractMcpTransport;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCMessage;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCNotification;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCRequest;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCResponse;
|
||||
|
||||
/**
|
||||
* Stdio client for communicating with a server process.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
public class StdioServerTransport extends AbstractMcpTransport {
|
||||
|
||||
private final static TypeReference<HashMap<String, Object>> MAP_TYPE_REF = new TypeReference<HashMap<String, Object>>() {
|
||||
};
|
||||
|
||||
private Process process;
|
||||
|
||||
private BufferedReader processErrorReader;
|
||||
private BufferedReader processReader;
|
||||
private BufferedWriter processWriter;
|
||||
|
||||
private Scheduler inboundScheduler;
|
||||
private Scheduler outboundScheduler;
|
||||
private Scheduler errorScheduler;
|
||||
|
||||
volatile boolean isRunning;
|
||||
|
||||
private final ServerParameters params;
|
||||
|
||||
public StdioServerTransport(ServerParameters params) {
|
||||
this(params, new ObjectMapper());
|
||||
}
|
||||
|
||||
public StdioServerTransport(ServerParameters params, ObjectMapper objectMapper) {
|
||||
|
||||
super(objectMapper);
|
||||
|
||||
Assert.notNull(params, "The params can not be null");
|
||||
Assert.notNull(objectMapper, "The ObjectMapper can not be null");
|
||||
|
||||
this.params = params;
|
||||
|
||||
// Start threads
|
||||
this.inboundScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(),
|
||||
"inbound");
|
||||
this.outboundScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(),
|
||||
"outbound");
|
||||
this.errorScheduler = Schedulers.fromExecutorService(Executors.newSingleThreadExecutor(),
|
||||
"error");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
// Prepare command and environment
|
||||
List<String> fullCommand = new ArrayList<>();
|
||||
fullCommand.add(params.getCommand());
|
||||
fullCommand.addAll(params.getArgs());
|
||||
|
||||
ProcessBuilder processBuilder = this.getProcessBuilder();
|
||||
processBuilder.command(fullCommand);
|
||||
processBuilder.environment().putAll(params.getEnv());
|
||||
|
||||
// Start the process
|
||||
try {
|
||||
this.process = processBuilder.start();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Failed to start process with command: " + fullCommand, e);
|
||||
}
|
||||
|
||||
// Validate process streams
|
||||
if (this.process.getInputStream() == null || process.getOutputStream() == null) {
|
||||
this.process.destroy();
|
||||
throw new RuntimeException("Process input or output stream is null");
|
||||
}
|
||||
|
||||
// Initialize readers and writers
|
||||
this.processErrorReader = this.process.errorReader();
|
||||
this.processReader = this.process.inputReader();
|
||||
this.processWriter = this.process.outputWriter();
|
||||
|
||||
// Start threads
|
||||
this.isRunning = true;
|
||||
startInboundProcessing();
|
||||
startOutboundProcessing();
|
||||
startErrorProcessing();
|
||||
}
|
||||
|
||||
protected ProcessBuilder getProcessBuilder() {
|
||||
return new ProcessBuilder();
|
||||
}
|
||||
|
||||
public void awaitForExit() {
|
||||
try {
|
||||
this.process.waitFor();
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException("Process interrupted", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void startErrorProcessing() {
|
||||
this.errorScheduler.schedule(() -> {
|
||||
try {
|
||||
String line;
|
||||
while (isRunning && processErrorReader != null && (line = processErrorReader.readLine()) != null) {
|
||||
try {
|
||||
System.out.println("Received error line: " + line);
|
||||
// TODO: handle errors, etc.
|
||||
this.getErrorSink().tryEmitNext(line);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (this.isRunning) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} finally {
|
||||
this.isRunning = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void startInboundProcessing() {
|
||||
this.inboundScheduler.schedule(() -> {
|
||||
try {
|
||||
String line;
|
||||
while (this.isRunning && this.processReader != null && (line = this.processReader.readLine()) != null) {
|
||||
try {
|
||||
JSONRPCMessage message = deserializeJsonRpcMessage(line);
|
||||
if (!this.getInboundSink().tryEmitNext(message).isSuccess()) {
|
||||
// TODO: Back off, reschedule, give up?
|
||||
throw new RuntimeException("Failed to enqueue message");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (isRunning) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
} finally {
|
||||
isRunning = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private JSONRPCMessage deserializeJsonRpcMessage(String jsonText) throws IOException {
|
||||
|
||||
var map = this.objectMapper.readValue(jsonText, MAP_TYPE_REF);
|
||||
|
||||
// Determine message type based on specific JSON structure
|
||||
if (map.containsKey("method") && map.containsKey("id")) {
|
||||
return this.objectMapper.convertValue(map, JSONRPCRequest.class);
|
||||
} else if (map.containsKey("method") && !map.containsKey("id")) {
|
||||
return this.objectMapper.convertValue(map, JSONRPCNotification.class);
|
||||
} else if (map.containsKey("result") || map.containsKey("error")) {
|
||||
return this.objectMapper.convertValue(map, JSONRPCResponse.class);
|
||||
}
|
||||
|
||||
throw new IllegalArgumentException("Cannot deserialize JSONRPCMessage: " + jsonText);
|
||||
}
|
||||
|
||||
private void startOutboundProcessing() {
|
||||
this.getOutboundSink()
|
||||
.asFlux()
|
||||
// this bit is important since writes come from user threads and we
|
||||
// want to ensure that the actual writing happens on a dedicated thread
|
||||
.publishOn(outboundScheduler)
|
||||
.handle((message, s) -> {
|
||||
if (message != null) {
|
||||
try {
|
||||
this.processWriter.write(objectMapper.writeValueAsString(message));
|
||||
this.processWriter.newLine();
|
||||
this.processWriter.flush();
|
||||
s.next(message);
|
||||
} catch (IOException e) {
|
||||
s.error(new RuntimeException(e));
|
||||
}
|
||||
}
|
||||
})
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> closeGracefully() {
|
||||
|
||||
this.isRunning = false;
|
||||
|
||||
return Mono.whenDelayError(
|
||||
Mono.fromRunnable(() -> {
|
||||
try {
|
||||
this.processErrorReader.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).subscribeOn(errorScheduler),
|
||||
Mono.fromRunnable(() -> {
|
||||
try {
|
||||
this.processReader.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).subscribeOn(inboundScheduler),
|
||||
Mono.fromRunnable(() -> {
|
||||
try {
|
||||
this.processWriter.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}).subscribeOn(outboundScheduler))
|
||||
.then(Mono.whenDelayError(inboundScheduler.disposeGracefully(),
|
||||
outboundScheduler.disposeGracefully(),
|
||||
errorScheduler.disposeGracefully()))
|
||||
.then(Mono.fromRunnable(() -> {
|
||||
if (this.process != null) {
|
||||
var process = this.process.destroyForcibly();
|
||||
if (process.exitValue() != 0) {
|
||||
throw new RuntimeException("Failed to destroy process");
|
||||
}
|
||||
}
|
||||
}))
|
||||
.then()
|
||||
.subscribeOn(Schedulers.boundedElastic());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.client.util;
|
||||
|
||||
import reactor.util.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
* @since 1.0.0
|
||||
*/
|
||||
|
||||
public class Assert {
|
||||
/**
|
||||
* Assert that an object is not {@code null}.
|
||||
*
|
||||
* <pre class="code">
|
||||
* Assert.notNull(clazz, "The class must not be null");
|
||||
* </pre>
|
||||
*
|
||||
* @param object the object to check
|
||||
* @param message the exception message to use if the assertion fails
|
||||
* @throws IllegalArgumentException if the object is {@code null}
|
||||
*/
|
||||
public static void notNull(@Nullable Object object, String message) {
|
||||
if (object == null) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the given String contains valid text content; that is, it must not
|
||||
* be {@code null} and must contain at least one non-whitespace character.
|
||||
* <pre class="code">Assert.hasText(name, "'name' must not be empty");</pre>
|
||||
* @param text the String to check
|
||||
* @param message the exception message to use if the assertion fails
|
||||
* @throws IllegalArgumentException if the text does not contain valid text content
|
||||
* @see StringUtils#hasText
|
||||
*/
|
||||
public static void hasText(@Nullable String text, String message) {
|
||||
if (!hasText(text)) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the given {@code String} contains actual <em>text</em>.
|
||||
* <p>More specifically, this method returns {@code true} if the
|
||||
* {@code String} is not {@code null}, its length is greater than 0,
|
||||
* and it contains at least one non-whitespace character.
|
||||
* @param str the {@code String} to check (may be {@code null})
|
||||
* @return {@code true} if the {@code String} is not {@code null}, its
|
||||
* length is greater than 0, and it does not contain whitespace only
|
||||
* @see #hasText(CharSequence)
|
||||
* @see #hasLength(String)
|
||||
* @see Character#isWhitespace
|
||||
*/
|
||||
public static boolean hasText(@Nullable String str) {
|
||||
return (str != null && !str.isBlank());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,119 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.spec;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.Sinks;
|
||||
import org.springframework.ai.mcp.client.util.Assert;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCMessage;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
public abstract class AbstractMcpTransport implements McpTransport {
|
||||
|
||||
protected final ObjectMapper objectMapper;
|
||||
|
||||
private final Sinks.Many<String> errorSink;
|
||||
private final Sinks.Many<JSONRPCMessage> inboundSink;
|
||||
private final Sinks.Many<JSONRPCMessage> outboundSink;
|
||||
|
||||
private Consumer<JSONRPCMessage> inboundMessageHandler = message -> System.out
|
||||
.println("Received message: " + message);
|
||||
private Consumer<String> errorHandler = error -> System.err.println("Received error: " + error);
|
||||
|
||||
public AbstractMcpTransport() {
|
||||
this(new ObjectMapper());
|
||||
}
|
||||
|
||||
public AbstractMcpTransport(ObjectMapper objectMapper) {
|
||||
|
||||
Assert.notNull(objectMapper, "ObjectMapper must not be null");
|
||||
this.objectMapper = objectMapper;
|
||||
|
||||
// TODO: consider the effects of buffering here -> the inter-process pipes are
|
||||
// independent and the notifications can flood the client/server.
|
||||
// Potentially, the interest in reading could be communicated from one party
|
||||
// to the other so the Blocking IO Threads can pause consuming the stream
|
||||
// buffers when there is no expectation for reading.
|
||||
|
||||
this.errorSink = Sinks.many().unicast().onBackpressureBuffer();
|
||||
this.inboundSink = Sinks.many().unicast().onBackpressureBuffer();
|
||||
this.outboundSink = Sinks.many().unicast().onBackpressureBuffer();
|
||||
|
||||
this.handleIncomingMessages();
|
||||
}
|
||||
|
||||
public ObjectMapper getObjectMapper() {
|
||||
return this.objectMapper;
|
||||
}
|
||||
|
||||
private void handleIncomingMessages() {
|
||||
this.inboundSink.asFlux()
|
||||
.subscribe(message -> this.inboundMessageHandler.accept(message));
|
||||
}
|
||||
|
||||
private void handleIncomingErrors() {
|
||||
this.errorSink.asFlux().subscribe(e -> {
|
||||
this.errorHandler.accept(e);
|
||||
// System.err.println(e); TODO: log the error
|
||||
});
|
||||
}
|
||||
|
||||
protected Sinks.Many<JSONRPCMessage> getInboundSink() {
|
||||
return inboundSink;
|
||||
}
|
||||
|
||||
protected Sinks.Many<JSONRPCMessage> getOutboundSink() {
|
||||
return outboundSink;
|
||||
}
|
||||
|
||||
protected Sinks.Many<String> getErrorSink() {
|
||||
return errorSink;
|
||||
}
|
||||
|
||||
public void setInboudMessageHandler(Consumer<JSONRPCMessage> inboundMessageHandler) {
|
||||
this.inboundMessageHandler = inboundMessageHandler;
|
||||
}
|
||||
|
||||
public void setInboundErrorHandler(Consumer<String> errorHandler) {
|
||||
this.errorHandler = errorHandler;
|
||||
}
|
||||
|
||||
// Start processing incoming messages
|
||||
public void start() {
|
||||
this.handleIncomingErrors();
|
||||
this.handleIncomingMessages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> sendMessage(JSONRPCMessage message) {
|
||||
if (this.outboundSink.tryEmitNext(message).isSuccess()) {
|
||||
// TODO: essentially we could reschedule ourselves in some time and make
|
||||
// another attempt with the already read data but pause reading until
|
||||
// success
|
||||
// In this approach we delegate the retry and the backpressure onto the
|
||||
// caller. This might be enough for most cases.
|
||||
return Mono.empty();
|
||||
} else {
|
||||
return Mono.error(new RuntimeException("Failed to enqueue message"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,114 @@
|
|||
package org.springframework.ai.mcp.spec;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.core.publisher.MonoSink;
|
||||
import org.springframework.ai.mcp.client.util.Assert;
|
||||
|
||||
/**
|
||||
* Implementation of the MCP client session.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
public class DefaultMcpSession implements McpSession {
|
||||
|
||||
private final ConcurrentHashMap<Object, MonoSink<McpSchema.JSONRPCResponse>> pendingResponses = new ConcurrentHashMap<>();
|
||||
|
||||
private final Duration requestTimeout;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private final McpTransport transport;
|
||||
|
||||
public DefaultMcpSession(Duration requestTimeout, ObjectMapper objectMapper, McpTransport transport) {
|
||||
|
||||
Assert.notNull(objectMapper, "The ObjectMapper can not be null");
|
||||
Assert.notNull(requestTimeout, "The requstTimeout can not be null");
|
||||
Assert.notNull(transport, "The transport can not be null");
|
||||
|
||||
this.requestTimeout = requestTimeout;
|
||||
this.objectMapper = objectMapper;
|
||||
this.transport = transport;
|
||||
|
||||
this.transport.setInboudMessageHandler(message -> {
|
||||
|
||||
if ( message instanceof McpSchema.JSONRPCResponse response) {
|
||||
var sink = pendingResponses.remove(response.id());
|
||||
if (sink == null) {
|
||||
System.out.println("Unexpected response for unkown id " + response.id());
|
||||
} else {
|
||||
sink.success(response);
|
||||
}
|
||||
} else if ( message instanceof McpSchema.JSONRPCRequest request) {
|
||||
System.out.println("Client does not yet support server requests");
|
||||
} else if ( message instanceof McpSchema.JSONRPCNotification notification) {
|
||||
System.out.println("Notifications not yet supported");
|
||||
}
|
||||
});
|
||||
|
||||
this.transport.setInboundErrorHandler(error -> System.out.println("Error received " + error));
|
||||
|
||||
this.transport.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Mono<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef) {
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
|
||||
return Mono.<McpSchema.JSONRPCResponse>create(sink -> {
|
||||
this.pendingResponses.put(requestId, sink);
|
||||
McpSchema.JSONRPCRequest jsonrpcRequest = new McpSchema.JSONRPCRequest(McpSchema.JSONRPC_VERSION, method,
|
||||
requestId, requestParams);
|
||||
try {
|
||||
// TODO: This is non-blocking, but it's actually a synchronous call,
|
||||
// perhaps there's no need to make it return Mono?
|
||||
this.transport.sendMessage(jsonrpcRequest)
|
||||
// TODO: It's most efficient to create a dedicated
|
||||
// Subscriber here
|
||||
.subscribe(v -> {
|
||||
}, e -> {
|
||||
this.pendingResponses.remove(requestId);
|
||||
sink.error(e);
|
||||
});
|
||||
} catch (Exception e) {
|
||||
sink.error(e);
|
||||
}
|
||||
}).timeout(this.requestTimeout).handle((jsonRpcResponse, s) -> {
|
||||
if (jsonRpcResponse.error() != null) {
|
||||
s.error(new McpError(jsonRpcResponse.error()));
|
||||
} else {
|
||||
if (typeRef.getType().getTypeName().equals("java.lang.Void")) {
|
||||
s.complete();
|
||||
} else {
|
||||
s.next(this.objectMapper.convertValue(jsonRpcResponse.result(), typeRef));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> sendNotification(String method, Map<String, Object> params) {
|
||||
McpSchema.JSONRPCNotification jsonrpcNotification = new McpSchema.JSONRPCNotification(McpSchema.JSONRPC_VERSION,
|
||||
method, params);
|
||||
try {
|
||||
this.transport.sendMessage(jsonrpcNotification);
|
||||
} catch (Exception e) {
|
||||
return Mono.error(new McpError(e));
|
||||
}
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> closeGracefully(Duration timeout) {
|
||||
// TODO handle the timeout in transport
|
||||
return Mono.fromRunnable(this.transport::close);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.spec;
|
||||
|
||||
public class McpError extends RuntimeException {
|
||||
|
||||
public McpError(Object error) {
|
||||
super(error.toString());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,609 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.spec;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
|
||||
|
||||
/**
|
||||
* Based on the <a href="http://www.jsonrpc.org/specification">JSON-RPC 2.0
|
||||
* specification<a/> and the <a href=
|
||||
* "https://github.com/modelcontextprotocol/specification/blob/main/schema/schema.ts">Model
|
||||
* Context Protocol Schema</a>.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public class McpSchema {
|
||||
|
||||
public static final String LATEST_PROTOCOL_VERSION = "2024-11-05";
|
||||
|
||||
public static final String JSONRPC_VERSION = "2.0";
|
||||
|
||||
// ---------------------------
|
||||
// JSON-RPC Error Codes
|
||||
// ---------------------------
|
||||
public final class ErrorCodes {
|
||||
|
||||
public static final int PARSE_ERROR = -32700;
|
||||
|
||||
public static final int INVALID_REQUEST = -32600;
|
||||
|
||||
public static final int METHOD_NOT_FOUND = -32601;
|
||||
|
||||
public static final int INVALID_PARAMS = -32602;
|
||||
|
||||
public static final int INTERNAL_ERROR = -32603;
|
||||
|
||||
}
|
||||
|
||||
public sealed interface Request permits InitializeRequest, CallToolRequest, CreateMessageRequest, CompleteRequest, GetPromptRequest {
|
||||
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// JSON-RPC Message Types
|
||||
// ---------------------------
|
||||
public sealed interface JSONRPCMessage permits JSONRPCRequest, JSONRPCNotification, JSONRPCResponse {
|
||||
|
||||
String jsonrpc();
|
||||
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record JSONRPCRequest( // @formatter:off
|
||||
@JsonProperty("jsonrpc") String jsonrpc,
|
||||
@JsonProperty("method") String method,
|
||||
@JsonProperty("id") Object id,
|
||||
@JsonProperty("params") Object params) implements JSONRPCMessage {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record JSONRPCNotification( // @formatter:off
|
||||
@JsonProperty("jsonrpc") String jsonrpc,
|
||||
@JsonProperty("method") String method,
|
||||
@JsonProperty("params") Map<String, Object> params) implements JSONRPCMessage {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record JSONRPCResponse( // @formatter:off
|
||||
@JsonProperty("jsonrpc") String jsonrpc,
|
||||
@JsonProperty("id") Object id,
|
||||
@JsonProperty("result") Object result,
|
||||
@JsonProperty("error") JSONRPCError error) implements JSONRPCMessage {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record JSONRPCError(
|
||||
@JsonProperty("code") int code,
|
||||
@JsonProperty("message") String message,
|
||||
@JsonProperty("data") Object data) {
|
||||
}
|
||||
}// @formatter:on
|
||||
|
||||
// ---------------------------
|
||||
// Initialization
|
||||
// ---------------------------
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record InitializeRequest( // @formatter:off
|
||||
@JsonProperty("protocolVersion") String protocolVersion,
|
||||
@JsonProperty("capabilities") ClientCapabilities capabilities,
|
||||
@JsonProperty("clientInfo") Implementation clientInfo) implements Request {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record InitializeResult( // @formatter:off
|
||||
@JsonProperty("protocolVersion") String protocolVersion,
|
||||
@JsonProperty("capabilities") ServerCapabilities capabilities,
|
||||
@JsonProperty("serverInfo") Implementation serverInfo,
|
||||
@JsonProperty("instructions") String instructions) {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ClientCapabilities( // @formatter:off
|
||||
@JsonProperty("experimental") Map<String, Object> experimental,
|
||||
@JsonProperty("roots") RootCapabilities roots,
|
||||
@JsonProperty("sampling") Object sampling) {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record RootCapabilities(
|
||||
@JsonProperty("listChanged") Boolean listChanged) {
|
||||
}
|
||||
}// @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ServerCapabilities( // @formatter:off
|
||||
@JsonProperty("experimental") Map<String, Object> experimental,
|
||||
@JsonProperty("logging") Object logging,
|
||||
@JsonProperty("prompts") PromptCapabilities prompts,
|
||||
@JsonProperty("resources") ResourceCapabilities resources,
|
||||
@JsonProperty("tools") ToolCapabilities tools) {
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record PromptCapabilities(
|
||||
@JsonProperty("listChanged") Boolean listChanged) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ResourceCapabilities(
|
||||
@JsonProperty("subscribe") Boolean subscribe,
|
||||
@JsonProperty("listChanged") Boolean listChanged) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ToolCapabilities(
|
||||
@JsonProperty("listChanged") Boolean listChanged) {
|
||||
}
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record Implementation(// @formatter:off
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("version") String version) {
|
||||
} // @formatter:on
|
||||
|
||||
// Existing Enums and Base Types (from previous implementation)
|
||||
public enum Role {
|
||||
|
||||
USER, ASSISTANT
|
||||
|
||||
}
|
||||
|
||||
public enum LoggingLevel {
|
||||
|
||||
DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY
|
||||
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Resource Interfaces
|
||||
// ---------------------------
|
||||
/**
|
||||
* Base for objects that include optional annotations for the client. The client
|
||||
* can
|
||||
* use annotations to inform how objects are used or displayed
|
||||
*/
|
||||
public interface Annotated {
|
||||
|
||||
Annotations annotations();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param audience Describes who the intended customer of this object or data
|
||||
* is. It
|
||||
* can include multiple entries to indicate content useful for
|
||||
* multiple audiences
|
||||
* (e.g., `["user", "assistant"]`).
|
||||
* @param priority Describes how important this data is for operating the
|
||||
* server. A
|
||||
* value of 1 means "most important," and indicates that the
|
||||
* data is effectively
|
||||
* required, while 0 means "least important," and indicates that
|
||||
* the data is entirely
|
||||
* optional. It is a number between 0 and 1.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record Annotations( // @formatter:off
|
||||
@JsonProperty("audience") List<Role> audience,
|
||||
@JsonProperty("priority") Double priority) {
|
||||
} // @formatter:on
|
||||
|
||||
/**
|
||||
* A known resource that the server is capable of reading.
|
||||
*
|
||||
* @param uri the URI of the resource.
|
||||
* @param name A human-readable name for this resource. This can be used
|
||||
* by clients to
|
||||
* populate UI elements.
|
||||
* @param description A description of what this resource represents. This can
|
||||
* be used
|
||||
* by clients to improve the LLM's understanding of available
|
||||
* resources. It can be
|
||||
* thought of like a "hint" to the model.
|
||||
* @param mimeType The MIME type of this resource, if known.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public record Resource( // @formatter:off
|
||||
@JsonProperty("uri") String uri,
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("description") String description,
|
||||
@JsonProperty("mimeType") String mimeType,
|
||||
@JsonProperty("annotations") Annotations annotations) implements Annotated {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ResourceTemplate( // @formatter:off
|
||||
@JsonProperty("uriTemplate") String uriTemplate,
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("description") String description,
|
||||
@JsonProperty("mimeType") String mimeType,
|
||||
@JsonProperty("annotations") Annotations annotations) implements Annotated {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ListResourcesResult( // @formatter:off
|
||||
@JsonProperty("resources") List<Resource> resources,
|
||||
@JsonProperty("nextCursor") String nextCursor) {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ListResourceTemplatesResult( // @formatter:off
|
||||
@JsonProperty("resourceTemplates") List<ResourceTemplate> resourceTemplates,
|
||||
@JsonProperty("nextCursor") String nextCursor) {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ReadResourceRequest( // @formatter:off
|
||||
@JsonProperty("uri") String uri){
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ReadResourceResult( // @formatter:off
|
||||
@JsonProperty("contents") List<ResourceContents> contents){
|
||||
} // @formatter:on
|
||||
|
||||
/**
|
||||
* Sent from the client to request resources/updated notifications from the
|
||||
* server
|
||||
* whenever a particular resource changes.
|
||||
*
|
||||
* @param uri the URI of the resource to subscribe to. The URI can use any
|
||||
* protocol;
|
||||
* it is up to the server how to interpret it.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record SubscribeRequest( // @formatter:off
|
||||
@JsonProperty("uri") String uri){
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record UnsubscribeRequest( // @formatter:off
|
||||
@JsonProperty("uri") String uri){
|
||||
} // @formatter:on
|
||||
|
||||
/**
|
||||
* The contents of a specific resource or sub-resource.
|
||||
*/
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.DEDUCTION, include = As.PROPERTY)
|
||||
@JsonSubTypes({ @JsonSubTypes.Type(value = TextResourceContents.class, name = "text"),
|
||||
@JsonSubTypes.Type(value = BlobResourceContents.class, name = "blob") })
|
||||
public sealed interface ResourceContents permits TextResourceContents, BlobResourceContents {
|
||||
|
||||
/**
|
||||
* The URI of this resource.
|
||||
*
|
||||
* @return the URI of this resource.
|
||||
*/
|
||||
String uri();
|
||||
|
||||
/**
|
||||
* The MIME type of this resource.
|
||||
*
|
||||
* @return the MIME type of this resource.
|
||||
*/
|
||||
String mimeType();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Text contents of a resource.
|
||||
*
|
||||
* @param uri the URI of this resource.
|
||||
* @param mimeType the MIME type of this resource.
|
||||
* @param text the text of the resource. This must only be set if the
|
||||
* resource can
|
||||
* actually be represented as text (not binary data).
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record TextResourceContents( // @formatter:off
|
||||
@JsonProperty("uri") String uri,
|
||||
@JsonProperty("mimeType") String mimeType,
|
||||
@JsonProperty("text") String text) implements ResourceContents {
|
||||
} // @formatter:on
|
||||
|
||||
/**
|
||||
* Binary contents of a resource.
|
||||
*
|
||||
* @param uri the URI of this resource.
|
||||
* @param mimeType the MIME type of this resource.
|
||||
* @param blob a base64-encoded string representing the binary data of the
|
||||
* resource.
|
||||
* This must only be set if the resource can actually be
|
||||
* represented as binary data
|
||||
* (not text).
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record BlobResourceContents( // @formatter:off
|
||||
@JsonProperty("uri") String uri,
|
||||
@JsonProperty("mimeType") String mimeType,
|
||||
@JsonProperty("blob") String blob) implements ResourceContents {
|
||||
} // @formatter:on
|
||||
|
||||
// ---------------------------
|
||||
// Prompt Interfaces
|
||||
// ---------------------------
|
||||
/**
|
||||
* A prompt or prompt template that the server offers.
|
||||
*
|
||||
* @param name The name of the prompt or prompt template.
|
||||
* @param description An optional description of what this prompt provides.
|
||||
* @param arguments A list of arguments to use for templating the prompt.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record Prompt( // @formatter:off
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("description") String description,
|
||||
@JsonProperty("arguments") List<PromptArgument> arguments) {
|
||||
} // @formatter:on
|
||||
|
||||
/**
|
||||
* Describes an argument that a prompt can accept.
|
||||
*
|
||||
* @param name The name of the argument.
|
||||
* @param description A human-readable description of the argument.
|
||||
* @param required Whether this argument must be provided.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record PromptArgument( // @formatter:off
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("description") String description,
|
||||
@JsonProperty("required") Boolean required) {
|
||||
}// @formatter:on
|
||||
|
||||
/**
|
||||
* Describes a message returned as part of a prompt.
|
||||
*
|
||||
* This is similar to `SamplingMessage`, but also supports the embedding of
|
||||
* resources
|
||||
* from the MCP server.
|
||||
*
|
||||
* @param role The sender or recipient of messages and data in a
|
||||
* conversation.
|
||||
* @param content The content of the message of type {@link Content}.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record PromptMessage( // @formatter:off
|
||||
@JsonProperty("role") Role role,
|
||||
@JsonProperty("content") Content content) {
|
||||
} // @formatter:on
|
||||
|
||||
/**
|
||||
* The server's response to a prompts/list request from the client.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ListPromptsResult( // @formatter:off
|
||||
@JsonProperty("prompts") List<Prompt> prompts,
|
||||
@JsonProperty("nextCursor") String nextCursor) {
|
||||
}// @formatter:on
|
||||
|
||||
/**
|
||||
* Used by the client to get a prompt provided by the server.
|
||||
*
|
||||
* @param name The name of the prompt or prompt template.
|
||||
* @param arguments Arguments to use for templating the prompt.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record GetPromptRequest(// @formatter:off
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("arguments") Map<String, Object> arguments) implements Request {
|
||||
}// @formatter:off
|
||||
|
||||
/**
|
||||
* The server's response to a prompts/get request from the client.
|
||||
*
|
||||
* @param description An optional description for the prompt.
|
||||
* @param messages A list of messages to display as part of the prompt.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record GetPromptResult( // @formatter:off
|
||||
@JsonProperty("description") String description,
|
||||
@JsonProperty("messages") List<PromptMessage> messages) {
|
||||
} // @formatter:on
|
||||
|
||||
// ---------------------------
|
||||
// Tool Interfaces
|
||||
// ---------------------------
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ListToolsResult( // @formatter:off
|
||||
@JsonProperty("tools") List<Tool> tools,
|
||||
@JsonProperty("nextCursor") String nextCursor) {
|
||||
}// @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record Tool( // @formatter:off
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("description") String description,
|
||||
@JsonProperty("inputSchema") Map<String, Object> inputSchema) {
|
||||
} // @formatter:on
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record CallToolRequest(// @formatter:off
|
||||
@JsonProperty("name") String name,
|
||||
@JsonProperty("arguments") Map<String, Object> arguments) implements Request {
|
||||
}// @formatter:off
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record CallToolResult( // @formatter:off
|
||||
@JsonProperty("content") List<Content> content,
|
||||
@JsonProperty("isError") Boolean isError) {
|
||||
} // @formatter:on
|
||||
|
||||
// ---------------------------
|
||||
// Sampling Interfaces
|
||||
// ---------------------------
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record SamplingMessage(// @formatter:off
|
||||
@JsonProperty("role") Role role,
|
||||
@JsonProperty("content") Content content) {
|
||||
} // @formatter:on
|
||||
|
||||
// Sampling and Message Creation
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record CreateMessageRequest(List<SamplingMessage> messages, ModelPreferences modelPreferences,
|
||||
String systemPrompt, ContextInclusionStrategy includeContext, Double temperature, int maxTokens,
|
||||
List<String> stopSequences, Map<String, Object> metadata) implements Request {
|
||||
|
||||
public enum ContextInclusionStrategy {
|
||||
|
||||
NONE, THIS_SERVER, ALL_SERVERS
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record CreateMessageResult(Role role, Content content, String model, StopReason stopReason) {
|
||||
public enum StopReason {
|
||||
|
||||
END_TURN, STOP_SEQUENCE, MAX_TOKENS
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Model Preferences
|
||||
// ---------------------------
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ModelPreferences(List<ModelHint> hints, Double costPriority, Double speedPriority,
|
||||
Double intelligencePriority) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ModelHint(String name) {
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Pagination Interfaces
|
||||
// ---------------------------
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record PaginatedRequest(@JsonProperty("cursor") String cursor) {
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record PaginatedResult(@JsonProperty("nextCursor") String nextCursor) {
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Progress and Logging
|
||||
// ---------------------------
|
||||
public record ProgressNotification(String progressToken, double progress, Double total) {
|
||||
}
|
||||
|
||||
public record LoggingMessageNotification(LoggingLevel level, String logger, Object data) {
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Autocomplete
|
||||
// ---------------------------
|
||||
public record CompleteRequest(PromptOrResourceReference ref, CompleteArgument argument) implements Request {
|
||||
public sealed interface PromptOrResourceReference permits PromptReference, ResourceReference {
|
||||
|
||||
String type();
|
||||
|
||||
}
|
||||
|
||||
public record PromptReference(String type, String name) implements PromptOrResourceReference {
|
||||
}
|
||||
|
||||
public record ResourceReference(String type, String uri) implements PromptOrResourceReference {
|
||||
}
|
||||
|
||||
public record CompleteArgument(String name, String value) {
|
||||
}
|
||||
}
|
||||
|
||||
public record CompleteResult(CompleteCompletion completion) {
|
||||
public record CompleteCompletion(List<String> values, Integer total, Boolean hasMore) {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------
|
||||
// Content Types
|
||||
// ---------------------------
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
|
||||
@JsonSubTypes({ @JsonSubTypes.Type(value = TextContent.class, name = "text"),
|
||||
@JsonSubTypes.Type(value = ImageContent.class, name = "image"),
|
||||
@JsonSubTypes.Type(value = EmbeddedResource.class, name = "resource") })
|
||||
public sealed interface Content permits TextContent, ImageContent, EmbeddedResource {
|
||||
|
||||
String type();
|
||||
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record TextContent( // @formatter:off
|
||||
@JsonProperty("audience") List<Role> audience,
|
||||
@JsonProperty("priority") Double priority,
|
||||
@JsonProperty("type") String type,
|
||||
@JsonProperty("text") String text) implements Content { // @formatter:on
|
||||
|
||||
public TextContent {
|
||||
type = "text";
|
||||
}
|
||||
|
||||
public String type() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record ImageContent( // @formatter:off
|
||||
@JsonProperty("audience") List<Role> audience,
|
||||
@JsonProperty("priority") Double priority,
|
||||
@JsonProperty("type") String type,
|
||||
@JsonProperty("data") String data,
|
||||
@JsonProperty("mimeType") String mimeType) implements Content { // @formatter:on
|
||||
|
||||
public ImageContent {
|
||||
type = "image";
|
||||
}
|
||||
|
||||
public String type() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record EmbeddedResource( // @formatter:off
|
||||
@JsonProperty("audience") List<Role> audience,
|
||||
@JsonProperty("priority") Double priority,
|
||||
@JsonProperty("type") String type,
|
||||
@JsonProperty("resource") ResourceContents resource) implements Content { // @formatter:on
|
||||
|
||||
public EmbeddedResource {
|
||||
type = "resource";
|
||||
}
|
||||
|
||||
public String type() {
|
||||
return type;
|
||||
}
|
||||
}
|
||||
|
||||
// Roots
|
||||
@JsonInclude(JsonInclude.Include.NON_ABSENT)
|
||||
public record Root( // @formatter:off
|
||||
@JsonProperty("uri") String uri,
|
||||
@JsonProperty("name") String name) {
|
||||
} // @formatter:on
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.spec;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* Represents a Model Control Protocol (MCP) session that handles communication between
|
||||
* clients and the server. This interface provides methods for sending requests
|
||||
* and notifications, as well as managing the session lifecycle.
|
||||
*
|
||||
* <p>The session operates asynchronously using Project Reactor's {@link Mono} type
|
||||
* for non-blocking operations. It supports both request-response patterns and
|
||||
* one-way notifications.</p>
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
public interface McpSession {
|
||||
|
||||
/**
|
||||
* Sends a request to the model server and expects a response of type T.
|
||||
*
|
||||
* <p>This method handles the request-response pattern where a response is expected
|
||||
* from the server. The response type is determined by the provided TypeReference.</p>
|
||||
*
|
||||
* @param <T> the type of the expected response
|
||||
* @param method the name of the method to be called on the server
|
||||
* @param requestParams the parameters to be sent with the request
|
||||
* @param typeRef the TypeReference describing the expected response type
|
||||
* @return a Mono that will emit the response when received
|
||||
*/
|
||||
<T> Mono<T> sendRequest(String method, Object requestParams, TypeReference<T> typeRef);
|
||||
|
||||
/**
|
||||
* Sends a notification to the model server without parameters.
|
||||
*
|
||||
* <p>This method implements the notification pattern where no response is expected
|
||||
* from the server. It's useful for fire-and-forget scenarios.</p>
|
||||
*
|
||||
* @param method the name of the notification method to be called on the server
|
||||
* @return a Mono that completes when the notification has been sent
|
||||
*/
|
||||
default Mono<Void> sendNotification(String method) {
|
||||
return sendNotification(method, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a notification to the model server with parameters.
|
||||
*
|
||||
* <p>Similar to {@link #sendNotification(String)} but allows sending additional
|
||||
* parameters with the notification.</p>
|
||||
*
|
||||
* @param method the name of the notification method to be called on the server
|
||||
* @param params a map of parameters to be sent with the notification
|
||||
* @return a Mono that completes when the notification has been sent
|
||||
*/
|
||||
Mono<Void> sendNotification(String method, Map<String, Object> params);
|
||||
|
||||
/**
|
||||
* Gracefully closes the session with a specified timeout.
|
||||
*
|
||||
* <p>This method attempts to close the session cleanly, waiting for any pending
|
||||
* operations to complete up to the specified timeout duration.</p>
|
||||
*
|
||||
* @param timeout the maximum duration to wait for the session to close
|
||||
* @return a Mono that completes when the session has been closed
|
||||
*/
|
||||
Mono<Void> closeGracefully(Duration timeout);
|
||||
}
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.spec;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCMessage;
|
||||
|
||||
/**
|
||||
* Defines the asynchronous transport layer for the Model Context Protocol
|
||||
* (MCP).
|
||||
*
|
||||
* <p>
|
||||
* The McpTransport interface provides the foundation for implementing custom
|
||||
* transport
|
||||
* mechanisms in the Model Context Protocol. It handles the bidirectional
|
||||
* communication between
|
||||
* the client and server components, supporting asynchronous message exchange
|
||||
* using JSON-RPC format.
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* Implementations of this interface are responsible for:
|
||||
* </p>
|
||||
* <ul>
|
||||
* <li>Managing the lifecycle of the transport connection</li>
|
||||
* <li>Handling incoming messages and errors from the server</li>
|
||||
* <li>Sending outbound messages to the server</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>
|
||||
* The transport layer is designed to be protocol-agnostic, allowing for various
|
||||
* implementations
|
||||
* such as WebSocket, HTTP, or custom protocols.
|
||||
* </p>
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @author Dariusz Jędrzejczyk
|
||||
*/
|
||||
public interface McpTransport {
|
||||
|
||||
/**
|
||||
* Initializes and starts the transport connection.
|
||||
*
|
||||
* <p>
|
||||
* This method should be called before any message exchange can occur. It sets
|
||||
* up
|
||||
* the necessary resources and establishes the connection to the server.
|
||||
* </p>
|
||||
*/
|
||||
void start();
|
||||
|
||||
/**
|
||||
* Closes the transport connection and releases any associated resources.
|
||||
*
|
||||
* <p>
|
||||
* This method ensures proper cleanup of resources when the transport is no
|
||||
* longer needed.
|
||||
* It should handle the graceful shutdown of any active connections.
|
||||
* </p>
|
||||
*/
|
||||
default void close() {
|
||||
this.closeGracefully().subscribe();
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the transport connection and releases any associated resources
|
||||
* asynchronously.
|
||||
*
|
||||
* @return a {@link Mono<Void>} that completes when the connection has been
|
||||
* closed.
|
||||
*/
|
||||
Mono<Void> closeGracefully();
|
||||
|
||||
/**
|
||||
* Sets the handler for processing incoming messages from the server.
|
||||
*
|
||||
* <p>
|
||||
* The provided handler will be called whenever a new message is received from
|
||||
* the server.
|
||||
* Messages are expected to follow the JSON-RPC format as defined in the MCP
|
||||
* specification.
|
||||
* </p>
|
||||
*
|
||||
* @param inboundMessageHandler a consumer that processes incoming
|
||||
* {@link JSONRPCMessage}s
|
||||
*/
|
||||
void setInboudMessageHandler(Consumer<JSONRPCMessage> inboundMessageHandler);
|
||||
|
||||
/**
|
||||
* Sets the handler for processing transport-level errors.
|
||||
*
|
||||
* <p>
|
||||
* The provided handler will be called when errors occur during transport
|
||||
* operations,
|
||||
* such as connection failures or protocol violations.
|
||||
* </p>
|
||||
*
|
||||
* @param inboundErrorHandler a consumer that processes error messages
|
||||
*/
|
||||
void setInboundErrorHandler(Consumer<String> inboundErrorHandler);
|
||||
|
||||
/**
|
||||
* Sends a message to the server asynchronously.
|
||||
*
|
||||
* <p>
|
||||
* This method handles the transmission of messages to the server in an
|
||||
* asynchronous manner.
|
||||
* Messages are sent in JSON-RPC format as specified by the MCP protocol.
|
||||
* </p>
|
||||
*
|
||||
* @param message the {@link JSONRPCMessage} to be sent to the server
|
||||
* @return a {@link Mono<Void>} that completes when the message has been sent
|
||||
*/
|
||||
Mono<Void> sendMessage(JSONRPCMessage message);
|
||||
}
|
||||
|
|
@ -0,0 +1,80 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.attic;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.ai.mcp.client.McpClient;
|
||||
import org.springframework.ai.mcp.client.McpSyncClient;
|
||||
import org.springframework.ai.mcp.client.stdio.ServerParameters;
|
||||
import org.springframework.ai.mcp.client.stdio.StdioServerTransport;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListResourcesResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListToolsResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Resource;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public class ClientSessionTests2 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
var stdioParams = ServerParameters.builder("uv")
|
||||
.args("--directory", "dir", "run", "mcp-server-sqlite",
|
||||
"--db-path", "~/test.db")
|
||||
.build();
|
||||
|
||||
try (McpSyncClient clientSession =
|
||||
McpClient.sync(new StdioServerTransport(stdioParams),
|
||||
Duration.ofSeconds(10), new ObjectMapper())) {
|
||||
|
||||
clientSession.initialize();
|
||||
|
||||
ListToolsResult tools = clientSession.listTools(null);
|
||||
System.out.println("Tools: " + tools);
|
||||
|
||||
clientSession.ping();
|
||||
|
||||
// CallToolRequest callToolRequest = new CallToolRequest("echo",
|
||||
// Map.of("message", "Hello MCP Spring AI!"));
|
||||
// CallToolResult callToolResult =
|
||||
// clientSession.callTool(callToolRequest);
|
||||
// System.out.println("Call Tool Result: " + callToolResult);
|
||||
// //
|
||||
// clientSession.sendRootsListChanged();
|
||||
|
||||
// Resources
|
||||
ListResourcesResult resources = clientSession.listResources(null);
|
||||
System.out.println("Resources Size: " + resources.resources().size());
|
||||
System.out.println("Resources: " + resources);
|
||||
for (Resource resource : resources.resources()) {
|
||||
System.out.println(clientSession.readResource(resource));
|
||||
|
||||
}
|
||||
|
||||
// var resourceTemplate = clientSession.listResourceTemplates(null);
|
||||
// System.out.println("Resource Templates: " + resourceTemplate);
|
||||
|
||||
// stdioClient.awaitForExit();
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.attic;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.ai.mcp.client.McpClient;
|
||||
import org.springframework.ai.mcp.client.McpSyncClient;
|
||||
import org.springframework.ai.mcp.client.stdio.ServerParameters;
|
||||
import org.springframework.ai.mcp.client.stdio.StdioServerTransport;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListResourcesResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListToolsResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Resource;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public class ClientSessionTests3 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
var stdioParams = ServerParameters.builder("uv")
|
||||
.args("--directory", "dir", "run", "mcp-server-sqlite",
|
||||
"--db-path", "~/test.db")
|
||||
.build();
|
||||
|
||||
|
||||
McpSyncClient clientSession = null;
|
||||
try {
|
||||
|
||||
clientSession = McpClient.sync(new StdioServerTransport(stdioParams),
|
||||
Duration.ofSeconds(10), new ObjectMapper());
|
||||
|
||||
clientSession.initialize();
|
||||
|
||||
ListToolsResult tools = clientSession.listTools(null);
|
||||
System.out.println("Tools: " + tools);
|
||||
|
||||
clientSession.ping();
|
||||
|
||||
// Resources
|
||||
ListResourcesResult resources = clientSession.listResources(null);
|
||||
System.out.println("Resources Size: " + resources.resources().size());
|
||||
System.out.println("Resources: " + resources);
|
||||
for (Resource resource : resources.resources()) {
|
||||
System.out.println(clientSession.readResource(resource));
|
||||
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
finally {
|
||||
if (clientSession != null) {
|
||||
clientSession.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,180 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.client;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.springframework.ai.mcp.client.stdio.ServerParameters;
|
||||
import org.springframework.ai.mcp.client.stdio.StdioServerTransport;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.CallToolRequest;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.GetPromptRequest;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Prompt;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Resource;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Tool;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* Unit tests for MCP Client Session functionality.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class McpAsyncClientTests {
|
||||
|
||||
private McpAsyncClient mcpAsyncClient;
|
||||
|
||||
private ServerParameters stdioParams;
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
private static final String TEST_MESSAGE = "Hello MCP Spring AI!";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
stdioParams = ServerParameters.builder("npx")
|
||||
.args("-y", "@modelcontextprotocol/server-everything", "dir")
|
||||
.build();
|
||||
|
||||
assertThatCode(() -> {
|
||||
mcpAsyncClient = McpClient.async(new StdioServerTransport(stdioParams), TIMEOUT, new ObjectMapper());
|
||||
mcpAsyncClient.initialize();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
// if (mcpSyncClient != null) {
|
||||
// assertThatCode(() -> mcpSyncClient.close()).doesNotThrowAnyException();
|
||||
// }
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConstructorWithInvalidArguments() {
|
||||
assertThatThrownBy(() -> McpClient.sync(null, TIMEOUT, new ObjectMapper()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
assertThatThrownBy(() -> McpClient.sync(new StdioServerTransport(stdioParams), null, new ObjectMapper()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
assertThatThrownBy(() -> McpClient.sync(new StdioServerTransport(stdioParams), TIMEOUT, null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15) // Giving extra time beyond the client timeout
|
||||
void testListTools() {
|
||||
mcpAsyncClient.listTools(null).subscribe(result -> {
|
||||
assertThat(result.tools()).isNotNull().isNotEmpty();
|
||||
|
||||
Tool firstTool = result.tools().get(0);
|
||||
assertThat(firstTool.name()).isNotNull();
|
||||
assertThat(firstTool.description()).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testPing() {
|
||||
assertThatCode(() -> mcpAsyncClient.ping().block()).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testCallTool() {
|
||||
CallToolRequest callToolRequest = new CallToolRequest("echo", Map.of("message", TEST_MESSAGE));
|
||||
|
||||
mcpAsyncClient.callTool(callToolRequest).subscribe(callToolResult -> {
|
||||
assertThat(callToolResult).isNotNull().satisfies(result -> {
|
||||
assertThat(result.content()).isNotNull();
|
||||
assertThat(result.isError()).isNull();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testCallToolWithInvalidTool() {
|
||||
CallToolRequest invalidRequest = new CallToolRequest("nonexistent_tool", Map.of("message", TEST_MESSAGE));
|
||||
|
||||
assertThatThrownBy(() -> mcpAsyncClient.callTool(invalidRequest).block()).isInstanceOf(Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testRootsListChanged() {
|
||||
assertThatCode(() -> mcpAsyncClient.sendRootsListChanged().block()).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testListResources() {
|
||||
mcpAsyncClient.listResources(null).subscribe(resources -> {
|
||||
assertThat(resources).isNotNull().satisfies(result -> {
|
||||
assertThat(result.resources()).isNotNull();
|
||||
|
||||
if (!result.resources().isEmpty()) {
|
||||
Resource firstResource = result.resources().get(0);
|
||||
assertThat(firstResource.uri()).isNotNull();
|
||||
assertThat(firstResource.name()).isNotNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testMcpAsyncClientState() {
|
||||
assertThat(mcpAsyncClient).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testListPrompts() {
|
||||
mcpAsyncClient.listPrompts(null).subscribe(prompts -> {
|
||||
assertThat(prompts).isNotNull()
|
||||
.satisfies(result -> {
|
||||
assertThat(result.prompts()).isNotNull();
|
||||
|
||||
if (!result.prompts().isEmpty()) {
|
||||
Prompt firstPrompt = result.prompts().get(0);
|
||||
assertThat(firstPrompt.name()).isNotNull();
|
||||
assertThat(firstPrompt.description()).isNotNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testGetPrompt() {
|
||||
mcpAsyncClient.getPrompt(new GetPromptRequest("simple_prompt", Map.of())).subscribe(prompt -> {
|
||||
assertThat(prompt).isNotNull()
|
||||
.satisfies(result -> {
|
||||
assertThat(result.description()).isNotNull();
|
||||
assertThat(result.messages()).isNotEmpty();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.client;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.springframework.ai.mcp.client.stdio.ServerParameters;
|
||||
import org.springframework.ai.mcp.client.stdio.StdioServerTransport;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.CallToolRequest;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.CallToolResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListResourcesResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.ListToolsResult;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Resource;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.TextContent;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.Tool;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/**
|
||||
* Unit tests for MCP Client Session functionality.
|
||||
*
|
||||
* @author Christian Tzolov
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class McpSyncClientTests {
|
||||
|
||||
private McpSyncClient mcpSyncClient;
|
||||
|
||||
private ServerParameters stdioParams;
|
||||
|
||||
private static final Duration TIMEOUT = Duration.ofSeconds(10);
|
||||
|
||||
private static final String TEST_MESSAGE = "Hello MCP Spring AI!";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
stdioParams = ServerParameters.builder("npx")
|
||||
.args("-y", "@modelcontextprotocol/server-everything", "dir")
|
||||
.build();
|
||||
|
||||
assertThatCode(() -> {
|
||||
mcpSyncClient = McpClient.sync(new StdioServerTransport(stdioParams), TIMEOUT, new ObjectMapper());
|
||||
mcpSyncClient.initialize();
|
||||
}).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (mcpSyncClient != null) {
|
||||
assertThatCode(() -> mcpSyncClient.close()).doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConstructorWithInvalidArguments() {
|
||||
assertThatThrownBy(() -> McpClient.sync(null, TIMEOUT, new ObjectMapper()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
assertThatThrownBy(() -> McpClient.sync(new StdioServerTransport(stdioParams), null, new ObjectMapper()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
|
||||
assertThatThrownBy(() -> McpClient.sync(new StdioServerTransport(stdioParams), TIMEOUT, null))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15) // Giving extra time beyond the client timeout
|
||||
void testListTools() {
|
||||
ListToolsResult tools = mcpSyncClient.listTools(null);
|
||||
|
||||
assertThat(tools).isNotNull().satisfies(result -> {
|
||||
assertThat(result.tools()).isNotNull().isNotEmpty();
|
||||
|
||||
Tool firstTool = result.tools().get(0);
|
||||
assertThat(firstTool.name()).isNotNull();
|
||||
assertThat(firstTool.description()).isNotNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15) // Giving extra time beyond the client timeout
|
||||
void testCallTools() {
|
||||
CallToolResult toolResult = mcpSyncClient.callTool(new CallToolRequest("add", Map.of("a", 3, "b", 4)));
|
||||
|
||||
assertThat(toolResult).isNotNull().satisfies(result -> {
|
||||
|
||||
assertThat(result.content()).hasSize(1);
|
||||
|
||||
TextContent content = (TextContent) result.content().get(0);
|
||||
|
||||
assertThat(content).isNotNull();
|
||||
assertThat(content.text()).isNotNull();
|
||||
assertThat(content.text()).contains("7");
|
||||
|
||||
System.out.println(content);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testPing() {
|
||||
assertThatCode(() -> mcpSyncClient.ping()).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testCallTool() {
|
||||
CallToolRequest callToolRequest = new CallToolRequest("echo", Map.of("message", TEST_MESSAGE));
|
||||
|
||||
CallToolResult callToolResult = mcpSyncClient.callTool(callToolRequest);
|
||||
|
||||
assertThat(callToolResult).isNotNull().satisfies(result -> {
|
||||
assertThat(result.content()).isNotNull();
|
||||
assertThat(result.isError()).isNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testCallToolWithInvalidTool() {
|
||||
CallToolRequest invalidRequest = new CallToolRequest("nonexistent_tool", Map.of("message", TEST_MESSAGE));
|
||||
|
||||
assertThatThrownBy(() -> mcpSyncClient.callTool(invalidRequest)).isInstanceOf(Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testRootsListChanged() {
|
||||
assertThatCode(() -> mcpSyncClient.sendRootsListChanged()).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(15)
|
||||
void testListResources() {
|
||||
ListResourcesResult resources = mcpSyncClient.listResources(null);
|
||||
|
||||
assertThat(resources).isNotNull().satisfies(result -> {
|
||||
assertThat(result.resources()).isNotNull();
|
||||
|
||||
if (!result.resources().isEmpty()) {
|
||||
Resource firstResource = result.resources().get(0);
|
||||
assertThat(firstResource.uri()).isNotNull();
|
||||
assertThat(firstResource.name()).isNotNull();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClientSessionState() {
|
||||
assertThat(mcpSyncClient).isNotNull();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,132 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.client.stdio;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* @author Christian Tzolov
|
||||
*
|
||||
*/
|
||||
public class StdioServerTransportTests {
|
||||
|
||||
@Mock
|
||||
private ServerParameters mockParams;
|
||||
|
||||
@Mock
|
||||
private Process mockProcess;
|
||||
|
||||
@Mock
|
||||
private BufferedReader mockErrorReader;
|
||||
|
||||
@Mock
|
||||
private BufferedReader mockReader;
|
||||
|
||||
@Mock
|
||||
private BufferedWriter mockWriter;
|
||||
|
||||
@Mock
|
||||
ProcessBuilder mockProcessBuilder;
|
||||
|
||||
private StdioServerTransport stdioServerTransport;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
when(mockParams.getCommand()).thenReturn("dummyCommand");
|
||||
when(mockParams.getArgs()).thenReturn(List.of("arg1", "arg2"));
|
||||
when(mockParams.getEnv()).thenReturn(new HashMap<>(Map.of("key", "value")));
|
||||
stdioServerTransport = new StdioServerTransport(mockParams, new ObjectMapper()) {
|
||||
@Override
|
||||
protected ProcessBuilder getProcessBuilder() {
|
||||
return mockProcessBuilder;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStart_Success() throws IOException {
|
||||
// Arrange
|
||||
when(mockProcessBuilder.start()).thenReturn(mockProcess);
|
||||
when(mockProcess.getInputStream()).thenReturn(mock(InputStream.class));
|
||||
when(mockProcess.getOutputStream()).thenReturn(mock(OutputStream.class));
|
||||
when(mockProcess.errorReader()).thenReturn(mockErrorReader);
|
||||
when(mockProcess.inputReader()).thenReturn(mockReader);
|
||||
when(mockProcess.outputWriter()).thenReturn(mockWriter);
|
||||
|
||||
// Act
|
||||
stdioServerTransport.start();
|
||||
|
||||
// Assert
|
||||
// TODO: assertThat(stdioServerTransport.isRunning).isTrue();
|
||||
verify(mockProcessBuilder).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStart_ProcessStartFailure() throws IOException {
|
||||
// Arrange
|
||||
when(mockProcessBuilder.start()).thenThrow(new IOException("Failed to start process"));
|
||||
|
||||
// Act & Assert
|
||||
RuntimeException exception = assertThrows(RuntimeException.class, () -> stdioServerTransport.start());
|
||||
assertThat(exception.getMessage()).contains("Failed to start process with command");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStart_NullInputStream() throws IOException {
|
||||
// Arrange
|
||||
when(mockProcessBuilder.start()).thenReturn(mockProcess);
|
||||
when(mockProcess.getInputStream()).thenReturn(null);
|
||||
when(mockProcess.getOutputStream()).thenReturn(mock(OutputStream.class));
|
||||
|
||||
// Act & Assert
|
||||
RuntimeException exception = assertThrows(RuntimeException.class, () -> stdioServerTransport.start());
|
||||
assertThat(exception.getMessage()).contains("Process input or output stream is null");
|
||||
verify(mockProcess).destroy();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStart_NullOutputStream() throws IOException {
|
||||
// Arrange
|
||||
when(mockProcessBuilder.start()).thenReturn(mockProcess);
|
||||
when(mockProcess.getInputStream()).thenReturn(mock(InputStream.class));
|
||||
when(mockProcess.getOutputStream()).thenReturn(null);
|
||||
|
||||
// Act & Assert
|
||||
RuntimeException exception = assertThrows(RuntimeException.class, () -> stdioServerTransport.start());
|
||||
assertThat(exception.getMessage()).contains("Process input or output stream is null");
|
||||
verify(mockProcess).destroy();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
/*
|
||||
* Copyright 2024 - 2024 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.spec;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCMessage;
|
||||
import org.springframework.ai.mcp.spec.McpSchema.JSONRPCRequest;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class DefaultMcpTransportTests {
|
||||
|
||||
private AbstractMcpTransport transport;
|
||||
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
objectMapper = new ObjectMapper();
|
||||
transport = new AbstractMcpTransport(objectMapper) {
|
||||
@Override
|
||||
public Mono<Void> closeGracefully() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void constructorShouldValidateObjectMapper() {
|
||||
assertThatThrownBy(() -> new AbstractMcpTransport(null) {
|
||||
@Override
|
||||
public Mono<Void> closeGracefully() {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessage("ObjectMapper must not be null");
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultConstructorShouldCreateValidInstance() {
|
||||
AbstractMcpTransport defaultTransport = new AbstractMcpTransport() {
|
||||
@Override
|
||||
public Mono<Void> closeGracefully() {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
assertThat(defaultTransport.getObjectMapper()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void customObjectMapperConstructorShouldCreateValidInstance() {
|
||||
assertThat(transport.getObjectMapper()).isSameAs(objectMapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendMessageShouldEmitToOutboundSink() {
|
||||
JSONRPCRequest message = new JSONRPCRequest(
|
||||
"2.0",
|
||||
"test",
|
||||
1,
|
||||
null);
|
||||
|
||||
AtomicReference<JSONRPCMessage> receivedMessage = new AtomicReference<>();
|
||||
transport.getOutboundSink().asFlux().subscribe(receivedMessage::set);
|
||||
|
||||
Mono<Void> result = transport.sendMessage(message);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.verifyComplete();
|
||||
|
||||
assertThat(receivedMessage.get())
|
||||
.isNotNull()
|
||||
.satisfies(msg -> {
|
||||
assertThat(((JSONRPCRequest) msg).jsonrpc()).isEqualTo("2.0");
|
||||
assertThat(((JSONRPCRequest) msg).method()).isEqualTo("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void customInboundMessageHandlerShouldReceiveMessages() {
|
||||
AtomicReference<JSONRPCMessage> receivedMessage = new AtomicReference<>();
|
||||
transport.setInboudMessageHandler(receivedMessage::set);
|
||||
transport.start();
|
||||
|
||||
JSONRPCRequest message = new JSONRPCRequest(
|
||||
"2.0",
|
||||
"test",
|
||||
1,
|
||||
null);
|
||||
|
||||
transport.getInboundSink().tryEmitNext(message);
|
||||
|
||||
assertThat(receivedMessage.get())
|
||||
.isNotNull()
|
||||
.satisfies(msg -> {
|
||||
assertThat(((JSONRPCRequest) msg).jsonrpc()).isEqualTo("2.0");
|
||||
assertThat(((JSONRPCRequest) msg).method()).isEqualTo("test");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void customErrorHandlerShouldReceiveErrors() {
|
||||
AtomicReference<String> receivedError = new AtomicReference<>();
|
||||
transport.setInboundErrorHandler(receivedError::set);
|
||||
transport.start();
|
||||
|
||||
String errorMessage = "Test error";
|
||||
transport.getErrorSink().tryEmitNext(errorMessage);
|
||||
|
||||
assertThat(receivedError.get())
|
||||
.isNotNull()
|
||||
.isEqualTo(errorMessage);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startShouldInitializeMessageAndErrorHandling() {
|
||||
AtomicReference<JSONRPCMessage> receivedMessage = new AtomicReference<>();
|
||||
AtomicReference<String> receivedError = new AtomicReference<>();
|
||||
|
||||
transport.setInboudMessageHandler(receivedMessage::set);
|
||||
transport.setInboundErrorHandler(receivedError::set);
|
||||
transport.start();
|
||||
|
||||
JSONRPCRequest message = new JSONRPCRequest(
|
||||
"2.0",
|
||||
"test",
|
||||
1,
|
||||
null);
|
||||
|
||||
String errorMessage = "Test error";
|
||||
|
||||
transport.getInboundSink().tryEmitNext(message);
|
||||
transport.getErrorSink().tryEmitNext(errorMessage);
|
||||
|
||||
assertThat(receivedMessage.get()).isNotNull();
|
||||
assertThat(receivedError.get()).isEqualTo(errorMessage);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendMessageShouldReturnErrorWhenSinkFails() {
|
||||
JSONRPCRequest message = new JSONRPCRequest(
|
||||
"2.0",
|
||||
"test",
|
||||
1,
|
||||
null);
|
||||
// Close the sink to simulate failure
|
||||
transport.getOutboundSink().tryEmitComplete();
|
||||
|
||||
Mono<Void> result = transport.sendMessage(message);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.verifyErrorSatisfies(error -> assertThat(error)
|
||||
.isInstanceOf(RuntimeException.class)
|
||||
.hasMessage("Failed to enqueue message"));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package org.springframework.ai.mcp.spring.boot;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.ai.mcp.client.McpClient;
|
||||
import org.springframework.ai.mcp.client.McpSyncClient;
|
||||
import org.springframework.ai.mcp.client.stdio.ServerParameters;
|
||||
import org.springframework.ai.mcp.client.stdio.StdioServerTransport;
|
||||
import org.springframework.ai.mcp.spring.McpFunctionCallback;
|
||||
|
||||
import org.springframework.ai.chat.client.ChatClient;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@SpringBootApplication
|
||||
public class McpApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(McpApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CommandLineRunner test(ChatClient.Builder chatClientBuilder, List<McpFunctionCallback> functionCallbacks) {
|
||||
|
||||
return args -> {
|
||||
|
||||
var chatClient = chatClientBuilder.defaultFunctions(functionCallbacks.toArray(new McpFunctionCallback[0]))
|
||||
.build();
|
||||
|
||||
var response = chatClient.prompt("What is the content of the test.txt file?").call().content();
|
||||
|
||||
System.out.println(response);
|
||||
|
||||
response = chatClient.prompt(
|
||||
"Please summarize the content of the test.txt file, covert the result in markdown format and store it into test.md")
|
||||
.call()
|
||||
.content();
|
||||
System.out.println("Summary:" + response);
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public List<McpFunctionCallback> functionCallbacks(McpSyncClient mcpClient) {
|
||||
|
||||
return mcpClient.listTools(null)
|
||||
.tools()
|
||||
.stream()
|
||||
.map(tool -> new McpFunctionCallback(mcpClient, tool))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Bean(destroyMethod = "close")
|
||||
public McpSyncClient clientSession() {
|
||||
|
||||
var stdioParams = ServerParameters.builder("npx")
|
||||
.args("-y", "@modelcontextprotocol/server-filesystem",
|
||||
"/Users/christiantzolov/Dev/projects/demo/mcp-server/dir")
|
||||
.build();
|
||||
|
||||
McpSyncClient mcpClient = null;
|
||||
try {
|
||||
mcpClient = McpClient.sync(new StdioServerTransport(stdioParams),
|
||||
Duration.ofSeconds(10), new ObjectMapper());
|
||||
|
||||
var init = mcpClient.initialize();
|
||||
|
||||
System.out.println("MCP Initialized: " + init);
|
||||
|
||||
return mcpClient;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue