Connection States
The useMcp hook exposes a state property that represents the current lifecycle of the connection to the MCP server. Handling these states correctly is crucial for a good user experience.
State Values
| State | Description |
|---|---|
discovering |
The client is initializing and determining how to connect to the server. |
pending_auth |
The server requires authentication, but automatic popup was prevented (often due to browser blockers or configuration). User action is required. |
authenticating |
An authentication flow (e.g., OAuth popup) is currently in progress. |
connecting |
The client is establishing the underlying transport connection (HTTP or SSE). |
loading |
The connection is established, and the client is fetching initial capabilities (tools, resources, prompts). |
ready |
The connection is fully established and ready for interaction. |
failed |
The connection or authentication encountered a fatal error. Check the error property for details. |
Handling States
Loading States
While the state is connecting or loading, you should show a loading indicator or disable interaction elements.
if (['connecting', 'loading'].includes(state)) {
return <Spinner />;
}
Failure and Retry
If the state is failed, the hook provides a retry() function to attempt reconnection.
if (state === 'failed') {
return (
<div className="error">
<p>{error}</p>
<button onClick={retry}>Retry Connection</button>
</div>
);
}
Authentication Requirements
If the state is pending_auth or authenticating, you may need to present the user with a way to manually trigger authentication if popups were blocked.
const { state, authenticate, authUrl } = useMcp({ ... });
if (state === 'pending_auth' || authUrl) {
return (
<div>
<p>Authentication Required</p>
<button onClick={authenticate}>Login</button>
{/* Fallback link if popup completely fails */}
{authUrl && <a href={authUrl} target="_blank">Open Auth Page</a>}
</div>
);
}