Package com.tnsai.mcp.client
Class McpClient
java.lang.Object
com.tnsai.mcp.client.McpClient
Client for connecting to Model Context Protocol (MCP) servers.
Features:
- Full MCP protocol support with initialize handshake
- Tool discovery and execution
- Resource listing, reading, and template support
- Prompt template support
- Sampling (LLM generation via server)
- Completion/autocomplete
- Roots exchange
- Logging level control
- Server notification handling
- Configurable timeouts
Example usage:
McpClient client = McpClient.builder()
.transport(new StdioTransport("npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"))
.clientName("MyApp")
.clientVersion("1.0.0")
.requestTimeout(Duration.ofSeconds(30))
.build();
client.connect();
client.initialize();
List<McpToolDefinition> tools = client.listTools();
JsonNode result = client.executeTool("read_file", Map.of("path", "/tmp/test.txt"));
client.disconnect();
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classBuilder for creating McpClient instances.static classException for MCP-related errors.static classServer information returned during initialization. -
Constructor Summary
ConstructorsConstructorDescriptionMcpClient(McpTransport transport) Creates an McpClient with the given transport and default settings. -
Method Summary
Modifier and TypeMethodDescriptionvoidAdds a root and notifies the server.static McpClient.Builderbuilder()Creates a new builder for McpClient.complete(CompletionRequest request) Requests auto-completion suggestions from the server.completePromptArgument(String promptName, String argName, String partialValue) Requests prompt argument completion suggestions.completeResourceUri(String partialUri) Requests resource URI completion suggestions.voidconnect()Connects to the MCP server.static McpClientcreate(McpTransport transport) Creates an McpClient with the given transport and default settings.createSamplingMessage(SamplingRequest request) Sends a sampling/createMessage request to the server to generate text.voidDisconnects from the MCP server.com.fasterxml.jackson.databind.JsonNodeexecuteTool(String toolName, Map<String, Object> arguments) Executes a tool on the server.com.fasterxml.jackson.databind.JsonNodeGets a prompt with the given arguments.getRoots()Returns the current list of roots.Returns the server capabilities after initialization.Returns the server info after initialization.voidInitializes the MCP session with capability exchange.booleanChecks if the client is connected to the server.booleanChecks if the client has completed initialization.Lists available prompts on the server.Lists available resources on the server.Lists available resource templates on the server.Lists available tools on the server.readResource(String uri) Reads the content of a resource.voidremoveRoot(Root root) Removes a root and notifies the server.voidsetLogLevel(LogLevel level) Sets the minimum log level on the server.voidsetOnLogMessage(Consumer<LogMessage> handler) Sets a handler for log message notifications from the server.voidsetOnNotification(Consumer<com.fasterxml.jackson.databind.JsonNode> handler) Sets a generic handler for all notifications.voidsetOnPromptsListChanged(Consumer<String> handler) Sets a handler for prompts list changed notifications.voidsetOnResourcesListChanged(Consumer<String> handler) Sets a handler for resources list changed notifications.voidsetOnToolsListChanged(Consumer<String> handler) Sets a handler for tools list changed notifications.voidSets the roots and notifies the server that roots have changed.voidSets the handler for server-initiated sampling requests.voidsubscribeResource(String uri) Subscribes to changes for a resource.voidUnsubscribes from changes for a resource.
-
Constructor Details
-
McpClient
Creates an McpClient with the given transport and default settings.- Parameters:
transport- the transport to use for communication
-
-
Method Details
-
builder
Creates a new builder for McpClient.- Returns:
- a new Builder instance
-
create
Creates an McpClient with the given transport and default settings.- Parameters:
transport- the transport to use- Returns:
- a new McpClient instance
-
connect
Connects to the MCP server.- Throws:
IOException- if connection fails
-
initialize
Initializes the MCP session with capability exchange. This must be called after connect() and before any other operations.- Throws:
IOException- if initialization failsMcpClient.McpException- if server returns an error
-
disconnect
Disconnects from the MCP server.- Throws:
IOException- if disconnection fails
-
isConnected
public boolean isConnected()Checks if the client is connected to the server.- Returns:
- true if connected
-
isInitialized
public boolean isInitialized()Checks if the client has completed initialization.- Returns:
- true if initialized
-
getServerCapabilities
Returns the server capabilities after initialization.- Returns:
- server capabilities, or null if not initialized
-
getServerInfo
Returns the server info after initialization.- Returns:
- server info, or null if not initialized
-
listTools
Lists available tools on the server.- Returns:
- list of tools with full definitions
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
executeTool
public com.fasterxml.jackson.databind.JsonNode executeTool(String toolName, Map<String, Object> arguments) throws IOException, McpClient.McpExceptionExecutes a tool on the server.- Parameters:
toolName- the name of the toolarguments- the arguments for the tool- Returns:
- the result of the execution
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
listResources
Lists available resources on the server.- Returns:
- list of resources
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error or doesn't support resources
-
listResourceTemplates
Lists available resource templates on the server.- Returns:
- list of resource templates
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error or doesn't support resources
-
readResource
Reads the content of a resource.- Parameters:
uri- the resource URI- Returns:
- list of resource contents (may contain multiple parts)
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
subscribeResource
Subscribes to changes for a resource.- Parameters:
uri- the resource URI to subscribe to- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error or doesn't support subscription
-
unsubscribeResource
Unsubscribes from changes for a resource.- Parameters:
uri- the resource URI to unsubscribe from- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
listPrompts
Lists available prompts on the server.- Returns:
- list of prompts
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error or doesn't support prompts
-
getPrompt
public com.fasterxml.jackson.databind.JsonNode getPrompt(String name, Map<String, String> arguments) throws IOException, McpClient.McpExceptionGets a prompt with the given arguments.- Parameters:
name- the prompt namearguments- the prompt arguments- Returns:
- the prompt messages
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
createSamplingMessage
public SamplingResponse createSamplingMessage(SamplingRequest request) throws IOException, McpClient.McpException Sends a sampling/createMessage request to the server to generate text.- Parameters:
request- the sampling request with messages and parameters- Returns:
- the sampling response with generated content
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error or doesn't support sampling
-
setSamplingRequestHandler
Sets the handler for server-initiated sampling requests. When a server sends a sampling/createMessage request to the client, this handler processes it.- Parameters:
handler- the sampling request handler
-
complete
public CompletionResponse complete(CompletionRequest request) throws IOException, McpClient.McpException Requests auto-completion suggestions from the server.- Parameters:
request- the completion request- Returns:
- the completion response with suggestions
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
completeResourceUri
public CompletionResponse completeResourceUri(String partialUri) throws IOException, McpClient.McpException Requests resource URI completion suggestions.- Parameters:
partialUri- the partial URI to complete- Returns:
- the completion response
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
completePromptArgument
public CompletionResponse completePromptArgument(String promptName, String argName, String partialValue) throws IOException, McpClient.McpException Requests prompt argument completion suggestions.- Parameters:
promptName- the prompt nameargName- the argument namepartialValue- the partial value to complete- Returns:
- the completion response
- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
getRoots
Returns the current list of roots.- Returns:
- the roots list
-
setRoots
Sets the roots and notifies the server that roots have changed.- Parameters:
newRoots- the new list of roots- Throws:
IOException- if sending the notification fails
-
addRoot
Adds a root and notifies the server.- Parameters:
root- the root to add- Throws:
IOException- if sending the notification fails
-
removeRoot
Removes a root and notifies the server.- Parameters:
root- the root to remove- Throws:
IOException- if sending the notification fails
-
setLogLevel
Sets the minimum log level on the server.- Parameters:
level- the desired minimum log level- Throws:
IOException- if communication failsMcpClient.McpException- if server returns an error
-
setOnLogMessage
Sets a handler for log message notifications from the server.- Parameters:
handler- the log message handler
-
setOnToolsListChanged
Sets a handler for tools list changed notifications.- Parameters:
handler- the handler to call when tools list changes
-
setOnResourcesListChanged
Sets a handler for resources list changed notifications.- Parameters:
handler- the handler to call when resources list changes
-
setOnPromptsListChanged
Sets a handler for prompts list changed notifications.- Parameters:
handler- the handler to call when prompts list changes
-
setOnNotification
Sets a generic handler for all notifications.- Parameters:
handler- the handler to call for any notification
-