Replace httpOnly with transportType option and add UI controls

- Replace httpOnly boolean with transportType ('auto'/'http'/'sse') option
- Add transport type cycling button next to 'Add New Server'
- Add blue transport badge next to connected server status
- Save transport preference to localStorage
- Update connection orchestration to handle sse-only and http-only modes
- Remove explicit fallback messaging since orchestration now controls it
This commit is contained in:
Glen Maddern 2025-06-24 22:38:35 +10:00
commit e7dd5776c3
3 changed files with 65 additions and 26 deletions

View file

@ -13,9 +13,11 @@ interface McpServer {
function McpConnection({ function McpConnection({
server, server,
onConnectionUpdate, onConnectionUpdate,
transportType,
}: { }: {
server: McpServer server: McpServer
onConnectionUpdate: (serverId: string, data: any) => void onConnectionUpdate: (serverId: string, data: any) => void
transportType: 'auto' | 'http' | 'sse'
}) { }) {
// Use the MCP hook with the server URL // Use the MCP hook with the server URL
const connection = useMcp({ const connection = useMcp({
@ -23,7 +25,7 @@ function McpConnection({
debug: true, debug: true,
autoRetry: false, autoRetry: false,
popupFeatures: 'width=500,height=600,resizable=yes,scrollbars=yes', popupFeatures: 'width=500,height=600,resizable=yes,scrollbars=yes',
httpOnly: true, // DEBUG: Only try HTTP transport, no SSE fallback transportType,
}) })
// Update parent component with connection data // Update parent component with connection data
@ -64,6 +66,22 @@ const McpServerModal: React.FC<McpServerModalProps> = ({
const stored = localStorage.getItem('mcpServerToolCounts') const stored = localStorage.getItem('mcpServerToolCounts')
return stored ? JSON.parse(stored) : {} return stored ? JSON.parse(stored) : {}
}) })
const [transportType, setTransportType] = useState<'auto' | 'http' | 'sse'>(() => {
const stored = localStorage.getItem('mcpTransportType')
return (stored as 'auto' | 'http' | 'sse') || 'auto'
})
// Helper to cycle through transport types
const cycleTransportType = () => {
setTransportType(current => {
switch (current) {
case 'auto': return 'http'
case 'http': return 'sse'
case 'sse': return 'auto'
default: return 'auto'
}
})
}
// const logRef = useRef<HTMLDivElement>(null) // Removed for now as debug logs not implemented in multi-server version // const logRef = useRef<HTMLDivElement>(null) // Removed for now as debug logs not implemented in multi-server version
// Save servers to localStorage whenever they change // Save servers to localStorage whenever they change
@ -76,6 +94,11 @@ const McpServerModal: React.FC<McpServerModalProps> = ({
localStorage.setItem('mcpServerToolCounts', JSON.stringify(serverToolCounts)) localStorage.setItem('mcpServerToolCounts', JSON.stringify(serverToolCounts))
}, [serverToolCounts]) }, [serverToolCounts])
// Save transport type to localStorage whenever it changes
useEffect(() => {
localStorage.setItem('mcpTransportType', transportType)
}, [transportType])
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
document.body.style.overflow = 'hidden' document.body.style.overflow = 'hidden'
@ -296,6 +319,11 @@ const McpServerModal: React.FC<McpServerModalProps> = ({
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{getStatusBadge(server.enabled ? state : 'disabled')} {getStatusBadge(server.enabled ? state : 'disabled')}
{server.enabled && state === 'ready' && (
<span className="px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded font-mono">
{transportType.toUpperCase()}
</span>
)}
<button <button
onClick={() => handleToggleServer(server.id)} onClick={() => handleToggleServer(server.id)}
className={`p-1 rounded ${server.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-50'}`} className={`p-1 rounded ${server.enabled ? 'text-green-600 hover:bg-green-50' : 'text-gray-400 hover:bg-gray-50'}`}
@ -372,7 +400,16 @@ const McpServerModal: React.FC<McpServerModalProps> = ({
{/* Add New Server */} {/* Add New Server */}
<div className="border-t pt-4"> <div className="border-t pt-4">
<h3 className="font-medium text-sm mb-3">Add New Server</h3> <div className="flex items-center justify-between mb-3">
<h3 className="font-medium text-sm">Add New Server</h3>
<button
onClick={cycleTransportType}
className="px-2 py-1 text-xs border border-gray-300 rounded bg-gray-50 hover:bg-gray-100 font-mono"
title="Click to cycle through transport types"
>
{transportType.toUpperCase()}
</button>
</div>
<div className="flex gap-2"> <div className="flex gap-2">
<input <input
type="text" type="text"
@ -420,6 +457,7 @@ const McpServerModal: React.FC<McpServerModalProps> = ({
key={server.id} key={server.id}
server={server} server={server}
onConnectionUpdate={handleConnectionUpdate} onConnectionUpdate={handleConnectionUpdate}
transportType={transportType}
/> />
))} ))}
</> </>

View file

@ -26,8 +26,8 @@ export type UseMcpOptions = {
autoReconnect?: boolean | number autoReconnect?: boolean | number
/** Popup window features string (dimensions and behavior) for OAuth */ /** Popup window features string (dimensions and behavior) for OAuth */
popupFeatures?: string popupFeatures?: string
/** Only try HTTP transport, don't fallback to SSE (useful for debugging) */ /** Transport type preference: 'auto' (HTTP with SSE fallback), 'http' (HTTP only), 'sse' (SSE only) */
httpOnly?: boolean transportType?: 'auto' | 'http' | 'sse'
} }
export type UseMcpResult = { export type UseMcpResult = {

View file

@ -30,7 +30,7 @@ export function useMcp(options: UseMcpOptions): UseMcpResult {
debug = false, debug = false,
autoRetry = false, autoRetry = false,
autoReconnect = DEFAULT_RECONNECT_DELAY, autoReconnect = DEFAULT_RECONNECT_DELAY,
httpOnly = false, transportType = 'auto',
} = options } = options
const [state, setState] = useState<UseMcpResult['state']>('discovering') const [state, setState] = useState<UseMcpResult['state']>('discovering')
@ -315,12 +315,7 @@ export function useMcp(options: UseMcpOptions): UseMcpResult {
errorMessage === 'Load failed' /* Safari */ errorMessage === 'Load failed' /* Safari */
if (transportType === 'http' && (is404 || is405 || isLikelyCors)) { if (transportType === 'http' && (is404 || is405 || isLikelyCors)) {
if (httpOnly) { addLog('warn', `HTTP transport failed (${isLikelyCors ? 'CORS' : is404 ? '404' : '405'}).`)
addLog('warn', `HTTP transport failed (${isLikelyCors ? 'CORS' : is404 ? '404' : '405'}). httpOnly=true, no fallback.`)
failConnection(`HTTP transport failed: ${isLikelyCors ? 'CORS' : is404 ? '404' : '405'}`, errorInstance)
return 'failed'
}
addLog('warn', `HTTP transport failed (${isLikelyCors ? 'CORS' : is404 ? '404' : '405'}). Will attempt fallback to SSE.`)
return 'fallback' // Signal that fallback should be attempted return 'fallback' // Signal that fallback should be attempted
} }
@ -361,7 +356,7 @@ export function useMcp(options: UseMcpOptions): UseMcpResult {
if (authTimeoutRef.current) clearTimeout(authTimeoutRef.current) if (authTimeoutRef.current) clearTimeout(authTimeoutRef.current)
addLog('error', 'Auth flow failed:', sdkAuthError) addLog('error', 'Auth flow failed:', sdkAuthError)
// Auth failed, but still allow fallback to SSE // Auth failed, but still allow fallback to SSE
if (transportType === 'http' && !httpOnly) { if (transportType === 'http') {
return 'fallback' // Try SSE even after auth failure return 'fallback' // Try SSE even after auth failure
} else { } else {
failConnection( failConnection(
@ -377,12 +372,7 @@ export function useMcp(options: UseMcpOptions): UseMcpResult {
// Don't call failConnection here for HTTP transport - let orchestration handle it // Don't call failConnection here for HTTP transport - let orchestration handle it
// so that SSE fallback can still be attempted // so that SSE fallback can still be attempted
if (transportType === 'http') { if (transportType === 'http') {
if (httpOnly) { addLog('warn', `HTTP transport failed: ${errorMessage}.`)
addLog('warn', `HTTP transport failed: ${errorMessage}. httpOnly=true, no fallback.`)
failConnection(`HTTP transport failed: ${errorMessage}`, errorInstance)
return 'failed'
}
addLog('warn', `HTTP transport failed: ${errorMessage}. Will attempt fallback to SSE.`)
return 'fallback' return 'fallback'
} else { } else {
// For SSE transport, we can fail immediately since there's no further fallback // For SSE transport, we can fail immediately since there's no further fallback
@ -395,16 +385,27 @@ export function useMcp(options: UseMcpOptions): UseMcpResult {
// --- Orchestrate Connection Attempts --- // --- Orchestrate Connection Attempts ---
let finalStatus: 'success' | 'auth_redirect' | 'failed' | 'fallback' = 'failed' // Default to failed let finalStatus: 'success' | 'auth_redirect' | 'failed' | 'fallback' = 'failed' // Default to failed
// 1. Try HTTP if (transportType === 'sse') {
// SSE only - skip HTTP entirely
addLog('debug', 'Using SSE-only transport mode')
finalStatus = await tryConnectWithTransport('sse')
} else if (transportType === 'http') {
// HTTP only - no fallback
addLog('debug', 'Using HTTP-only transport mode')
finalStatus = await tryConnectWithTransport('http')
} else {
// Auto mode - try HTTP first, fallback to SSE
addLog('debug', 'Using auto transport mode (HTTP with SSE fallback)')
const httpResult = await tryConnectWithTransport('http') const httpResult = await tryConnectWithTransport('http')
// 2. Try SSE only if HTTP requested fallback and we haven't redirected // Try SSE only if HTTP requested fallback and we haven't redirected
if (httpResult === 'fallback' && isMountedRef.current && stateRef.current !== 'authenticating') { if (httpResult === 'fallback' && isMountedRef.current && stateRef.current !== 'authenticating') {
const sseResult = await tryConnectWithTransport('sse') const sseResult = await tryConnectWithTransport('sse')
finalStatus = sseResult // Use SSE result as final status finalStatus = sseResult // Use SSE result as final status
} else { } else {
finalStatus = httpResult // Use HTTP result if no fallback was needed/possible finalStatus = httpResult // Use HTTP result if no fallback was needed/possible
} }
}
// If we still have 'fallback' status, convert to 'failed' since no more transports to try // If we still have 'fallback' status, convert to 'failed' since no more transports to try
if (finalStatus === 'fallback') { if (finalStatus === 'fallback') {