Mcp React Native Reference Documentation
Mcp
Current Version: 11.6.1
Chilkat.Mcp
Read resources with
Pass a connected 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 opens a Streamable HTTP session and performs
the MCP initialize handshake, negotiating the protocol version and
establishing a session id.
Resources & prompts
ListResources and
ReadResource, and fetch prompts with
ListPrompts and
GetPrompt.
Use with Chilkat.Ai
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.
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.
AuthToken property before calling
Connect. Chilkat then sends it as an
Authorization: Bearer <token> header on every request. Leave it
unset for servers that do not require authentication.
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.
Object Creation
// npm install @chilkat/react-native react-native-nitro-modules
// (React Native 0.76+ with the New Architecture; then `pod install` for iOS. The Chilkat
// native library is downloaded and verified during the native build -- see the package README.)
import { Chilkat, Mcp } from '@chilkat/react-native'
// Once per app start, before any other Chilkat call:
Chilkat.unlockBundle('Anything for 30-day trial') // shorthand for new Global().unlockBundle(..)
const mcp = new Mcp()
// ... the native object is released when `mcp` is garbage collected, or now with mcp.dispose()Creates the underlying native Chilkat object. Mcp is a Nitro Module HybridObject: use it from the JavaScript thread only (it cannot be passed to a Worklet or another runtime). Every member is synchronous and blocks the JavaScript thread until Chilkat returns; a method that can take a while also exists as a ...Async twin returning a Promise, which runs the same call on a native worker thread so the UI keeps rendering. While such a call is pending, every other call on this object throws, except abort() and assigning onPercentDone / onProgressInfo.
Releases the native object immediately instead of waiting for garbage collection (useful for a large BinData or an open socket). Calling it more than once is harmless; any other use of the object afterwards throws. An object with a pending ...Async call cannot be disposed until the promise settles.
Errors
A method that can fail throws a plain Error: a method whose only outcome is success or failure returns void and throws on failure; a method producing a string or an object returns it and throws where Chilkat would have returned null. The error's message is "Class.method(...): reason", where the reason is the last informative line of the object's lastErrorText, which holds the full Chilkat log of the failed call. A ...Async twin rejects its promise with the same Error instead of throwing. Properties never throw, and methods that answer a question (has..., is..., ...) return a plain boolean.
try {
mcp.someMethod(...)
} catch (e) {
console.log((e as Error).message) // Mcp.someMethod(...): <reason>
console.log(mcp.lastErrorText) // the full Chilkat log of the failed call
}
// The same call without blocking the JavaScript thread:
try {
await mcp.someMethodAsync(...)
} catch (e) {
console.log((e as Error).message) // Mcp.someMethodAsync: <reason>
}
Properties
AuthToken
authToken: string
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.
Connected
readonly connected: boolean
ConnectTimeoutMs
connectTimeoutMs: number
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).
DebugLogFilePath
debugLogFilePath: string
If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.
Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.
Possible causes of hangs include:
- A timeout property set to 0, indicating an infinite timeout.
- A hang occurring within an event callback in the application code.
- An internal bug in the Chilkat code causing the hang.
HeartbeatMs
heartbeatMs: number
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.
IdleTimeoutMs
idleTimeoutMs: number
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).
LastErrorHtml
readonly lastErrorHtml: string
Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastErrorText
readonly lastErrorText: string
Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
LastErrorXml
readonly lastErrorXml: string
Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.
topLastMethodSuccess
lastMethodSuccess: boolean
Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.
ProtocolVersion
protocolVersion: string
The MCP protocol version. May be set before Connect to request a specific version; after Connect 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.
ServerInstructions
readonly serverInstructions: string
Read-only. Optional usage instructions provided by the server in the initialize result (may be the empty string), available after Connect.
ServerName
readonly serverName: string
ServerVersion
readonly serverVersion: string
SessionId
readonly sessionId: string
Read-only. The Mcp-Session-Id assigned by the server during the Connect handshake, or the empty string if the server is stateless. Chilkat automatically includes this session id on all subsequent requests.
VerboseLogging
verboseLogging: boolean
If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.
Version
readonly version: string
Methods
CallTool
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. 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 must be called first.
Returns normally on success; throws an Error on failure.
CallToolAsync
Asynchronous form of CallTool: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
Close
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.
Returns normally on success; throws an Error on failure.
CloseAsync
Asynchronous form of Close: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
Connect
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 SessionId, ProtocolVersion, ServerName, ServerVersion, and ServerInstructions properties are populated, and Connected becomes true.
If an AuthToken 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.
Returns normally on success; throws an Error on failure.
ConnectAsync
Asynchronous form of Connect: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
GetLastJsonData
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, CallTool, ReadResource, and GetPrompt each return only the inner result object.
GetPrompt
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 must be called first.
Returns normally on success; throws an Error on failure.
GetPromptAsync
Asynchronous form of GetPrompt: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
ListPrompts
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 must be called first.
Returns normally on success; throws an Error on failure.
ListPromptsAsync
Asynchronous form of ListPrompts: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
ListResources
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 must be called first.
Returns normally on success; throws an Error on failure.
ListResourcesAsync
Asynchronous form of ListResources: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
ListTools
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 must be called first.
Returns normally on success; throws an Error on failure.
ListToolsAsync
Asynchronous form of ListTools: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
ReadResource
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 must be called first.
Returns normally on success; throws an Error on failure.
ReadResourceAsync
Asynchronous form of ReadResource: the same call on a native worker thread, so the JavaScript thread (and the UI) stays responsive. Takes the same arguments and resolves with the same result. While the returned Promise is pending, every other call on this object throws (the object is busy), except abort(), which cancels the call, and assigning the onPercentDone / onProgressInfo callbacks, which report its progress.
Note: the onPercentDone and onProgressInfo callbacks run on the JavaScript thread while the promise is pending, so they can update the UI directly. A rejection's message is "Class.methodAsync: reason"; the full log is in lastErrorText.
Returns a Promise that resolves with the synchronous method's result (undefined for a void method) and rejects with an Error where the synchronous method would throw.
SetConnectionSettings
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.
Returns normally on success; throws an Error on failure.
Events
While a method runs, Mcp reports progress through two optional callback properties. Assign a function to receive the event, or undefined to stop receiving it. The callbacks are delivered on the JavaScript thread, so they are useful with the ...Async methods: during a synchronous call the JavaScript thread is busy inside Chilkat, and the events can only arrive after it returns.
const mcp = new Mcp()
mcp.onPercentDone = (pct) => setProgress(pct) // pct is 0..100
mcp.onProgressInfo = (name, value) => console.log(`${name}: ${value}`)
mcp.heartbeatMs = 250 // let abort() take effect within a quarter second
const pending = mcp.someMethodAsync(...)
cancelButton.onPress = () => mcp.abort() // the promise then rejects
await pendingPercentDone fires when an operation's completion percentage is known; ProgressInfo delivers named progress values (what is reported depends on the class and method). There is no AbortCheck callback: to cancel a pending ...Async call, call abort() on the object. Chilkat notices the request at its next progress check, which happens at least every heartbeatMs milliseconds on the classes that have that property (0, the default, disables the heartbeat, so set it for a responsive cancel), and the promise rejects with Chilkat's abort error. abort() is harmless when nothing is pending.
PercentDone
onPercentDone?: (pctDone: number) => void
This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The pctDone argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have pctDone equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).
The PercentDone callback also acts as an AbortCheck event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.
To abort the operation, set the abort output argument to true. This will cause the method to terminate and return a failure status or corresponding failure value.
Example:
mcp.onPercentDone = (pct) => {
// pct ranges from 0 to 100.
setProgress(pct) // runs on the JavaScript thread: React state may be updated directly
}
await mcp.someMethodAsync(...)
// To stop an operation from within the callback, call mcp.abort()ProgressInfo
onProgressInfo?: (name: string, value: string) => void
This event callback provides tag name/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.
Note: Some Chilkat methods don't fire any ProgressInfo events.
Example:
mcp.onProgressInfo = (name, value) => console.log(`${name}: ${value}`)
await mcp.someMethodAsync(...)