Class Mcp

All Implemented Interfaces:
AutoCloseable

public class Mcp extends ChilkatObject
<section class="mcp-summary">

A client for the Model Context Protocol (MCP).

Chilkat.Mcp connects to an MCP server and gives an application access to the server's tools, resources, and prompts over a single, unified API. MCP is an open protocol that standardizes how applications supply context and callable tools to AI models.

Connect & handshake

connect(String) opens a Streamable HTTP session and performs the MCP initialize handshake, negotiating the protocol version and establishing a session id.

Tools

List the server's tools with listTools(JsonObject) and invoke them with callTool(String, JsonObject, JsonObject).

Resources & prompts

Read resources with listResources(JsonObject) and readResource(String, JsonObject), and fetch prompts with listPrompts(JsonObject) and getPrompt(String, JsonObject, JsonObject).

Use with Chilkat.Ai

Pass a connected Chilkat.Mcp to Chilkat.Ai.UseMcp to register the server's tools with an AI model. During a conversation the model's tool calls are routed to the MCP server automatically.

Transport: This class uses the MCP Streamable HTTP transport (protocol version 2025-06-18). A server response may arrive as a single JSON object or as a Server-Sent-Events stream; both are handled transparently. The stdio transport is not supported.

Authentication: If the MCP server requires authorization, set the getAuthToken() property before calling connect(String). Chilkat then sends it as an Authorization: Bearer <token> header on every request. Leave it unset for servers that do not require authentication.

Pagination: When a server has more items than fit in a single response, the tools/list, resources/list, and prompts/list results include a nextCursor string. In this release the list methods return the first page only and do not accept a cursor argument, so nextCursor is informational.

</section>

Event-capable: long-running methods report progress through a ProgressListener installed with setProgressListener(ProgressListener), onAbortCheck(BooleanSupplier), onPercentDone(IntPredicate) or onProgressInfo(BiConsumer).

Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when done; an unclosed instance is freed when it becomes unreachable.

See Also:
Online reference
  • Constructor Details

    • Mcp

      public Mcp()
      Creates a new Mcp object.
  • Method Details

    • getAuthToken

      public String getAuthToken()
      An optional bearer token for authenticating to the MCP server. When set, it is sent as an Authorization: Bearer <token> header on every request. The default is the empty string.
      Returns:
      the value of the AuthToken property
    • setAuthToken

      public void setAuthToken​(String value)
      Sets the AuthToken property; see getAuthToken().
      Parameters:
      value - the new value (not null)
    • getConnectTimeoutMs

      public int getConnectTimeoutMs()
      The maximum amount of time, in milliseconds, to wait to establish the TCP/TLS connection to the MCP server. The default value is 30000 (30 seconds).
      Returns:
      the value of the ConnectTimeoutMs property
    • setConnectTimeoutMs

      public void setConnectTimeoutMs​(int value)
      Sets the ConnectTimeoutMs property; see getConnectTimeoutMs().
      Parameters:
      value - the new value
    • getConnected

      public boolean getConnected()
      Read-only. true after a successful connect(String) (the initialize handshake completed).
      Returns:
      the value of the Connected property (read-only)
    • getHeartbeatMs

      public int getHeartbeatMs()
      The interval in milliseconds between each AbortCheck event callback, which enables an application to abort a method before it completes. By default, HeartbeatMs is 0, meaning no AbortCheck event callbacks fire.
      Returns:
      the value of the HeartbeatMs property
    • setHeartbeatMs

      public void setHeartbeatMs​(int value)
      Sets the HeartbeatMs property; see getHeartbeatMs().
      Parameters:
      value - the new value
    • getIdleTimeoutMs

      public int getIdleTimeoutMs()
      The maximum amount of time, in milliseconds, to wait for additional incoming data when receiving a response has paused. This is not a total timeout. The default value is 180000 (180 seconds).
      Returns:
      the value of the IdleTimeoutMs property
    • setIdleTimeoutMs

      public void setIdleTimeoutMs​(int value)
      Sets the IdleTimeoutMs property; see getIdleTimeoutMs().
      Parameters:
      value - the new value
    • getProtocolVersion

      public String getProtocolVersion()
      The MCP protocol version. May be set before connect(String) to request a specific version; after connect(String) it reflects the version negotiated with the server and is sent in the MCP-Protocol-Version header of each request. The default is 2025-06-18.
      Returns:
      the value of the ProtocolVersion property
    • setProtocolVersion

      public void setProtocolVersion​(String value)
      Sets the ProtocolVersion property; see getProtocolVersion().
      Parameters:
      value - the new value (not null)
    • getServerInstructions

      public String getServerInstructions()
      Read-only. Optional usage instructions provided by the server in the initialize result (may be the empty string), available after connect(String).
      Returns:
      the value of the ServerInstructions property (read-only)
    • getServerName

      public String getServerName()
      Read-only. The server name reported in the initialize result, available after connect(String).
      Returns:
      the value of the ServerName property (read-only)
    • getServerVersion

      public String getServerVersion()
      Read-only. The server version reported in the initialize result, available after connect(String).
      Returns:
      the value of the ServerVersion property (read-only)
    • getSessionId

      public String getSessionId()
      Read-only. The Mcp-Session-Id assigned by the server during the connect(String) handshake, or the empty string if the server is stateless. Chilkat automatically includes this session id on all subsequent requests.
      Returns:
      the value of the SessionId property (read-only)
    • callTool

      public void callTool​(String name, JsonObject argsJson, JsonObject resultJson)
      Calls the MCP tools/call method for the tool named name, passing the JSON arguments object in argsJson. The members of argsJson are the tool's input arguments and should match the tool's inputSchema as returned by listTools(JsonObject). For example, a weather tool might be called with the arguments { "location": "Boston, MA", "units": "fahrenheit" }. Pass an empty JSON object (not a null) for a tool that takes no arguments.

      On success, the tool result is placed in resultJson. It contains a content array, an isError boolean, and optionally a structuredContent object. Each element of the content array has a type ("text", "image", "audio", or "resource"); for a "text" element the value is in its text member. A typical result looks like:

      {
         "content": [ { "type": "text", "text": "The weather in Boston is 72F and sunny." } ],
         "isError": false
       }

      Thus the text of the first content item is at JSON path content[0].text.

      Note: A tool that executes but reports a failure returns true here with isError set to true in resultJson (the failure message is typically carried in the content array). The return value is false only for transport- or protocol-level failures.

      connect(String) must be called first.

      Parameters:
      name - the name argument (not null)
      argsJson - the argsJson argument (not null)
      resultJson - the resultJson argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • closeSession

      public void closeSession()
      Explicitly terminates the MCP session by sending an HTTP DELETE with the Mcp-Session-Id header, then releases the connection. It is safe to call this method when not connected (it simply releases any transport). A server that does not permit client-terminated sessions responds with HTTP 405, which is not treated as an error.

      (Named Close in the other Chilkat APIs.)

      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • connect

      public void connect​(String url)
      Connects to the MCP (Model Context Protocol) server at the Streamable HTTP endpoint URL in url (for example https://example.com/mcp) and performs the MCP initialize handshake.

      On success, the getSessionId(), getProtocolVersion(), getServerName(), getServerVersion(), and getServerInstructions() properties are populated, and getConnected() becomes true.

      If an getAuthToken() is set, it is sent as a bearer token on the request. The URL must begin with http:// or https://; the host, port, and path are taken from it. Only the Streamable HTTP transport is supported; the stdio transport is not.

      Parameters:
      url - the url argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getLastJsonData

      public void getLastJsonData​(JsonObject json)
      Returns, in json, the complete JSON-RPC response envelope from the most recent request (the jsonrpc, id, and result or error members), for diagnostics and logging. Note that this is the full JSON-RPC envelope, whereas listTools(JsonObject), callTool(String, JsonObject, JsonObject), readResource(String, JsonObject), and getPrompt(String, JsonObject, JsonObject) each return only the inner result object.
      Parameters:
      json - the json argument (not null)
    • getPrompt

      public void getPrompt​(String name, JsonObject argsJson, JsonObject json)
      Calls the MCP prompts/get method for the prompt named name, passing the JSON arguments object in argsJson (pass an empty object for a prompt that takes no arguments). On success, the result is placed in json, consisting of an optional description and a messages array in which each message has a role and content.

      connect(String) must be called first.

      Parameters:
      name - the name argument (not null)
      argsJson - the argsJson argument (not null)
      json - the json argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • listPrompts

      public void listPrompts​(JsonObject json)
      Calls the MCP prompts/list method. On success, the server's result object is placed in json, containing a prompts array in which each prompt has a name, optionally a description, and an arguments array, and possibly a nextCursor for pagination.

      connect(String) must be called first.

      Parameters:
      json - the json argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • listResources

      public void listResources​(JsonObject json)
      Calls the MCP resources/list method. On success, the server's result object is placed in json, containing a resources array in which each resource has a uri, a name, and optionally a description and mimeType, and possibly a nextCursor for pagination.

      connect(String) must be called first.

      Parameters:
      json - the json argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • listTools

      public void listTools​(JsonObject json)
      Calls the MCP tools/list method. On success, the server's result object is placed in json, containing a tools array in which each tool has a name, a description, and an inputSchema (a JSON Schema describing the tool's arguments), and possibly a nextCursor for pagination.

      connect(String) must be called first.

      Parameters:
      json - the json argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • readResource

      public void readResource​(String uri, JsonObject json)
      Calls the MCP resources/read method for the resource identified by the URI in uri. On success, the result is placed in json, containing a contents array whose entries carry a uri, a mimeType, and either text (for text resources) or blob (base64 for binary resources).

      connect(String) must be called first.

      Parameters:
      uri - the uri argument (not null)
      json - the json argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setConnectionSettings

      public void setConnectionSettings​(Socket sock)
      Copies connection settings, including HTTP proxy, SOCKS proxy, bind (network interface) IP address, and TLS options, from sock. This is optional; if not used, default settings apply. Call this method before connect(String).
      Parameters:
      sock - the sock argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • setProgressListener

      public void setProgressListener​(ProgressListener listener)
      Installs the listener that receives this object's progress events (abortCheck, percentDone, progressInfo) during its long-running methods; replaces any listener or lambda installed before; null removes it.
      Parameters:
      listener - the listener, or null
      Throws:
      IllegalStateException - if called from inside one of this object's own callbacks
    • getProgressListener

      public ProgressListener getProgressListener()
      Returns the installed listener, or null.
      Returns:
      the listener installed with setProgressListener(ProgressListener) or one of the on... methods
    • onAbortCheck

      public void onAbortCheck​(BooleanSupplier callback)
      Installs a listener whose only callback is abortCheck: called every HeartbeatMs milliseconds during a long-running method; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onPercentDone

      public void onPercentDone​(IntPredicate callback)
      Installs a listener whose only callback is percentDone: called with the completion percentage (0..100) as a long-running method progresses; return true to abort it. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener
    • onProgressInfo

      public void onProgressInfo​(BiConsumer<String,​String> callback)
      Installs a listener whose only callback is progressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.
      Parameters:
      callback - the callback, or null to remove the listener