Class McpClient

java.lang.Object
com.tnsai.mcp.client.McpClient

public class McpClient extends Object
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();
 
  • Constructor Details

    • McpClient

      public McpClient(McpTransport transport)
      Creates an McpClient with the given transport and default settings.
      Parameters:
      transport - the transport to use for communication
  • Method Details

    • builder

      public static McpClient.Builder builder()
      Creates a new builder for McpClient.
      Returns:
      a new Builder instance
    • create

      public static McpClient create(McpTransport transport)
      Creates an McpClient with the given transport and default settings.
      Parameters:
      transport - the transport to use
      Returns:
      a new McpClient instance
    • connect

      public void connect() throws IOException
      Connects to the MCP server.
      Throws:
      IOException - if connection fails
    • initialize

      public void initialize() throws IOException, McpClient.McpException
      Initializes the MCP session with capability exchange. This must be called after connect() and before any other operations.
      Throws:
      IOException - if initialization fails
      McpClient.McpException - if server returns an error
    • disconnect

      public void disconnect() throws IOException
      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

      public ServerCapabilities getServerCapabilities()
      Returns the server capabilities after initialization.
      Returns:
      server capabilities, or null if not initialized
    • getServerInfo

      public McpClient.ServerInfo 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 fails
      McpClient.McpException - if server returns an error
    • executeTool

      public com.fasterxml.jackson.databind.JsonNode executeTool(String toolName, Map<String,Object> arguments) throws IOException, McpClient.McpException
      Executes a tool on the server.
      Parameters:
      toolName - the name of the tool
      arguments - the arguments for the tool
      Returns:
      the result of the execution
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error
    • listResources

      public List<Resource> listResources() throws IOException, McpClient.McpException
      Lists available resources on the server.
      Returns:
      list of resources
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error or doesn't support resources
    • listResourceTemplates

      public List<ResourceTemplate> listResourceTemplates() throws IOException, McpClient.McpException
      Lists available resource templates on the server.
      Returns:
      list of resource templates
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error or doesn't support resources
    • readResource

      public List<ResourceContent> readResource(String uri) throws IOException, McpClient.McpException
      Reads the content of a resource.
      Parameters:
      uri - the resource URI
      Returns:
      list of resource contents (may contain multiple parts)
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error
    • subscribeResource

      public void subscribeResource(String uri) throws IOException, McpClient.McpException
      Subscribes to changes for a resource.
      Parameters:
      uri - the resource URI to subscribe to
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error or doesn't support subscription
    • unsubscribeResource

      public void unsubscribeResource(String uri) throws IOException, McpClient.McpException
      Unsubscribes from changes for a resource.
      Parameters:
      uri - the resource URI to unsubscribe from
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error
    • listPrompts

      public List<Prompt> listPrompts() throws IOException, McpClient.McpException
      Lists available prompts on the server.
      Returns:
      list of prompts
      Throws:
      IOException - if communication fails
      McpClient.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.McpException
      Gets a prompt with the given arguments.
      Parameters:
      name - the prompt name
      arguments - the prompt arguments
      Returns:
      the prompt messages
      Throws:
      IOException - if communication fails
      McpClient.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 fails
      McpClient.McpException - if server returns an error or doesn't support sampling
    • setSamplingRequestHandler

      public void setSamplingRequestHandler(Function<SamplingRequest,SamplingResponse> handler)
      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

      Requests auto-completion suggestions from the server.
      Parameters:
      request - the completion request
      Returns:
      the completion response with suggestions
      Throws:
      IOException - if communication fails
      McpClient.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 fails
      McpClient.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 name
      argName - the argument name
      partialValue - the partial value to complete
      Returns:
      the completion response
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error
    • getRoots

      public List<Root> getRoots()
      Returns the current list of roots.
      Returns:
      the roots list
    • setRoots

      public void setRoots(List<Root> newRoots) throws IOException
      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

      public void addRoot(Root root) throws IOException
      Adds a root and notifies the server.
      Parameters:
      root - the root to add
      Throws:
      IOException - if sending the notification fails
    • removeRoot

      public void removeRoot(Root root) throws IOException
      Removes a root and notifies the server.
      Parameters:
      root - the root to remove
      Throws:
      IOException - if sending the notification fails
    • setLogLevel

      public void setLogLevel(LogLevel level) throws IOException, McpClient.McpException
      Sets the minimum log level on the server.
      Parameters:
      level - the desired minimum log level
      Throws:
      IOException - if communication fails
      McpClient.McpException - if server returns an error
    • setOnLogMessage

      public void setOnLogMessage(Consumer<LogMessage> handler)
      Sets a handler for log message notifications from the server.
      Parameters:
      handler - the log message handler
    • setOnToolsListChanged

      public void setOnToolsListChanged(Consumer<String> handler)
      Sets a handler for tools list changed notifications.
      Parameters:
      handler - the handler to call when tools list changes
    • setOnResourcesListChanged

      public void setOnResourcesListChanged(Consumer<String> handler)
      Sets a handler for resources list changed notifications.
      Parameters:
      handler - the handler to call when resources list changes
    • setOnPromptsListChanged

      public void setOnPromptsListChanged(Consumer<String> handler)
      Sets a handler for prompts list changed notifications.
      Parameters:
      handler - the handler to call when prompts list changes
    • setOnNotification

      public void setOnNotification(Consumer<com.fasterxml.jackson.databind.JsonNode> handler)
      Sets a generic handler for all notifications.
      Parameters:
      handler - the handler to call for any notification