Open History to see the last commit
1import { useMemo, useRef } from 'react'
2import { createMcpAppBridge } from '@tanstack/ai-client'
3import type {
4 CreateMcpAppBridgeOptions,
5 McpAppBridge,
6} from '@tanstack/ai-client'
7
8export type UseMcpAppBridgeOptions = CreateMcpAppBridgeOptions
9
10/**
11 * React wrapper around `createMcpAppBridge` that returns a **stable** bridge for
12 * the given `threadId`/`callEndpoint`, while always invoking the latest
13 * `chat.sendMessage` and `onLink` (kept in refs). This avoids both recreating
14 * the bridge on every render and the stale-closure / `exhaustive-deps` dance
15 * you'd otherwise write by hand:
16 *
17 * ```tsx
18 * const { sendMessage } = useChat({ threadId, connection })
19 * const bridge = useMcpAppBridge({
20 * threadId,
21 * callEndpoint: '/api/mcp-apps-call',
22 * chat: { sendMessage: (content, body) => sendMessage(content, { body }) },
23 * onLink: (url) => window.open(url, '_blank', 'noopener,noreferrer'),
24 * })
25 * // pass `bridge` to <MCPAppResource bridge={bridge} … />
26 * ```
27 *
28 * The bridge is recreated only when `threadId`, `callEndpoint`, `fetchImpl`, or
29 * the *presence* of `onLink` changes — passing a new inline `onLink`/`sendMessage`
30 * each render does not churn it.
31 */
32export function useMcpAppBridge(options: UseMcpAppBridgeOptions): McpAppBridge {
33 const { threadId, callEndpoint, chat, fetchImpl, onLink } = options
34
35 // Latest-value refs so the bridge identity stays stable but its callbacks are
36 // never stale (the bridge calls `.current` at invocation time, not creation).
37 const chatRef = useRef(chat)
38 chatRef.current = chat
39 const onLinkRef = useRef(onLink)
40 onLinkRef.current = onLink
41
42 // Whether a link handler was supplied governs the bridge's link behavior
43 // (forward vs. display-only warn), so it's part of the bridge's identity.
44 const hasOnLink = onLink != null
45
46 return useMemo(
47 () =>
48 createMcpAppBridge({
49 threadId,
50 callEndpoint,
51 fetchImpl,
52 chat: {
53 sendMessage: (content, body) =>
54 chatRef.current.sendMessage(content, body),
55 },
56 onLink: hasOnLink ? (url) => onLinkRef.current?.(url) : undefined,
57 }),
58 [threadId, callEndpoint, fetchImpl, hasOnLink],
59 )
60}