Class Mcp
- All Implemented Interfaces:
AutoCloseable
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
opens a Streamable HTTP session and performs
the MCP connect(String)initialize handshake, negotiating the protocol version and
establishing a session id.
Tools
List the server's tools with and invoke
them with listTools(JsonObject).
callTool(String, JsonObject, JsonObject)
Resources & prompts
Read resources with and
listResources(JsonObject), and fetch prompts with
readResource(String, JsonObject) and
listPrompts(JsonObject).
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
property before calling
getAuthToken(). Chilkat then sends it as an
connect(String)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 Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidcallTool(String name, JsonObject argsJson, JsonObject resultJson)Calls the MCPtools/callmethod for the tool namedname, passing the JSON arguments object inargsJson.voidExplicitly terminates the MCP session by sending an HTTPDELETEwith theMcp-Session-Idheader, then releases the connection.voidConnects to the MCP (Model Context Protocol) server at the Streamable HTTP endpoint URL inurl(for examplehttps://example.com/mcp) and performs the MCPinitializehandshake.An optional bearer token for authenticating to the MCP server.booleanRead-only.intThe maximum amount of time, in milliseconds, to wait to establish the TCP/TLS connection to the MCP server.intThe interval in milliseconds between eachAbortCheckevent callback, which enables an application to abort a method before it completes.intThe maximum amount of time, in milliseconds, to wait for additional incoming data when receiving a response has paused.voidgetLastJsonData(JsonObject json)Returns, injson, the complete JSON-RPC response envelope from the most recent request (thejsonrpc,id, andresultorerrormembers), for diagnostics and logging.Returns the installed listener, ornull.voidgetPrompt(String name, JsonObject argsJson, JsonObject json)Calls the MCPprompts/getmethod for the prompt namedname, passing the JSON arguments object inargsJson(pass an empty object for a prompt that takes no arguments).The MCP protocol version.Read-only.Read-only.Read-only.Read-only.voidlistPrompts(JsonObject json)Calls the MCPprompts/listmethod.voidlistResources(JsonObject json)Calls the MCPresources/listmethod.voidlistTools(JsonObject json)Calls the MCPtools/listmethod.voidonAbortCheck(BooleanSupplier callback)Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it.voidonPercentDone(IntPredicate callback)Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it.voidonProgressInfo(BiConsumer<String,String> callback)Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds.voidreadResource(String uri, JsonObject json)Calls the MCPresources/readmethod for the resource identified by the URI inuri.voidsetAuthToken(String value)Sets theAuthTokenproperty; seegetAuthToken().voidsetConnectionSettings(Socket sock)Copies connection settings, including HTTP proxy, SOCKS proxy, bind (network interface) IP address, and TLS options, fromsock.voidsetConnectTimeoutMs(int value)Sets theConnectTimeoutMsproperty; seegetConnectTimeoutMs().voidsetHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().voidsetIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().voidsetProgressListener(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;nullremoves it.voidsetProtocolVersion(String value)Sets theProtocolVersionproperty; seegetProtocolVersion().Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Mcp
public Mcp()Creates a newMcpobject.
-
-
Method Details
-
getAuthToken
An optional bearer token for authenticating to the MCP server. When set, it is sent as anAuthorization: Bearer <token>header on every request. The default is the empty string.- Returns:
- the value of the
AuthTokenproperty
-
setAuthToken
Sets theAuthTokenproperty; seegetAuthToken().- Parameters:
value- the new value (notnull)
-
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 is30000(30 seconds).- Returns:
- the value of the
ConnectTimeoutMsproperty
-
setConnectTimeoutMs
public void setConnectTimeoutMs(int value)Sets theConnectTimeoutMsproperty; seegetConnectTimeoutMs().- Parameters:
value- the new value
-
getConnected
public boolean getConnected()- Returns:
- the value of the
Connectedproperty (read-only)
-
getHeartbeatMs
public int getHeartbeatMs()The interval in milliseconds between eachAbortCheckevent callback, which enables an application to abort a method before it completes. By default, HeartbeatMs is0, meaning no AbortCheck event callbacks fire.- Returns:
- the value of the
HeartbeatMsproperty
-
setHeartbeatMs
public void setHeartbeatMs(int value)Sets theHeartbeatMsproperty; seegetHeartbeatMs().- 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 is180000(180 seconds).- Returns:
- the value of the
IdleTimeoutMsproperty
-
setIdleTimeoutMs
public void setIdleTimeoutMs(int value)Sets theIdleTimeoutMsproperty; seegetIdleTimeoutMs().- Parameters:
value- the new value
-
getProtocolVersion
The MCP protocol version. May be set beforeto request a specific version; afterconnect(String)it reflects the version negotiated with the server and is sent in theconnect(String)MCP-Protocol-Versionheader of each request. The default is2025-06-18.- Returns:
- the value of the
ProtocolVersionproperty
-
setProtocolVersion
Sets theProtocolVersionproperty; seegetProtocolVersion().- Parameters:
value- the new value (notnull)
-
getServerInstructions
Read-only. Optional usage instructions provided by the server in theinitializeresult (may be the empty string), available after.connect(String)- Returns:
- the value of the
ServerInstructionsproperty (read-only)
-
getServerName
Read-only. The server name reported in theinitializeresult, available after.connect(String)- Returns:
- the value of the
ServerNameproperty (read-only)
-
getServerVersion
Read-only. The server version reported in theinitializeresult, available after.connect(String)- Returns:
- the value of the
ServerVersionproperty (read-only)
-
getSessionId
Read-only. TheMcp-Session-Idassigned by the server during thehandshake, or the empty string if the server is stateless. Chilkat automatically includes this session id on all subsequent requests.connect(String)- Returns:
- the value of the
SessionIdproperty (read-only)
-
callTool
Calls the MCPtools/callmethod for the tool namedname, passing the JSON arguments object inargsJson. The members ofargsJsonare the tool's input arguments and should match the tool'sinputSchemaas returned by. For example, a weather tool might be called with the argumentslistTools(JsonObject){ "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 acontentarray, anisErrorboolean, and optionally astructuredContentobject. Each element of thecontentarray has atype("text","image","audio", or"resource"); for a"text"element the value is in itstextmember. 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
truehere withisErrorset totrueinresultJson(the failure message is typically carried in thecontentarray). The return value isfalseonly for transport- or protocol-level failures.must be called first.connect(String)- Parameters:
name- thenameargument (notnull)argsJson- theargsJsonargument (notnull)resultJson- theresultJsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
closeSession
public void closeSession()Explicitly terminates the MCP session by sending an HTTPDELETEwith theMcp-Session-Idheader, 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 HTTP405, which is not treated as an error.(Named
Closein the other Chilkat APIs.)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
connect
Connects to the MCP (Model Context Protocol) server at the Streamable HTTP endpoint URL inurl(for examplehttps://example.com/mcp) and performs the MCPinitializehandshake.On success, the
,getSessionId(),getProtocolVersion(),getServerName(), andgetServerVersion()properties are populated, andgetServerInstructions()becomesgetConnected()true.If an
is set, it is sent as a bearer token on the request. The URL must begin withgetAuthToken()http://orhttps://; the host, port, and path are taken from it. Only the Streamable HTTP transport is supported; the stdio transport is not.- Parameters:
url- theurlargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
getLastJsonData
Returns, injson, the complete JSON-RPC response envelope from the most recent request (thejsonrpc,id, andresultorerrormembers), for diagnostics and logging. Note that this is the full JSON-RPC envelope, whereas,listTools(JsonObject),callTool(String, JsonObject, JsonObject), andreadResource(String, JsonObject)each return only the innergetPrompt(String, JsonObject, JsonObject)resultobject.- Parameters:
json- thejsonargument (notnull)
-
getPrompt
Calls the MCPprompts/getmethod for the prompt namedname, passing the JSON arguments object inargsJson(pass an empty object for a prompt that takes no arguments). On success, the result is placed injson, consisting of an optionaldescriptionand amessagesarray in which each message has aroleandcontent.must be called first.connect(String)- Parameters:
name- thenameargument (notnull)argsJson- theargsJsonargument (notnull)json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
listPrompts
Calls the MCPprompts/listmethod. On success, the server's result object is placed injson, containing apromptsarray in which each prompt has aname, optionally adescription, and anargumentsarray, and possibly anextCursorfor pagination.must be called first.connect(String)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
listResources
Calls the MCPresources/listmethod. On success, the server's result object is placed injson, containing aresourcesarray in which each resource has auri, aname, and optionally adescriptionandmimeType, and possibly anextCursorfor pagination.must be called first.connect(String)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
listTools
Calls the MCPtools/listmethod. On success, the server's result object is placed injson, containing atoolsarray in which each tool has aname, adescription, and aninputSchema(a JSON Schema describing the tool's arguments), and possibly anextCursorfor pagination.must be called first.connect(String)- Parameters:
json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
readResource
Calls the MCPresources/readmethod for the resource identified by the URI inuri. On success, the result is placed injson, containing acontentsarray whose entries carry auri, amimeType, and eithertext(for text resources) orblob(base64 for binary resources).must be called first.connect(String)- Parameters:
uri- theuriargument (notnull)json- thejsonargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setConnectionSettings
Copies connection settings, including HTTP proxy, SOCKS proxy, bind (network interface) IP address, and TLS options, fromsock. This is optional; if not used, default settings apply. Call this method before.connect(String)- Parameters:
sock- thesockargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setProgressListener
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;nullremoves it.- Parameters:
listener- the listener, ornull- Throws:
IllegalStateException- if called from inside one of this object's own callbacks
-
getProgressListener
Returns the installed listener, ornull.- Returns:
- the listener installed with
setProgressListener(ProgressListener)or one of theon...methods
-
onAbortCheck
Installs a listener whose only callback isabortCheck: called everyHeartbeatMsmilliseconds during a long-running method; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onPercentDone
Installs a listener whose only callback ispercentDone: called with the completion percentage (0..100) as a long-running method progresses; returntrueto abort it. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-
onProgressInfo
Installs a listener whose only callback isprogressInfo: called with a name/value pair of progress information as a long-running method proceeds. Replaces any listener installed before.- Parameters:
callback- the callback, ornullto remove the listener
-