@tambo-ai/react 0.73.1 → 0.74.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -12
- package/dist/hooks/use-component-state.d.ts +1 -1
- package/dist/hooks/use-component-state.js.map +1 -1
- package/dist/hooks/use-streaming-props.d.ts +1 -1
- package/dist/hooks/use-streaming-props.js +1 -1
- package/dist/hooks/use-streaming-props.js.map +1 -1
- package/dist/hooks/use-tambo-stream-status.d.ts +1 -1
- package/dist/hooks/use-tambo-stream-status.js +1 -1
- package/dist/hooks/use-tambo-stream-status.js.map +1 -1
- package/dist/mcp/mcp-hooks.d.ts.map +1 -1
- package/dist/mcp/mcp-hooks.js +70 -16
- package/dist/mcp/mcp-hooks.js.map +1 -1
- package/dist/providers/tambo-interactable-provider-partial-updates.test.js +3 -3
- package/dist/providers/tambo-interactable-provider-partial-updates.test.js.map +1 -1
- package/dist/providers/tambo-interactable-provider.js +2 -2
- package/dist/providers/tambo-interactable-provider.js.map +1 -1
- package/dist/providers/tambo-interactable-provider.test.js +3 -3
- package/dist/providers/tambo-interactable-provider.test.js.map +1 -1
- package/dist/providers/tambo-thread-input-provider.d.ts.map +1 -1
- package/dist/providers/tambo-thread-input-provider.js +1 -0
- package/dist/providers/tambo-thread-input-provider.js.map +1 -1
- package/dist/v1/__tests__/v1-interactables.test.d.ts +2 -0
- package/dist/v1/__tests__/v1-interactables.test.d.ts.map +1 -0
- package/dist/v1/__tests__/v1-interactables.test.js +135 -0
- package/dist/v1/__tests__/v1-interactables.test.js.map +1 -0
- package/dist/v1/components/v1-component-renderer.d.ts +48 -0
- package/dist/v1/components/v1-component-renderer.d.ts.map +1 -0
- package/dist/v1/components/v1-component-renderer.js +137 -0
- package/dist/v1/components/v1-component-renderer.js.map +1 -0
- package/dist/v1/components/v1-component-renderer.test.d.ts +2 -0
- package/dist/v1/components/v1-component-renderer.test.d.ts.map +1 -0
- package/dist/v1/components/v1-component-renderer.test.js +270 -0
- package/dist/v1/components/v1-component-renderer.test.js.map +1 -0
- package/dist/v1/hooks/use-tambo-v1-component-state.d.ts.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-component-state.js +2 -25
- package/dist/v1/hooks/use-tambo-v1-component-state.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-component-state.test.js +2 -1
- package/dist/v1/hooks/use-tambo-v1-component-state.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-messages.test.js +25 -1
- package/dist/v1/hooks/use-tambo-v1-messages.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-send-message.d.ts +18 -0
- package/dist/v1/hooks/use-tambo-v1-send-message.d.ts.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-send-message.js +204 -17
- package/dist/v1/hooks/use-tambo-v1-send-message.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-send-message.test.js +261 -7
- package/dist/v1/hooks/use-tambo-v1-send-message.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-stream-status.d.ts +90 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.d.ts.map +1 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.js +179 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.js.map +1 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.test.d.ts +2 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.test.d.ts.map +1 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.test.js +371 -0
- package/dist/v1/hooks/use-tambo-v1-stream-status.test.js.map +1 -0
- package/dist/v1/hooks/use-tambo-v1-suggestions.d.ts +78 -54
- package/dist/v1/hooks/use-tambo-v1-suggestions.d.ts.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-suggestions.js +153 -87
- package/dist/v1/hooks/use-tambo-v1-suggestions.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-suggestions.test.js +213 -134
- package/dist/v1/hooks/use-tambo-v1-suggestions.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread-input.test.js +148 -13
- package/dist/v1/hooks/use-tambo-v1-thread-input.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread-list.d.ts +8 -21
- package/dist/v1/hooks/use-tambo-v1-thread-list.d.ts.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread-list.js +11 -10
- package/dist/v1/hooks/use-tambo-v1-thread-list.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread-list.test.js +37 -2
- package/dist/v1/hooks/use-tambo-v1-thread-list.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread.d.ts +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread.d.ts.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread.js +2 -7
- package/dist/v1/hooks/use-tambo-v1-thread.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1-thread.test.js +2 -0
- package/dist/v1/hooks/use-tambo-v1-thread.test.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1.d.ts +12 -28
- package/dist/v1/hooks/use-tambo-v1.d.ts.map +1 -1
- package/dist/v1/hooks/use-tambo-v1.js +164 -31
- package/dist/v1/hooks/use-tambo-v1.js.map +1 -1
- package/dist/v1/hooks/use-tambo-v1.test.js +891 -18
- package/dist/v1/hooks/use-tambo-v1.test.js.map +1 -1
- package/dist/v1/index.d.ts +7 -1
- package/dist/v1/index.d.ts.map +1 -1
- package/dist/v1/index.js +18 -1
- package/dist/v1/index.js.map +1 -1
- package/dist/v1/providers/tambo-v1-provider.d.ts +16 -6
- package/dist/v1/providers/tambo-v1-provider.d.ts.map +1 -1
- package/dist/v1/providers/tambo-v1-provider.js +14 -19
- package/dist/v1/providers/tambo-v1-provider.js.map +1 -1
- package/dist/v1/providers/tambo-v1-provider.test.js +34 -20
- package/dist/v1/providers/tambo-v1-provider.test.js.map +1 -1
- package/dist/v1/providers/tambo-v1-stream-context.d.ts +3 -3
- package/dist/v1/providers/tambo-v1-stream-context.d.ts.map +1 -1
- package/dist/v1/providers/tambo-v1-stream-context.js +60 -12
- package/dist/v1/providers/tambo-v1-stream-context.js.map +1 -1
- package/dist/v1/providers/tambo-v1-stream-context.test.js +49 -20
- package/dist/v1/providers/tambo-v1-stream-context.test.js.map +1 -1
- package/dist/v1/providers/tambo-v1-stub-provider.d.ts.map +1 -1
- package/dist/v1/providers/tambo-v1-stub-provider.js +2 -0
- package/dist/v1/providers/tambo-v1-stub-provider.js.map +1 -1
- package/dist/v1/providers/tambo-v1-stub-provider.test.js +7 -6
- package/dist/v1/providers/tambo-v1-stub-provider.test.js.map +1 -1
- package/dist/v1/providers/tambo-v1-thread-input-provider.d.ts +1 -6
- package/dist/v1/providers/tambo-v1-thread-input-provider.d.ts.map +1 -1
- package/dist/v1/providers/tambo-v1-thread-input-provider.js +14 -12
- package/dist/v1/providers/tambo-v1-thread-input-provider.js.map +1 -1
- package/dist/v1/types/event.d.ts +9 -1
- package/dist/v1/types/event.d.ts.map +1 -1
- package/dist/v1/types/event.js.map +1 -1
- package/dist/v1/types/event.test.js +5 -1
- package/dist/v1/types/event.test.js.map +1 -1
- package/dist/v1/types/message.d.ts +65 -7
- package/dist/v1/types/message.d.ts.map +1 -1
- package/dist/v1/types/message.js.map +1 -1
- package/dist/v1/types/thread.d.ts +4 -0
- package/dist/v1/types/thread.d.ts.map +1 -1
- package/dist/v1/types/thread.js.map +1 -1
- package/dist/v1/utils/event-accumulator.d.ts +40 -4
- package/dist/v1/utils/event-accumulator.d.ts.map +1 -1
- package/dist/v1/utils/event-accumulator.js +444 -35
- package/dist/v1/utils/event-accumulator.js.map +1 -1
- package/dist/v1/utils/event-accumulator.test.js +1041 -28
- package/dist/v1/utils/event-accumulator.test.js.map +1 -1
- package/dist/v1/utils/registry-conversion.d.ts +9 -9
- package/dist/v1/utils/registry-conversion.d.ts.map +1 -1
- package/dist/v1/utils/registry-conversion.js +10 -11
- package/dist/v1/utils/registry-conversion.js.map +1 -1
- package/dist/v1/utils/registry-conversion.test.js +39 -11
- package/dist/v1/utils/registry-conversion.test.js.map +1 -1
- package/dist/v1/utils/thread-utils.d.ts +16 -0
- package/dist/v1/utils/thread-utils.d.ts.map +1 -0
- package/dist/v1/utils/thread-utils.js +34 -0
- package/dist/v1/utils/thread-utils.js.map +1 -0
- package/dist/v1/utils/tool-executor.d.ts.map +1 -1
- package/dist/v1/utils/tool-executor.js +2 -0
- package/dist/v1/utils/tool-executor.js.map +1 -1
- package/dist/v1/utils/tool-executor.test.js +5 -0
- package/dist/v1/utils/tool-executor.test.js.map +1 -1
- package/esm/context-helpers/context-helpers-provider.test.js +2 -2
- package/esm/context-helpers/context-helpers.test.js +1 -1
- package/esm/context-helpers/current-interactables-context-helper.d.ts +1 -1
- package/esm/context-helpers/current-page-context-helper.d.ts +1 -1
- package/esm/context-helpers/current-time-context-helper.d.ts +1 -1
- package/esm/context-helpers/index.d.ts +4 -4
- package/esm/context-helpers/index.js +4 -4
- package/esm/hoc/with-tambo-interactable.d.ts +1 -1
- package/esm/hoc/with-tambo-interactable.js +2 -2
- package/esm/hoc/with-tambo-interactable.test.js +3 -3
- package/esm/hooks/index.d.ts +8 -8
- package/esm/hooks/index.js +8 -8
- package/esm/hooks/react-query-hooks.js +1 -1
- package/esm/hooks/use-component-state.d.ts +1 -1
- package/esm/hooks/use-component-state.js +3 -3
- package/esm/hooks/use-component-state.js.map +1 -1
- package/esm/hooks/use-component-state.test.js +5 -5
- package/esm/hooks/use-current-message.d.ts +1 -1
- package/esm/hooks/use-current-message.test.js +1 -1
- package/esm/hooks/use-message-images.test.js +1 -1
- package/esm/hooks/use-streaming-props.d.ts +1 -1
- package/esm/hooks/use-streaming-props.js +1 -1
- package/esm/hooks/use-streaming-props.js.map +1 -1
- package/esm/hooks/use-suggestions.d.ts +2 -2
- package/esm/hooks/use-suggestions.js +10 -10
- package/esm/hooks/use-suggestions.test.js +7 -7
- package/esm/hooks/use-tambo-stream-status.d.ts +1 -1
- package/esm/hooks/use-tambo-stream-status.js +4 -4
- package/esm/hooks/use-tambo-stream-status.js.map +1 -1
- package/esm/hooks/use-tambo-stream-status.test.js +4 -4
- package/esm/hooks/use-tambo-threads.js +3 -3
- package/esm/hooks/use-tambo-threads.test.js +3 -3
- package/esm/hooks/use-tambo-voice.js +2 -2
- package/esm/hooks/use-tambo-voice.test.js +3 -3
- package/esm/index.d.ts +22 -22
- package/esm/index.js +15 -15
- package/esm/mcp/elicitation.d.ts +1 -1
- package/esm/mcp/elicitation.test.js +1 -1
- package/esm/mcp/index.d.ts +7 -7
- package/esm/mcp/index.js +3 -3
- package/esm/mcp/mcp-client.d.ts +1 -1
- package/esm/mcp/mcp-client.js +1 -1
- package/esm/mcp/mcp-client.test.js +1 -1
- package/esm/mcp/mcp-hooks.d.ts +1 -1
- package/esm/mcp/mcp-hooks.d.ts.map +1 -1
- package/esm/mcp/mcp-hooks.js +74 -20
- package/esm/mcp/mcp-hooks.js.map +1 -1
- package/esm/mcp/mcp-hooks.test.js +6 -6
- package/esm/mcp/tambo-mcp-provider.d.ts +4 -4
- package/esm/mcp/tambo-mcp-provider.js +7 -7
- package/esm/mcp/tambo-mcp-provider.test.js +5 -5
- package/esm/mcp/use-mcp-servers.test.js +4 -4
- package/esm/model/generate-component-response.d.ts +1 -1
- package/esm/model/tambo-interactable.d.ts +1 -1
- package/esm/model/tambo-thread.d.ts +1 -1
- package/esm/providers/__tests__/thread-input-resource-resolution.test.js +3 -3
- package/esm/providers/hooks/use-tambo-session-token.test.js +1 -1
- package/esm/providers/index.d.ts +12 -12
- package/esm/providers/index.js +10 -10
- package/esm/providers/tambo-client-provider.js +1 -1
- package/esm/providers/tambo-client-provider.test.js +2 -2
- package/esm/providers/tambo-component-provider.d.ts +1 -1
- package/esm/providers/tambo-component-provider.js +2 -2
- package/esm/providers/tambo-context-attachment-provider.js +1 -1
- package/esm/providers/tambo-context-attachment-provider.test.js +2 -2
- package/esm/providers/tambo-context-helpers-provider.d.ts +1 -1
- package/esm/providers/tambo-context-helpers-provider.js +1 -1
- package/esm/providers/tambo-context-helpers-provider.test.js +2 -2
- package/esm/providers/tambo-interactable-provider-partial-updates.test.js +4 -4
- package/esm/providers/tambo-interactable-provider-partial-updates.test.js.map +1 -1
- package/esm/providers/tambo-interactable-provider.d.ts +5 -5
- package/esm/providers/tambo-interactable-provider.js +6 -6
- package/esm/providers/tambo-interactable-provider.js.map +1 -1
- package/esm/providers/tambo-interactable-provider.test.js +4 -4
- package/esm/providers/tambo-interactable-provider.test.js.map +1 -1
- package/esm/providers/tambo-interactables-additional-context-edge-cases.test.js +4 -4
- package/esm/providers/tambo-interactables-additional-context.test.js +4 -4
- package/esm/providers/tambo-mcp-token-provider.js +2 -2
- package/esm/providers/tambo-prop-stream-provider/index.d.ts +8 -8
- package/esm/providers/tambo-prop-stream-provider/index.js +9 -9
- package/esm/providers/tambo-prop-stream-provider/pending.d.ts +1 -1
- package/esm/providers/tambo-prop-stream-provider/pending.js +2 -2
- package/esm/providers/tambo-prop-stream-provider/provider.d.ts +1 -1
- package/esm/providers/tambo-prop-stream-provider/provider.js +2 -2
- package/esm/providers/tambo-prop-stream-provider/streaming.d.ts +1 -1
- package/esm/providers/tambo-prop-stream-provider/streaming.js +2 -2
- package/esm/providers/tambo-prop-stream-provider/success.d.ts +1 -1
- package/esm/providers/tambo-prop-stream-provider/success.js +2 -2
- package/esm/providers/tambo-prop-stream-provider/types.d.ts +1 -1
- package/esm/providers/tambo-prop-stream-provider.test.js +4 -4
- package/esm/providers/tambo-provider.d.ts +7 -7
- package/esm/providers/tambo-provider.js +10 -10
- package/esm/providers/tambo-registry-provider.d.ts +3 -3
- package/esm/providers/tambo-registry-provider.js +3 -3
- package/esm/providers/tambo-registry-provider.test.js +2 -2
- package/esm/providers/tambo-registry-schema-compat.test.js +2 -2
- package/esm/providers/tambo-stubs.d.ts +4 -4
- package/esm/providers/tambo-stubs.js +9 -9
- package/esm/providers/tambo-stubs.test.js +2 -2
- package/esm/providers/tambo-thread-input-provider.d.ts +2 -2
- package/esm/providers/tambo-thread-input-provider.d.ts.map +1 -1
- package/esm/providers/tambo-thread-input-provider.js +11 -10
- package/esm/providers/tambo-thread-input-provider.js.map +1 -1
- package/esm/providers/tambo-thread-provider-initial-messages.test.js +6 -6
- package/esm/providers/tambo-thread-provider.d.ts +2 -2
- package/esm/providers/tambo-thread-provider.js +8 -8
- package/esm/providers/tambo-thread-provider.test.js +7 -7
- package/esm/schema/index.d.ts +4 -4
- package/esm/schema/index.js +4 -4
- package/esm/schema/json-schema.test.js +1 -1
- package/esm/schema/schema.d.ts +1 -1
- package/esm/schema/schema.js +2 -2
- package/esm/schema/schema.test.js +3 -3
- package/esm/schema/standard-schema.test.js +1 -1
- package/esm/schema/validate.js +2 -2
- package/esm/schema/validate.test.js +1 -1
- package/esm/testing/tools.d.ts +3 -3
- package/esm/testing/tools.js +2 -2
- package/esm/util/content-parts.test.js +1 -1
- package/esm/util/generate-component.d.ts +2 -2
- package/esm/util/generate-component.js +4 -4
- package/esm/util/generate-component.test.js +2 -2
- package/esm/util/is-promise.test.js +1 -1
- package/esm/util/mcp-server-utils.d.ts +1 -1
- package/esm/util/mcp-server-utils.js +1 -1
- package/esm/util/mcp-server-utils.test.js +2 -2
- package/esm/util/message-builder.d.ts +1 -1
- package/esm/util/message-builder.test.js +1 -1
- package/esm/util/query-utils.test.js +1 -1
- package/esm/util/registry-validators.d.ts +1 -1
- package/esm/util/registry-validators.js +2 -2
- package/esm/util/registry-validators.test.js +1 -1
- package/esm/util/registry.d.ts +1 -1
- package/esm/util/registry.js +1 -1
- package/esm/util/registry.test.js +2 -2
- package/esm/util/resource-content-resolver.d.ts +2 -2
- package/esm/util/resource-content-resolver.js +1 -1
- package/esm/util/resource-content-resolver.test.js +3 -3
- package/esm/util/resource-validators.d.ts +1 -1
- package/esm/util/resource-validators.test.js +1 -1
- package/esm/util/tool-caller.d.ts +1 -1
- package/esm/util/tool-caller.js +1 -1
- package/esm/util/validate-component-name.test.js +1 -1
- package/esm/v1/__tests__/v1-interactables.test.d.ts +2 -0
- package/esm/v1/__tests__/v1-interactables.test.d.ts.map +1 -0
- package/esm/v1/__tests__/v1-interactables.test.js +130 -0
- package/esm/v1/__tests__/v1-interactables.test.js.map +1 -0
- package/esm/v1/components/v1-component-renderer.d.ts +48 -0
- package/esm/v1/components/v1-component-renderer.d.ts.map +1 -0
- package/esm/v1/components/v1-component-renderer.js +100 -0
- package/esm/v1/components/v1-component-renderer.js.map +1 -0
- package/esm/v1/components/v1-component-renderer.test.d.ts +2 -0
- package/esm/v1/components/v1-component-renderer.test.d.ts.map +1 -0
- package/esm/v1/components/v1-component-renderer.test.js +265 -0
- package/esm/v1/components/v1-component-renderer.test.js.map +1 -0
- package/esm/v1/hooks/use-tambo-v1-component-state.d.ts.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-component-state.js +4 -27
- package/esm/v1/hooks/use-tambo-v1-component-state.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-component-state.test.js +6 -5
- package/esm/v1/hooks/use-tambo-v1-component-state.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-messages.d.ts +1 -1
- package/esm/v1/hooks/use-tambo-v1-messages.js +1 -1
- package/esm/v1/hooks/use-tambo-v1-messages.test.js +27 -3
- package/esm/v1/hooks/use-tambo-v1-messages.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-send-message.d.ts +20 -2
- package/esm/v1/hooks/use-tambo-v1-send-message.d.ts.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-send-message.js +213 -26
- package/esm/v1/hooks/use-tambo-v1-send-message.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-send-message.test.js +266 -12
- package/esm/v1/hooks/use-tambo-v1-send-message.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-stream-status.d.ts +90 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.d.ts.map +1 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.js +176 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.js.map +1 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.test.d.ts +2 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.test.d.ts.map +1 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.test.js +369 -0
- package/esm/v1/hooks/use-tambo-v1-stream-status.test.js.map +1 -0
- package/esm/v1/hooks/use-tambo-v1-suggestions.d.ts +78 -54
- package/esm/v1/hooks/use-tambo-v1-suggestions.d.ts.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-suggestions.js +157 -91
- package/esm/v1/hooks/use-tambo-v1-suggestions.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-suggestions.test.js +218 -139
- package/esm/v1/hooks/use-tambo-v1-suggestions.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread-input.d.ts +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread-input.js +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread-input.test.js +151 -16
- package/esm/v1/hooks/use-tambo-v1-thread-input.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread-list.d.ts +8 -21
- package/esm/v1/hooks/use-tambo-v1-thread-list.d.ts.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread-list.js +12 -11
- package/esm/v1/hooks/use-tambo-v1-thread-list.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread-list.test.js +39 -4
- package/esm/v1/hooks/use-tambo-v1-thread-list.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread.d.ts +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread.d.ts.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread.js +3 -8
- package/esm/v1/hooks/use-tambo-v1-thread.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1-thread.test.js +4 -2
- package/esm/v1/hooks/use-tambo-v1-thread.test.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1.d.ts +15 -31
- package/esm/v1/hooks/use-tambo-v1.d.ts.map +1 -1
- package/esm/v1/hooks/use-tambo-v1.js +134 -34
- package/esm/v1/hooks/use-tambo-v1.js.map +1 -1
- package/esm/v1/hooks/use-tambo-v1.test.js +862 -19
- package/esm/v1/hooks/use-tambo-v1.test.js.map +1 -1
- package/esm/v1/index.d.ts +28 -22
- package/esm/v1/index.d.ts.map +1 -1
- package/esm/v1/index.js +30 -18
- package/esm/v1/index.js.map +1 -1
- package/esm/v1/providers/tambo-v1-provider.d.ts +21 -11
- package/esm/v1/providers/tambo-v1-provider.d.ts.map +1 -1
- package/esm/v1/providers/tambo-v1-provider.js +20 -25
- package/esm/v1/providers/tambo-v1-provider.js.map +1 -1
- package/esm/v1/providers/tambo-v1-provider.test.js +40 -26
- package/esm/v1/providers/tambo-v1-provider.test.js.map +1 -1
- package/esm/v1/providers/tambo-v1-stream-context.d.ts +4 -4
- package/esm/v1/providers/tambo-v1-stream-context.d.ts.map +1 -1
- package/esm/v1/providers/tambo-v1-stream-context.js +62 -14
- package/esm/v1/providers/tambo-v1-stream-context.js.map +1 -1
- package/esm/v1/providers/tambo-v1-stream-context.test.js +50 -21
- package/esm/v1/providers/tambo-v1-stream-context.test.js.map +1 -1
- package/esm/v1/providers/tambo-v1-stub-provider.d.ts +3 -3
- package/esm/v1/providers/tambo-v1-stub-provider.d.ts.map +1 -1
- package/esm/v1/providers/tambo-v1-stub-provider.js +7 -5
- package/esm/v1/providers/tambo-v1-stub-provider.js.map +1 -1
- package/esm/v1/providers/tambo-v1-stub-provider.test.js +12 -11
- package/esm/v1/providers/tambo-v1-stub-provider.test.js.map +1 -1
- package/esm/v1/providers/tambo-v1-thread-input-provider.d.ts +3 -8
- package/esm/v1/providers/tambo-v1-thread-input-provider.d.ts.map +1 -1
- package/esm/v1/providers/tambo-v1-thread-input-provider.js +18 -16
- package/esm/v1/providers/tambo-v1-thread-input-provider.js.map +1 -1
- package/esm/v1/types/event.d.ts +9 -1
- package/esm/v1/types/event.d.ts.map +1 -1
- package/esm/v1/types/event.js.map +1 -1
- package/esm/v1/types/event.test.js +6 -2
- package/esm/v1/types/event.test.js.map +1 -1
- package/esm/v1/types/message.d.ts +65 -7
- package/esm/v1/types/message.d.ts.map +1 -1
- package/esm/v1/types/message.js.map +1 -1
- package/esm/v1/types/thread.d.ts +5 -1
- package/esm/v1/types/thread.d.ts.map +1 -1
- package/esm/v1/types/thread.js.map +1 -1
- package/esm/v1/utils/component-renderer.test.js +1 -1
- package/esm/v1/utils/event-accumulator.d.ts +41 -5
- package/esm/v1/utils/event-accumulator.d.ts.map +1 -1
- package/esm/v1/utils/event-accumulator.js +444 -36
- package/esm/v1/utils/event-accumulator.js.map +1 -1
- package/esm/v1/utils/event-accumulator.test.js +1042 -29
- package/esm/v1/utils/event-accumulator.test.js.map +1 -1
- package/esm/v1/utils/json-patch.test.js +1 -1
- package/esm/v1/utils/registry-conversion.d.ts +9 -9
- package/esm/v1/utils/registry-conversion.d.ts.map +1 -1
- package/esm/v1/utils/registry-conversion.js +11 -12
- package/esm/v1/utils/registry-conversion.js.map +1 -1
- package/esm/v1/utils/registry-conversion.test.js +40 -12
- package/esm/v1/utils/registry-conversion.test.js.map +1 -1
- package/esm/v1/utils/stream-handler.test.js +1 -1
- package/esm/v1/utils/thread-utils.d.ts +16 -0
- package/esm/v1/utils/thread-utils.d.ts.map +1 -0
- package/esm/v1/utils/thread-utils.js +31 -0
- package/esm/v1/utils/thread-utils.js.map +1 -0
- package/esm/v1/utils/tool-call-tracker.d.ts +1 -1
- package/esm/v1/utils/tool-executor.d.ts +1 -1
- package/esm/v1/utils/tool-executor.d.ts.map +1 -1
- package/esm/v1/utils/tool-executor.js +2 -0
- package/esm/v1/utils/tool-executor.js.map +1 -1
- package/esm/v1/utils/tool-executor.test.js +6 -1
- package/esm/v1/utils/tool-executor.test.js.map +1 -1
- package/package.json +11 -10
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
<p align="center">
|
|
14
14
|
<a href="https://docs.tambo.co">Documentation</a> •
|
|
15
|
-
<a href="https://docs.tambo.co/
|
|
15
|
+
<a href="https://docs.tambo.co/reference/react-sdk">API Reference</a> •
|
|
16
16
|
<a href="https://discord.gg/dJNvPEHth6">Discord</a>
|
|
17
17
|
</p>
|
|
18
18
|
|
|
@@ -159,7 +159,7 @@ const components: TamboComponent[] = [
|
|
|
159
159
|
];
|
|
160
160
|
```
|
|
161
161
|
|
|
162
|
-
[→ Learn more about components](https://docs.tambo.co/concepts/
|
|
162
|
+
[→ Learn more about components](https://docs.tambo.co/concepts/generative-interfaces)
|
|
163
163
|
|
|
164
164
|
### Provider Setup
|
|
165
165
|
|
|
@@ -176,7 +176,7 @@ Wrap your app with `TamboProvider` to enable AI capabilities:
|
|
|
176
176
|
</TamboProvider>
|
|
177
177
|
```
|
|
178
178
|
|
|
179
|
-
[→ See all provider options](https://docs.tambo.co/
|
|
179
|
+
[→ See all provider options](https://docs.tambo.co/reference/react-sdk/providers)
|
|
180
180
|
|
|
181
181
|
### Hooks
|
|
182
182
|
|
|
@@ -189,7 +189,7 @@ Wrap your app with `TamboProvider` to enable AI capabilities:
|
|
|
189
189
|
| `useTamboStreamStatus()` | Monitor streaming status for progressive loading |
|
|
190
190
|
| `useTamboSuggestions()` | Generate contextual suggestions |
|
|
191
191
|
|
|
192
|
-
[→ API Reference](https://docs.tambo.co/
|
|
192
|
+
[→ API Reference](https://docs.tambo.co/reference/react-sdk)
|
|
193
193
|
|
|
194
194
|
## Key Features
|
|
195
195
|
|
|
@@ -211,7 +211,7 @@ const components: TamboComponent[] = [
|
|
|
211
211
|
];
|
|
212
212
|
```
|
|
213
213
|
|
|
214
|
-
[→ Learn more about components](https://docs.tambo.co/concepts/
|
|
214
|
+
[→ Learn more about components](https://docs.tambo.co/concepts/generative-interfaces)
|
|
215
215
|
|
|
216
216
|
### Interactable Components
|
|
217
217
|
|
|
@@ -234,7 +234,7 @@ const InteractableNote = withInteractable(Note, {
|
|
|
234
234
|
<InteractableNote id="note-1" title="My Note" content="Content here" />;
|
|
235
235
|
```
|
|
236
236
|
|
|
237
|
-
[→ Learn more about interactable components](https://docs.tambo.co/concepts/
|
|
237
|
+
[→ Learn more about interactable components](https://docs.tambo.co/concepts/generative-interfaces/interactable-components)
|
|
238
238
|
|
|
239
239
|
### MCP Integration
|
|
240
240
|
|
|
@@ -298,7 +298,7 @@ const tools = [
|
|
|
298
298
|
</TamboProvider>;
|
|
299
299
|
```
|
|
300
300
|
|
|
301
|
-
[→ Learn more about tools](https://docs.tambo.co/
|
|
301
|
+
[→ Learn more about tools](https://docs.tambo.co/guides/take-actions/register-tools)
|
|
302
302
|
|
|
303
303
|
#### Advanced: Transforming Tool Responses
|
|
304
304
|
|
|
@@ -426,7 +426,7 @@ registerResourceSource({
|
|
|
426
426
|
|
|
427
427
|
Local resources appear in `useTamboMcpResourceList()` alongside MCP resources, with MCP resources always prefixed by their serverKey.
|
|
428
428
|
|
|
429
|
-
[→ Learn more about resources](https://docs.tambo.co/concepts/resources)
|
|
429
|
+
[→ Learn more about resources](https://docs.tambo.co/concepts/model-context-protocol/features#resources)
|
|
430
430
|
|
|
431
431
|
### Streaming Status
|
|
432
432
|
|
|
@@ -451,7 +451,7 @@ function LoadingComponent({ title, data }) {
|
|
|
451
451
|
}
|
|
452
452
|
```
|
|
453
453
|
|
|
454
|
-
[→ Learn more about streaming](https://docs.tambo.co/concepts/
|
|
454
|
+
[→ Learn more about streaming](https://docs.tambo.co/concepts/generative-interfaces/component-state)
|
|
455
455
|
|
|
456
456
|
### Context, Auth, and Suggestions
|
|
457
457
|
|
|
@@ -484,7 +484,7 @@ suggestions.map((s) => (
|
|
|
484
484
|
|
|
485
485
|
### Supported LLM Providers
|
|
486
486
|
|
|
487
|
-
OpenAI, Anthropic, Google Gemini, Mistral, Groq, and any OpenAI-compatible provider. [Full list](https://docs.tambo.co/
|
|
487
|
+
OpenAI, Anthropic, Google Gemini, Mistral, Groq, and any OpenAI-compatible provider. [Full list](https://docs.tambo.co/reference/llm-providers). Missing one? [Let us know](https://github.com/tambo-ai/tambo/issues).
|
|
488
488
|
|
|
489
489
|
## When to Use This SDK
|
|
490
490
|
|
|
@@ -519,8 +519,8 @@ TypeScript definitions included for both outputs.
|
|
|
519
519
|
|
|
520
520
|
- [Full Documentation](https://docs.tambo.co)
|
|
521
521
|
- [Getting Started Guide](https://docs.tambo.co/getting-started/quickstart)
|
|
522
|
-
- [API Reference](https://docs.tambo.co/
|
|
523
|
-
- [Component Guides](https://docs.tambo.co/concepts/
|
|
522
|
+
- [API Reference](https://docs.tambo.co/reference/react-sdk)
|
|
523
|
+
- [Component Guides](https://docs.tambo.co/concepts/generative-interfaces)
|
|
524
524
|
- [UI Library](https://ui.tambo.co)
|
|
525
525
|
|
|
526
526
|
## License
|
|
@@ -22,7 +22,7 @@ type StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];
|
|
|
22
22
|
* user edits take precedence over the original prop value.
|
|
23
23
|
*
|
|
24
24
|
* Pair with `useTamboStreamStatus` to disable inputs while streaming.
|
|
25
|
-
* @see {@link https://docs.tambo.co/concepts/
|
|
25
|
+
* @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}
|
|
26
26
|
*/
|
|
27
27
|
export declare function useTamboComponentState<S = undefined>(keyName: string, initialValue?: S, setFromProp?: S, debounceTime?: number): StateUpdateResult<S | undefined>;
|
|
28
28
|
export declare function useTamboComponentState<S>(keyName: string, initialValue: S, setFromProp?: S, debounceTime?: number): StateUpdateResult<S>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-component-state.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AA+Cb,wDAkKC;AAhND,6CAAwC;AACxC,iCAAqE;AACrE,+CAAoD;AACpD,0BAAwE;AACxE,0FAAgF;AAChF,+DAA4D;AAyC5D,SAAgB,sBAAsB,CACpC,OAAe,EACf,YAAgB,EAChB,WAAe,EACf,YAAY,GAAG,GAAG;IAElB,MAAM,OAAO,GAAG,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,CAAC;QAClC,CAAC;IACH,CAAC,EAAE,CAAC,WAAW,EAAE,4BAA4B,CAAC,CAAC,CAAC;IAEhD,gFAAgF;IAChF,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,kFAAkF;QAClF,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO;QACT,CAAC;QACD,OAAO,GAAG,EAAE;YACV,KAAK,UAAU,YAAY;gBACzB,IAAI,CAAC;oBACH,MAAM,yBAAyB,CAAC,KAAK,EAAE,CAAC;gBAC1C,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO,CAAC,KAAK,CACX,iDAAiD,EACjD,KAAK,CACN,CAAC;gBACJ,CAAC;YACH,CAAC;YACD,kDAAkD;YAClD,KAAK,YAAY,EAAE,CAAC;QACtB,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,yBAAyB,EAAE,WAAW,CAAC,CAAC,CAAC;IAE7C,OAAO,CAAC,UAAe,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC","sourcesContent":["\"use client\";\nimport { deepEqual } from \"fast-equals\";\nimport { useCallback, useContext, useEffect, useState } from \"react\";\nimport { useDebouncedCallback } from \"use-debounce\";\nimport { TamboThreadMessage, useTamboClient, useTamboThread } from \"..\";\nimport { useTamboInteractable } from \"../providers/tambo-interactable-provider\";\nimport { TamboMessageContext } from \"./use-current-message\";\n\ntype StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];\n\n/**\n * A React hook that acts like useState, but also automatically updates the thread message's componentState.\n * If used within an interactable component (wrapped with withTamboInteractable), it updates the\n * interactable provider's global state (sent to Tambo on every request) instead of the remote thread message state.\n * For generated components, it updates both the local and remote thread message's componentState.\n *\n * Benefits: Passes user changes to AI, and when threads are returned, state is preserved.\n * Works in both generative and interactable component contexts.\n * @param keyName - The unique key to identify this state value within the message's componentState object\n * @param initialValue - Optional initial value for the state, used if no componentState value exists in the Tambo message containing this hook usage.\n * @param setFromProp - Optional value used to set the state value, only while no componentState value exists in the Tambo message containing this hook usage. Use this to allow streaming updates from a prop to the state value.\n * @param debounceTime - Optional debounce time in milliseconds (default: 500ms) to limit API calls.\n * @returns A tuple of [currentState, setState] similar to React's useState\n * @example\n * ```tsx\n * const [count, setCount] = useTamboComponentState(\"counter\", 0);\n * ```\n *\n * Use `setFromProp` to seed state from streamed props. During streaming,\n * state updates as new prop values arrive. Once streaming completes,\n * user edits take precedence over the original prop value.\n *\n * Pair with `useTamboStreamStatus` to disable inputs while streaming.\n * @see {@link https://docs.tambo.co/concepts/streaming/streaming-best-practices}\n */\nexport function useTamboComponentState<S = undefined>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S | undefined>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime = 500,\n): StateUpdateResult<S> {\n const message = useContext(TamboMessageContext);\n const { updateThreadMessage } = useTamboThread();\n const client = useTamboClient();\n const componentId = message?.interactableMetadata?.id ?? null;\n const { setInteractableState, getInteractableComponentState } =\n useTamboInteractable();\n const messageState = message?.componentState?.[keyName];\n const interactableState = componentId\n ? getInteractableComponentState(componentId)?.[keyName]\n : undefined;\n const initialState =\n (interactableState as S) ?? (messageState as S) ?? initialValue;\n const [localState, setLocalState] = useState<S | undefined>(initialState);\n const [initializedFromThreadMessage, setInitializedFromThreadMessage] =\n useState(messageState ? true : false);\n\n // Optimistically update the local thread message's componentState\n const updateLocalThreadMessage = useCallback(\n async (newState: S, existingMessage: TamboThreadMessage | null) => {\n if (!existingMessage) {\n return;\n }\n const updatedMessage = {\n threadId: existingMessage.threadId,\n componentState: {\n ...existingMessage.componentState,\n [keyName]: newState,\n },\n };\n await updateThreadMessage(existingMessage.id, updatedMessage, false);\n },\n [updateThreadMessage, keyName],\n );\n\n // Debounced callback to update the remote thread message's componentState\n const updateRemoteThreadMessage = useDebouncedCallback(\n async (newState: S, existingMessage: TamboThreadMessage | null) => {\n if (!existingMessage) {\n return;\n }\n await client.beta.threads.messages.updateComponentState(\n existingMessage.id,\n {\n id: existingMessage.threadId,\n state: { [keyName]: newState },\n },\n );\n },\n debounceTime,\n );\n\n const setValue = useCallback(\n (newState: S) => {\n setLocalState(newState);\n if (componentId) {\n // For interactable components, update the interactable provider's state\n setInteractableState(componentId, keyName, newState);\n } else if (message) {\n // For generated components, update both local and remote thread message state\n void updateLocalThreadMessage(newState, message);\n void updateRemoteThreadMessage(newState, message);\n }\n },\n [\n message,\n updateLocalThreadMessage,\n updateRemoteThreadMessage,\n setInteractableState,\n componentId,\n keyName,\n ],\n );\n\n const existingInteractableState = componentId\n ? getInteractableComponentState(componentId)?.[keyName]\n : undefined;\n const shouldUpdateInteractableInitial =\n !!componentId &&\n existingInteractableState === undefined &&\n initialValue !== undefined;\n\n // Set initial value in interactable state if we're in an interactable context and there's no existing state\n useEffect(() => {\n if (!shouldUpdateInteractableInitial) {\n return;\n }\n setInteractableState(componentId, keyName, initialValue!);\n }, [\n shouldUpdateInteractableInitial,\n componentId,\n keyName,\n initialValue,\n setInteractableState,\n ]);\n\n const shouldSyncFromMessage =\n !!message && messageState !== undefined && messageState !== null;\n\n // Mirror the thread message's componentState value to the local state and interactable state\n useEffect(() => {\n if (!shouldSyncFromMessage) {\n return;\n }\n setInitializedFromThreadMessage(true);\n const stateValue = messageState as S;\n setLocalState(stateValue);\n if (componentId) {\n setInteractableState(componentId, keyName, stateValue);\n }\n }, [\n shouldSyncFromMessage,\n messageState,\n keyName,\n setInteractableState,\n componentId,\n ]);\n\n // Sync from interactable provider to local state when state changes externally (e.g., from Tambo tool call)\n useEffect(() => {\n if (!componentId) return;\n // only update if different\n setLocalState((prev) =>\n deepEqual(prev, interactableState) ? prev : (interactableState as S),\n );\n }, [componentId, interactableState]);\n\n // For editable fields that are set from a prop to allow streaming updates, don't overwrite a fetched state value set from the thread message with prop value on initial load.\n useEffect(() => {\n if (setFromProp !== undefined && !initializedFromThreadMessage) {\n setLocalState(setFromProp as S);\n }\n }, [setFromProp, initializedFromThreadMessage]);\n\n // Ensure pending changes are flushed on unmount (only for generated components)\n useEffect(() => {\n // Only flush remote updates for generated components, not interactable components\n if (componentId) {\n return;\n }\n return () => {\n async function flushUpdates() {\n try {\n await updateRemoteThreadMessage.flush();\n } catch (error) {\n console.error(\n \"Failed to flush pending thread message updates:\",\n error,\n );\n }\n }\n // Fire-and-forget cleanup (errors handled inside)\n void flushUpdates();\n };\n }, [updateRemoteThreadMessage, componentId]);\n\n return [localState as S, setValue];\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-component-state.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AA+Cb,wDAkKC;AAhND,6CAAwC;AACxC,iCAAqE;AACrE,+CAAoD;AACpD,0BAAwE;AACxE,0FAAgF;AAChF,+DAA4D;AAyC5D,SAAgB,sBAAsB,CACpC,OAAe,EACf,YAAgB,EAChB,WAAe,EACf,YAAY,GAAG,GAAG;IAElB,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,yCAAmB,CAAC,CAAC;IAChD,MAAM,EAAE,mBAAmB,EAAE,GAAG,IAAA,kBAAc,GAAE,CAAC;IACjD,MAAM,MAAM,GAAG,IAAA,kBAAc,GAAE,CAAC;IAChC,MAAM,WAAW,GAAG,OAAO,EAAE,oBAAoB,EAAE,EAAE,IAAI,IAAI,CAAC;IAC9D,MAAM,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,GAC3D,IAAA,kDAAoB,GAAE,CAAC;IACzB,MAAM,YAAY,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC,OAAO,CAAC,CAAC;IACxD,MAAM,iBAAiB,GAAG,WAAW;QACnC,CAAC,CAAC,6BAA6B,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,CAAC;QACvD,CAAC,CAAC,SAAS,CAAC;IACd,MAA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AC,yBAAyB,EAAE,WAAW,CAAC,CAAC,CAAC;IAE7C,OAAO,CAAC,UAAe,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC","sourcesContent":["\"use client\";\nimport { deepEqual } from \"fast-equals\";\nimport { useCallback, useContext, useEffect, useState } from \"react\";\nimport { useDebouncedCallback } from \"use-debounce\";\nimport { TamboThreadMessage, useTamboClient, useTamboThread } from \"..\";\nimport { useTamboInteractable } from \"../providers/tambo-interactable-provider\";\nimport { TamboMessageContext } from \"./use-current-message\";\n\ntype StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];\n\n/**\n * A React hook that acts like useState, but also automatically updates the thread message's componentState.\n * If used within an interactable component (wrapped with withTamboInteractable), it updates the\n * interactable provider's global state (sent to Tambo on every request) instead of the remote thread message state.\n * For generated components, it updates both the local and remote thread message's componentState.\n *\n * Benefits: Passes user changes to AI, and when threads are returned, state is preserved.\n * Works in both generative and interactable component contexts.\n * @param keyName - The unique key to identify this state value within the message's componentState object\n * @param initialValue - Optional initial value for the state, used if no componentState value exists in the Tambo message containing this hook usage.\n * @param setFromProp - Optional value used to set the state value, only while no componentState value exists in the Tambo message containing this hook usage. Use this to allow streaming updates from a prop to the state value.\n * @param debounceTime - Optional debounce time in milliseconds (default: 500ms) to limit API calls.\n * @returns A tuple of [currentState, setState] similar to React's useState\n * @example\n * ```tsx\n * const [count, setCount] = useTamboComponentState(\"counter\", 0);\n * ```\n *\n * Use `setFromProp` to seed state from streamed props. During streaming,\n * state updates as new prop values arrive. Once streaming completes,\n * user edits take precedence over the original prop value.\n *\n * Pair with `useTamboStreamStatus` to disable inputs while streaming.\n * @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}\n */\nexport function useTamboComponentState<S = undefined>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S | undefined>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime = 500,\n): StateUpdateResult<S> {\n const message = useContext(TamboMessageContext);\n const { updateThreadMessage } = useTamboThread();\n const client = useTamboClient();\n const componentId = message?.interactableMetadata?.id ?? null;\n const { setInteractableState, getInteractableComponentState } =\n useTamboInteractable();\n const messageState = message?.componentState?.[keyName];\n const interactableState = componentId\n ? getInteractableComponentState(componentId)?.[keyName]\n : undefined;\n const initialState =\n (interactableState as S) ?? (messageState as S) ?? initialValue;\n const [localState, setLocalState] = useState<S | undefined>(initialState);\n const [initializedFromThreadMessage, setInitializedFromThreadMessage] =\n useState(messageState ? true : false);\n\n // Optimistically update the local thread message's componentState\n const updateLocalThreadMessage = useCallback(\n async (newState: S, existingMessage: TamboThreadMessage | null) => {\n if (!existingMessage) {\n return;\n }\n const updatedMessage = {\n threadId: existingMessage.threadId,\n componentState: {\n ...existingMessage.componentState,\n [keyName]: newState,\n },\n };\n await updateThreadMessage(existingMessage.id, updatedMessage, false);\n },\n [updateThreadMessage, keyName],\n );\n\n // Debounced callback to update the remote thread message's componentState\n const updateRemoteThreadMessage = useDebouncedCallback(\n async (newState: S, existingMessage: TamboThreadMessage | null) => {\n if (!existingMessage) {\n return;\n }\n await client.beta.threads.messages.updateComponentState(\n existingMessage.id,\n {\n id: existingMessage.threadId,\n state: { [keyName]: newState },\n },\n );\n },\n debounceTime,\n );\n\n const setValue = useCallback(\n (newState: S) => {\n setLocalState(newState);\n if (componentId) {\n // For interactable components, update the interactable provider's state\n setInteractableState(componentId, keyName, newState);\n } else if (message) {\n // For generated components, update both local and remote thread message state\n void updateLocalThreadMessage(newState, message);\n void updateRemoteThreadMessage(newState, message);\n }\n },\n [\n message,\n updateLocalThreadMessage,\n updateRemoteThreadMessage,\n setInteractableState,\n componentId,\n keyName,\n ],\n );\n\n const existingInteractableState = componentId\n ? getInteractableComponentState(componentId)?.[keyName]\n : undefined;\n const shouldUpdateInteractableInitial =\n !!componentId &&\n existingInteractableState === undefined &&\n initialValue !== undefined;\n\n // Set initial value in interactable state if we're in an interactable context and there's no existing state\n useEffect(() => {\n if (!shouldUpdateInteractableInitial) {\n return;\n }\n setInteractableState(componentId, keyName, initialValue!);\n }, [\n shouldUpdateInteractableInitial,\n componentId,\n keyName,\n initialValue,\n setInteractableState,\n ]);\n\n const shouldSyncFromMessage =\n !!message && messageState !== undefined && messageState !== null;\n\n // Mirror the thread message's componentState value to the local state and interactable state\n useEffect(() => {\n if (!shouldSyncFromMessage) {\n return;\n }\n setInitializedFromThreadMessage(true);\n const stateValue = messageState as S;\n setLocalState(stateValue);\n if (componentId) {\n setInteractableState(componentId, keyName, stateValue);\n }\n }, [\n shouldSyncFromMessage,\n messageState,\n keyName,\n setInteractableState,\n componentId,\n ]);\n\n // Sync from interactable provider to local state when state changes externally (e.g., from Tambo tool call)\n useEffect(() => {\n if (!componentId) return;\n // only update if different\n setLocalState((prev) =>\n deepEqual(prev, interactableState) ? prev : (interactableState as S),\n );\n }, [componentId, interactableState]);\n\n // For editable fields that are set from a prop to allow streaming updates, don't overwrite a fetched state value set from the thread message with prop value on initial load.\n useEffect(() => {\n if (setFromProp !== undefined && !initializedFromThreadMessage) {\n setLocalState(setFromProp as S);\n }\n }, [setFromProp, initializedFromThreadMessage]);\n\n // Ensure pending changes are flushed on unmount (only for generated components)\n useEffect(() => {\n // Only flush remote updates for generated components, not interactable components\n if (componentId) {\n return;\n }\n return () => {\n async function flushUpdates() {\n try {\n await updateRemoteThreadMessage.flush();\n } catch (error) {\n console.error(\n \"Failed to flush pending thread message updates:\",\n error,\n );\n }\n }\n // Fire-and-forget cleanup (errors handled inside)\n void flushUpdates();\n };\n }, [updateRemoteThreadMessage, componentId]);\n\n return [localState as S, setValue];\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Low-level helper that merges streamed props into state.
|
|
3
3
|
* @deprecated Use `useTamboComponentState` with `setFromProp` instead.
|
|
4
4
|
* This hook will be removed in 1.0.0.
|
|
5
|
-
* @see {@link https://docs.tambo.co/concepts/
|
|
5
|
+
* @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}
|
|
6
6
|
* @param currentState - Current state object
|
|
7
7
|
* @param setState - State setter function
|
|
8
8
|
* @param streamingProps - Props to merge into state when they change
|
|
@@ -7,7 +7,7 @@ const react_1 = require("react");
|
|
|
7
7
|
* Low-level helper that merges streamed props into state.
|
|
8
8
|
* @deprecated Use `useTamboComponentState` with `setFromProp` instead.
|
|
9
9
|
* This hook will be removed in 1.0.0.
|
|
10
|
-
* @see {@link https://docs.tambo.co/concepts/
|
|
10
|
+
* @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}
|
|
11
11
|
* @param currentState - Current state object
|
|
12
12
|
* @param setState - State setter function
|
|
13
13
|
* @param streamingProps - Props to merge into state when they change
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-streaming-props.js","sourceRoot":"","sources":["../../src/hooks/use-streaming-props.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AAab,wDA2BC;AAtCD,iCAAkC;AAElC;;;;;;;;GAQG;AACH,SAAgB,sBAAsB,CACpC,YAA2B,EAC3B,QAA4B,EAC5B,cAA0B;IAE1B,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,IAAI,YAAY,EAAE,CAAC;YACjB,IAAI,YAAY,GAAG,KAAK,CAAC;YACzB,MAAM,OAAO,GAAe,EAAE,CAAC;YAE/B,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACtD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;oBACvD,YAAY,GAAG,IAAI,CAAC;oBACpB,OAAO,CAAC,GAAc,CAAC,GAAG,KAAmB,CAAC;gBAChD,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,IAAI,YAAY,EAAE,CAAC;gBACjB,QAAQ,CAAC;oBACP,GAAG,YAAY;oBACf,GAAG,OAAO;iBACX,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,sCAAsC;QACtC,uDAAuD;IACzD,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;AACzC,CAAC","sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Low-level helper that merges streamed props into state.\n * @deprecated Use `useTamboComponentState` with `setFromProp` instead.\n * This hook will be removed in 1.0.0.\n * @see {@link https://docs.tambo.co/concepts/
|
|
1
|
+
{"version":3,"file":"use-streaming-props.js","sourceRoot":"","sources":["../../src/hooks/use-streaming-props.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AAab,wDA2BC;AAtCD,iCAAkC;AAElC;;;;;;;;GAQG;AACH,SAAgB,sBAAsB,CACpC,YAA2B,EAC3B,QAA4B,EAC5B,cAA0B;IAE1B,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,IAAI,YAAY,EAAE,CAAC;YACjB,IAAI,YAAY,GAAG,KAAK,CAAC;YACzB,MAAM,OAAO,GAAe,EAAE,CAAC;YAE/B,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;gBACtD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,YAAY,CAAC,GAAG,CAAC,EAAE,CAAC;oBACvD,YAAY,GAAG,IAAI,CAAC;oBACpB,OAAO,CAAC,GAAc,CAAC,GAAG,KAAmB,CAAC;gBAChD,CAAC;YACH,CAAC,CAAC,CAAC;YAEH,IAAI,YAAY,EAAE,CAAC;gBACjB,QAAQ,CAAC;oBACP,GAAG,YAAY;oBACf,GAAG,OAAO;iBACX,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,sCAAsC;QACtC,uDAAuD;IACzD,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;AACzC,CAAC","sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\n\n/**\n * Low-level helper that merges streamed props into state.\n * @deprecated Use `useTamboComponentState` with `setFromProp` instead.\n * This hook will be removed in 1.0.0.\n * @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}\n * @param currentState - Current state object\n * @param setState - State setter function\n * @param streamingProps - Props to merge into state when they change\n */\nexport function useTamboStreamingProps<T extends Record<string, any>>(\n currentState: T | undefined,\n setState: (state: T) => void,\n streamingProps: Partial<T>,\n) {\n useEffect(() => {\n if (currentState) {\n let shouldUpdate = false;\n const updates: Partial<T> = {};\n\n Object.entries(streamingProps).forEach(([key, value]) => {\n if (value !== undefined && value !== currentState[key]) {\n shouldUpdate = true;\n updates[key as keyof T] = value as T[keyof T];\n }\n });\n\n if (shouldUpdate) {\n setState({\n ...currentState,\n ...updates,\n });\n }\n }\n // Only run when streamingProps change\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [...Object.values(streamingProps)]);\n}\n"]}
|
|
@@ -63,7 +63,7 @@ export interface PropStatus {
|
|
|
63
63
|
* Use `propStatus.<field>?.isSuccess` before treating a prop as complete.
|
|
64
64
|
*
|
|
65
65
|
* Pair with `useTamboComponentState` to disable inputs while streaming.
|
|
66
|
-
* @see {@link https://docs.tambo.co/concepts/
|
|
66
|
+
* @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}
|
|
67
67
|
* @template Props - Component props type
|
|
68
68
|
* @returns `streamStatus` (overall) and `propStatus` (per-prop) flags
|
|
69
69
|
* @throws {Error} When used during SSR/SSG
|
|
@@ -168,7 +168,7 @@ function deriveGlobalStreamStatus(generationStage, propStatus, hasComponent, gen
|
|
|
168
168
|
* Use `propStatus.<field>?.isSuccess` before treating a prop as complete.
|
|
169
169
|
*
|
|
170
170
|
* Pair with `useTamboComponentState` to disable inputs while streaming.
|
|
171
|
-
* @see {@link https://docs.tambo.co/concepts/
|
|
171
|
+
* @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}
|
|
172
172
|
* @template Props - Component props type
|
|
173
173
|
* @returns `streamStatus` (overall) and `propStatus` (per-prop) flags
|
|
174
174
|
* @throws {Error} When used during SSR/SSG
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-tambo-stream-status.js","sourceRoot":"","sources":["../../src/hooks/use-tambo-stream-status.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AAgUb,oDAwCC;AAvWD,iCAAqD;AACrD,sFAAuE;AACvE,8EAA6E;AAC7E,+DAA+D;AAqE/D;;;;GAIG;AACH,SAAS,gBAAgB;IACvB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CACb,6DAA6D;YAC3D,4CAA4C;YAC5C,6DAA6D,CAChE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,uBAAuB,CAC9B,KAAwB,EACxB,eAAgC,EAChC,SAAiB;IAEjB,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,IAAA,gBAAQ,EAU9C,EAAE,CAAC,CAAC;IAEN,mDAAmD;IACnD,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,eAAe,CAAC,CAAC,IAAI,EAAE,EAAE;YACvB,0DAA0D;YAC1D,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAChD,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CAC5D,CAAC;YACF,OAAO,iBAAiB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;QACvC,CAAC,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;IAEhB,oFAAoF;IACpF,IAAA,iBAAS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OAAO,CAAC,KAAK,CAAC;YAC1B,CAAC,CAAC,SAAS,CAAC;QACd,MAAM,YAAY,GAAG,CAAC,CAAC,OAAO,EAAE,SAAS,CAAC;QAC1C,OAAO,wBAAwB,CAC7B,eAAe,EACf,UAAU,EACV,YAAY,EACZ,eAAe,CAChB,CAAC;IACJ,CAAC,EAAE,CAAC,eAAe,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;IAE3C,OAAO;QACL,YAAY;QACZ,UAAU;KACX,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { GenerationStage } from \"../model/generate-component-response\";\nimport { useTamboGenerationStage } from \"../providers/tambo-thread-provider\";\nimport { useTamboCurrentMessage } from \"./use-current-message\";\n\n/**\n * Global stream status flags for a specific component in a message.\n * Represents the aggregate state across all props for this component only.\n * Once a component completes, its status remains stable regardless of other generations.\n */\nexport interface StreamStatus {\n /**\n * Indicates no tokens have been received for any prop and generation is not active.\n * Useful for showing initial loading states before any data arrives.\n */\n isPending: boolean;\n\n /**\n * Indicates active streaming - either generation is streaming OR at least one prop is still streaming.\n * Use this to show loading animations or skeleton states during data transmission.\n */\n isStreaming: boolean;\n\n /**\n * Indicates successful completion - generation is complete AND every prop finished without error.\n * Safe to render the final component when this is true.\n */\n isSuccess: boolean;\n\n /**\n * Indicates a fatal error occurred in any prop or the stream itself.\n * Check streamError for details about what went wrong.\n */\n isError: boolean;\n\n /**\n * The first fatal error encountered during streaming (if any).\n * Will be undefined if no errors occurred.\n */\n streamError?: Error;\n}\n\n/**\n * Streaming status flags for individual component props.\n * Tracks the state of each prop as it streams from the LLM.\n */\nexport interface PropStatus {\n /**\n * Indicates no tokens have been received for this specific prop yet.\n * The prop value is still undefined, null, or empty string.\n */\n isPending: boolean;\n\n /**\n * Indicates at least one token has been received but streaming is not complete.\n * The prop has partial content that may still be updating.\n */\n isStreaming: boolean;\n\n /**\n * Indicates this prop has finished streaming successfully.\n * The prop value is complete and stable.\n */\n isSuccess: boolean;\n\n /**\n * The error that occurred during streaming (if any).\n * Will be undefined if no error occurred for this prop.\n */\n error?: Error;\n}\n\n/**\n * SSR Guard - throws during server-side rendering.\n * Ensures the hook is only used in browser contexts.\n * @throws {Error} When called during server-side rendering\n */\nfunction assertClientSide() {\n if (typeof window === \"undefined\") {\n throw new Error(\n \"useTamboStreamStatus can only be used in browser contexts. \" +\n \"This hook is not compatible with SSR/SSG. \" +\n \"Consider wrapping it in useEffect or using dynamic imports.\",\n );\n }\n}\n\n/**\n * Track streaming status for individual props by monitoring their values.\n * Monitors when props receive their first token and when they complete streaming.\n * Maintains stable state per message - once props complete for a message, they stay complete.\n * @template Props - The type of the component props being tracked\n * @param props - The current component props object\n * @param generationStage - The current generation stage from the LLM\n * @param messageId - The ID of the current message to track component-specific state\n * @returns A record mapping each prop key to its PropStatus\n */\nfunction usePropsStreamingStatus<Props extends Record<string, any>>(\n props: Props | undefined,\n generationStage: GenerationStage,\n messageId: string,\n): Record<keyof Props, PropStatus> {\n const [propTracking, setPropTracking] = useState<\n Record<\n string,\n {\n hasStarted: boolean;\n isComplete: boolean;\n error?: Error;\n messageId: string;\n }\n >\n >({});\n\n /** Reset tracking only when the message changes */\n useEffect(() => {\n setPropTracking((prev) => {\n // If we have tracking data for a different message, reset\n const hasOldMessageData = Object.values(prev).some(\n (track) => track.messageId && track.messageId !== messageId,\n );\n return hasOldMessageData ? {} : prev;\n });\n }, [messageId]);\n\n /** Track when props start streaming (receive first token) and when they complete */\n useEffect(() => {\n if (!props) return;\n\n setPropTracking((prev) => {\n const updated = { ...prev };\n let hasChanges = false;\n\n // First pass: identify which props are starting now\n const propsStartingNow: string[] = [];\n Object.entries(props).forEach(([key, value]) => {\n const current = prev[key] || {\n hasStarted: false,\n isComplete: false,\n };\n\n /** A prop starts streaming when it has a non-empty value for the first time */\n const hasContent =\n value !== undefined && value !== null && value !== \"\";\n const justStarted = hasContent && !current.hasStarted;\n\n if (justStarted) {\n propsStartingNow.push(key);\n }\n });\n\n // Second pass: update tracking and mark previous props as complete\n Object.entries(props).forEach(([key, value]) => {\n const current = prev[key] || {\n hasStarted: false,\n isComplete: false,\n };\n\n /** A prop starts streaming when it has a non-empty value for the first time */\n const hasContent =\n value !== undefined && value !== null && value !== \"\";\n const justStarted = hasContent && !current.hasStarted;\n\n /**\n * A prop is complete when it has started and either:\n * 1. A following prop has started, OR\n * 2. Generation is complete (for the final prop)\n */\n const hasFollowingPropStarted = propsStartingNow.some(\n (startingKey) => startingKey !== key,\n );\n const isGenerationComplete =\n generationStage === GenerationStage.COMPLETE;\n const isComplete =\n current.hasStarted &&\n (hasFollowingPropStarted || isGenerationComplete) &&\n !current.isComplete;\n\n // Once a prop is complete for this message, it stays complete\n if (current.isComplete && current.messageId === messageId) {\n // Skip - already complete for this message\n return;\n }\n\n if (justStarted || isComplete) {\n updated[key] = {\n ...current,\n hasStarted: justStarted ? true : current.hasStarted,\n isComplete: isComplete ? true : current.isComplete,\n messageId,\n };\n hasChanges = true;\n }\n });\n\n return hasChanges ? updated : prev;\n });\n }, [props, generationStage, messageId]);\n\n /** Convert tracking state to PropStatus objects */\n return useMemo(() => {\n if (!props) return {} as Record<keyof Props, PropStatus>;\n\n const result = {} as Record<keyof Props, PropStatus>;\n\n Object.keys(props).forEach((key) => {\n const tracking = propTracking[key] || {\n hasStarted: false,\n isComplete: false,\n messageId: \"\",\n };\n\n // If this prop is complete for this message, it stays complete\n const isCompleteForThisMessage =\n tracking.isComplete && tracking.messageId === messageId;\n\n // Only consider generation stage if this prop isn't already complete for this message\n const isGenerationStreaming =\n !isCompleteForThisMessage &&\n generationStage === GenerationStage.STREAMING_RESPONSE;\n\n result[key as keyof Props] = {\n isPending: !tracking.hasStarted && !isCompleteForThisMessage,\n isStreaming:\n tracking.hasStarted &&\n !isCompleteForThisMessage &&\n isGenerationStreaming,\n isSuccess: isCompleteForThisMessage,\n error: tracking.error,\n };\n });\n\n return result;\n }, [props, propTracking, generationStage, messageId]);\n}\n\n/**\n * Derives global StreamStatus from generation stage and individual prop statuses.\n * Aggregates individual prop states into a unified stream status.\n * @template Props - The type of the component props\n * @param generationStage - The current generation stage from the LLM\n * @param propStatus - Status record for each individual prop\n * @param hasComponent - Whether a component exists in the current message\n * @param generationError - Any error from the generation process itself\n * @returns The aggregated StreamStatus for the entire component\n */\nfunction deriveGlobalStreamStatus<Props extends Record<string, any>>(\n generationStage: GenerationStage,\n propStatus: Record<keyof Props, PropStatus>,\n hasComponent: boolean,\n generationError?: Error,\n): StreamStatus {\n const propStatuses = Object.values(propStatus);\n\n // If all props are already successful, the component is complete regardless of generation stage\n const allPropsSuccessful =\n propStatuses.length > 0 && propStatuses.every((p) => p.isSuccess);\n\n // Only consider generation stage if not all props are complete\n const isGenerationStreaming =\n !allPropsSuccessful &&\n generationStage === GenerationStage.STREAMING_RESPONSE;\n const isGenerationError = generationStage === GenerationStage.ERROR;\n\n /** Find first error from generation or any prop */\n const firstError =\n generationError ?? propStatuses.find((p) => p.error)?.error;\n\n return {\n /** isPending: no component yet OR (has component but no props have started) */\n isPending:\n !hasComponent ||\n (!isGenerationStreaming &&\n !allPropsSuccessful &&\n propStatuses.every((p) => p.isPending)),\n\n /** isStreaming: any prop is streaming (generation stage doesn't matter if props are complete) */\n isStreaming: propStatuses.some((p) => p.isStreaming),\n\n /** isSuccess: all props successful (component is stable once all props complete) */\n isSuccess: allPropsSuccessful,\n\n /** isError: generation error OR any prop error */\n isError:\n isGenerationError ||\n propStatuses.some((p) => p.error) ||\n !!generationError,\n\n streamError: firstError,\n };\n}\n\n/**\n * Track streaming status for Tambo component props.\n *\n * **Important**: Props update repeatedly during streaming and may be partial.\n * Use `propStatus.<field>?.isSuccess` before treating a prop as complete.\n *\n * Pair with `useTamboComponentState` to disable inputs while streaming.\n * @see {@link https://docs.tambo.co/concepts/streaming/streaming-best-practices}\n * @template Props - Component props type\n * @returns `streamStatus` (overall) and `propStatus` (per-prop) flags\n * @throws {Error} When used during SSR/SSG\n * @example\n * ```tsx\n * // Wait for entire stream\n * const { streamStatus } = useTamboStreamStatus();\n * if (!streamStatus.isSuccess) return <Spinner />;\n * return <Card {...props} />;\n * ```\n * @example\n * ```tsx\n * // Highlight in-flight props\n * const { propStatus } = useTamboStreamStatus<Props>();\n * <h2 className={propStatus.title.isStreaming ? \"animate-pulse\" : \"\"}>\n * {title}\n * </h2>\n * ```\n */\nexport function useTamboStreamStatus<\n Props extends Record<string, any> = Record<string, any>,\n>(): {\n streamStatus: StreamStatus;\n propStatus: Record<keyof Props, PropStatus>;\n} {\n /** SSR Guard - ensure client-side only execution */\n assertClientSide();\n\n const { generationStage } = useTamboGenerationStage();\n const message = useTamboCurrentMessage();\n\n /** Get the current component props from the message */\n const componentProps = (message?.component?.props as Props) || ({} as Props);\n\n /** Track per-prop streaming status */\n const propStatus = usePropsStreamingStatus(\n componentProps,\n generationStage,\n message?.id ?? \"\",\n );\n\n /** Derive global stream status from prop statuses and generation stage */\n const streamStatus = useMemo(() => {\n const generationError = message?.error\n ? new Error(message.error)\n : undefined;\n const hasComponent = !!message?.component;\n return deriveGlobalStreamStatus(\n generationStage,\n propStatus,\n hasComponent,\n generationError,\n );\n }, [generationStage, propStatus, message]);\n\n return {\n streamStatus,\n propStatus,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"use-tambo-stream-status.js","sourceRoot":"","sources":["../../src/hooks/use-tambo-stream-status.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AAgUb,oDAwCC;AAvWD,iCAAqD;AACrD,sFAAuE;AACvE,8EAA6E;AAC7E,+DAA+D;AAqE/D;;;;GAIG;AACH,SAAS,gBAAgB;IACvB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,MAAM,IAAI,KAAK,CACb,6DAA6D;YAC3D,4CAA4C;YAC5C,6DAA6D,CAChE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,uBAAuB,CAC9B,KAAwB,EACxB,eAAgC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;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,SAAgB,oBAAoB;IAMlC,oDAAoD;IACpD,gBAAgB,EAAE,CAAC;IAEnB,MAAM,EAAE,eAAe,EAAE,GAAG,IAAA,+CAAuB,GAAE,CAAC;IACtD,MAAM,OAAO,GAAG,IAAA,4CAAsB,GAAE,CAAC;IAEzC,uDAAuD;IACvD,MAAM,cAAc,GAAI,OAAO,EAAE,SAAS,EAAE,KAAe,IAAK,EAAY,CAAC;IAE7E,sCAAsC;IACtC,MAAM,UAAU,GAAG,uBAAuB,CACxC,cAAc,EACd,eAAe,EACf,OAAO,EAAE,EAAE,IAAI,EAAE,CAClB,CAAC;IAEF,0EAA0E;IAC1E,MAAM,YAAY,GAAG,IAAA,eAAO,EAAC,GAAG,EAAE;QAChC,MAAM,eAAe,GAAG,OAAO,EAAE,KAAK;YACpC,CAAC,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;YAC1B,CAAC,CAAC,SAAS,CAAC;QACd,MAAM,YAAY,GAAG,CAAC,CAAC,OAAO,EAAE,SAAS,CAAC;QAC1C,OAAO,wBAAwB,CAC7B,eAAe,EACf,UAAU,EACV,YAAY,EACZ,eAAe,CAChB,CAAC;IACJ,CAAC,EAAE,CAAC,eAAe,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC;IAE3C,OAAO;QACL,YAAY;QACZ,UAAU;KACX,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\nimport { useEffect, useMemo, useState } from \"react\";\nimport { GenerationStage } from \"../model/generate-component-response\";\nimport { useTamboGenerationStage } from \"../providers/tambo-thread-provider\";\nimport { useTamboCurrentMessage } from \"./use-current-message\";\n\n/**\n * Global stream status flags for a specific component in a message.\n * Represents the aggregate state across all props for this component only.\n * Once a component completes, its status remains stable regardless of other generations.\n */\nexport interface StreamStatus {\n /**\n * Indicates no tokens have been received for any prop and generation is not active.\n * Useful for showing initial loading states before any data arrives.\n */\n isPending: boolean;\n\n /**\n * Indicates active streaming - either generation is streaming OR at least one prop is still streaming.\n * Use this to show loading animations or skeleton states during data transmission.\n */\n isStreaming: boolean;\n\n /**\n * Indicates successful completion - generation is complete AND every prop finished without error.\n * Safe to render the final component when this is true.\n */\n isSuccess: boolean;\n\n /**\n * Indicates a fatal error occurred in any prop or the stream itself.\n * Check streamError for details about what went wrong.\n */\n isError: boolean;\n\n /**\n * The first fatal error encountered during streaming (if any).\n * Will be undefined if no errors occurred.\n */\n streamError?: Error;\n}\n\n/**\n * Streaming status flags for individual component props.\n * Tracks the state of each prop as it streams from the LLM.\n */\nexport interface PropStatus {\n /**\n * Indicates no tokens have been received for this specific prop yet.\n * The prop value is still undefined, null, or empty string.\n */\n isPending: boolean;\n\n /**\n * Indicates at least one token has been received but streaming is not complete.\n * The prop has partial content that may still be updating.\n */\n isStreaming: boolean;\n\n /**\n * Indicates this prop has finished streaming successfully.\n * The prop value is complete and stable.\n */\n isSuccess: boolean;\n\n /**\n * The error that occurred during streaming (if any).\n * Will be undefined if no error occurred for this prop.\n */\n error?: Error;\n}\n\n/**\n * SSR Guard - throws during server-side rendering.\n * Ensures the hook is only used in browser contexts.\n * @throws {Error} When called during server-side rendering\n */\nfunction assertClientSide() {\n if (typeof window === \"undefined\") {\n throw new Error(\n \"useTamboStreamStatus can only be used in browser contexts. \" +\n \"This hook is not compatible with SSR/SSG. \" +\n \"Consider wrapping it in useEffect or using dynamic imports.\",\n );\n }\n}\n\n/**\n * Track streaming status for individual props by monitoring their values.\n * Monitors when props receive their first token and when they complete streaming.\n * Maintains stable state per message - once props complete for a message, they stay complete.\n * @template Props - The type of the component props being tracked\n * @param props - The current component props object\n * @param generationStage - The current generation stage from the LLM\n * @param messageId - The ID of the current message to track component-specific state\n * @returns A record mapping each prop key to its PropStatus\n */\nfunction usePropsStreamingStatus<Props extends Record<string, any>>(\n props: Props | undefined,\n generationStage: GenerationStage,\n messageId: string,\n): Record<keyof Props, PropStatus> {\n const [propTracking, setPropTracking] = useState<\n Record<\n string,\n {\n hasStarted: boolean;\n isComplete: boolean;\n error?: Error;\n messageId: string;\n }\n >\n >({});\n\n /** Reset tracking only when the message changes */\n useEffect(() => {\n setPropTracking((prev) => {\n // If we have tracking data for a different message, reset\n const hasOldMessageData = Object.values(prev).some(\n (track) => track.messageId && track.messageId !== messageId,\n );\n return hasOldMessageData ? {} : prev;\n });\n }, [messageId]);\n\n /** Track when props start streaming (receive first token) and when they complete */\n useEffect(() => {\n if (!props) return;\n\n setPropTracking((prev) => {\n const updated = { ...prev };\n let hasChanges = false;\n\n // First pass: identify which props are starting now\n const propsStartingNow: string[] = [];\n Object.entries(props).forEach(([key, value]) => {\n const current = prev[key] || {\n hasStarted: false,\n isComplete: false,\n };\n\n /** A prop starts streaming when it has a non-empty value for the first time */\n const hasContent =\n value !== undefined && value !== null && value !== \"\";\n const justStarted = hasContent && !current.hasStarted;\n\n if (justStarted) {\n propsStartingNow.push(key);\n }\n });\n\n // Second pass: update tracking and mark previous props as complete\n Object.entries(props).forEach(([key, value]) => {\n const current = prev[key] || {\n hasStarted: false,\n isComplete: false,\n };\n\n /** A prop starts streaming when it has a non-empty value for the first time */\n const hasContent =\n value !== undefined && value !== null && value !== \"\";\n const justStarted = hasContent && !current.hasStarted;\n\n /**\n * A prop is complete when it has started and either:\n * 1. A following prop has started, OR\n * 2. Generation is complete (for the final prop)\n */\n const hasFollowingPropStarted = propsStartingNow.some(\n (startingKey) => startingKey !== key,\n );\n const isGenerationComplete =\n generationStage === GenerationStage.COMPLETE;\n const isComplete =\n current.hasStarted &&\n (hasFollowingPropStarted || isGenerationComplete) &&\n !current.isComplete;\n\n // Once a prop is complete for this message, it stays complete\n if (current.isComplete && current.messageId === messageId) {\n // Skip - already complete for this message\n return;\n }\n\n if (justStarted || isComplete) {\n updated[key] = {\n ...current,\n hasStarted: justStarted ? true : current.hasStarted,\n isComplete: isComplete ? true : current.isComplete,\n messageId,\n };\n hasChanges = true;\n }\n });\n\n return hasChanges ? updated : prev;\n });\n }, [props, generationStage, messageId]);\n\n /** Convert tracking state to PropStatus objects */\n return useMemo(() => {\n if (!props) return {} as Record<keyof Props, PropStatus>;\n\n const result = {} as Record<keyof Props, PropStatus>;\n\n Object.keys(props).forEach((key) => {\n const tracking = propTracking[key] || {\n hasStarted: false,\n isComplete: false,\n messageId: \"\",\n };\n\n // If this prop is complete for this message, it stays complete\n const isCompleteForThisMessage =\n tracking.isComplete && tracking.messageId === messageId;\n\n // Only consider generation stage if this prop isn't already complete for this message\n const isGenerationStreaming =\n !isCompleteForThisMessage &&\n generationStage === GenerationStage.STREAMING_RESPONSE;\n\n result[key as keyof Props] = {\n isPending: !tracking.hasStarted && !isCompleteForThisMessage,\n isStreaming:\n tracking.hasStarted &&\n !isCompleteForThisMessage &&\n isGenerationStreaming,\n isSuccess: isCompleteForThisMessage,\n error: tracking.error,\n };\n });\n\n return result;\n }, [props, propTracking, generationStage, messageId]);\n}\n\n/**\n * Derives global StreamStatus from generation stage and individual prop statuses.\n * Aggregates individual prop states into a unified stream status.\n * @template Props - The type of the component props\n * @param generationStage - The current generation stage from the LLM\n * @param propStatus - Status record for each individual prop\n * @param hasComponent - Whether a component exists in the current message\n * @param generationError - Any error from the generation process itself\n * @returns The aggregated StreamStatus for the entire component\n */\nfunction deriveGlobalStreamStatus<Props extends Record<string, any>>(\n generationStage: GenerationStage,\n propStatus: Record<keyof Props, PropStatus>,\n hasComponent: boolean,\n generationError?: Error,\n): StreamStatus {\n const propStatuses = Object.values(propStatus);\n\n // If all props are already successful, the component is complete regardless of generation stage\n const allPropsSuccessful =\n propStatuses.length > 0 && propStatuses.every((p) => p.isSuccess);\n\n // Only consider generation stage if not all props are complete\n const isGenerationStreaming =\n !allPropsSuccessful &&\n generationStage === GenerationStage.STREAMING_RESPONSE;\n const isGenerationError = generationStage === GenerationStage.ERROR;\n\n /** Find first error from generation or any prop */\n const firstError =\n generationError ?? propStatuses.find((p) => p.error)?.error;\n\n return {\n /** isPending: no component yet OR (has component but no props have started) */\n isPending:\n !hasComponent ||\n (!isGenerationStreaming &&\n !allPropsSuccessful &&\n propStatuses.every((p) => p.isPending)),\n\n /** isStreaming: any prop is streaming (generation stage doesn't matter if props are complete) */\n isStreaming: propStatuses.some((p) => p.isStreaming),\n\n /** isSuccess: all props successful (component is stable once all props complete) */\n isSuccess: allPropsSuccessful,\n\n /** isError: generation error OR any prop error */\n isError:\n isGenerationError ||\n propStatuses.some((p) => p.error) ||\n !!generationError,\n\n streamError: firstError,\n };\n}\n\n/**\n * Track streaming status for Tambo component props.\n *\n * **Important**: Props update repeatedly during streaming and may be partial.\n * Use `propStatus.<field>?.isSuccess` before treating a prop as complete.\n *\n * Pair with `useTamboComponentState` to disable inputs while streaming.\n * @see {@link https://docs.tambo.co/concepts/generative-interfaces/component-state}\n * @template Props - Component props type\n * @returns `streamStatus` (overall) and `propStatus` (per-prop) flags\n * @throws {Error} When used during SSR/SSG\n * @example\n * ```tsx\n * // Wait for entire stream\n * const { streamStatus } = useTamboStreamStatus();\n * if (!streamStatus.isSuccess) return <Spinner />;\n * return <Card {...props} />;\n * ```\n * @example\n * ```tsx\n * // Highlight in-flight props\n * const { propStatus } = useTamboStreamStatus<Props>();\n * <h2 className={propStatus.title.isStreaming ? \"animate-pulse\" : \"\"}>\n * {title}\n * </h2>\n * ```\n */\nexport function useTamboStreamStatus<\n Props extends Record<string, any> = Record<string, any>,\n>(): {\n streamStatus: StreamStatus;\n propStatus: Record<keyof Props, PropStatus>;\n} {\n /** SSR Guard - ensure client-side only execution */\n assertClientSide();\n\n const { generationStage } = useTamboGenerationStage();\n const message = useTamboCurrentMessage();\n\n /** Get the current component props from the message */\n const componentProps = (message?.component?.props as Props) || ({} as Props);\n\n /** Track per-prop streaming status */\n const propStatus = usePropsStreamingStatus(\n componentProps,\n generationStage,\n message?.id ?? \"\",\n );\n\n /** Derive global stream status from prop statuses and generation stage */\n const streamStatus = useMemo(() => {\n const generationError = message?.error\n ? new Error(message.error)\n : undefined;\n const hasComponent = !!message?.component;\n return deriveGlobalStreamStatus(\n generationStage,\n propStatus,\n hasComponent,\n generationError,\n );\n }, [generationStage, propStatus, message]);\n\n return {\n streamStatus,\n propStatus,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-hooks.d.ts","sourceRoot":"","sources":["../../src/mcp/mcp-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"mcp-hooks.d.ts","sourceRoot":"","sources":["../../src/mcp/mcp-hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAGzB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAKvD,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,SAAS,EAEf,MAAM,sBAAsB,CAAC;AAkC9B,MAAM,MAAM,cAAc,GAAG,iBAAiB,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC,CAAC;AAClE,MAAM,WAAW,eAAe;IAE9B,MAAM,EAAE,kBAAkB,CAAC;IAC3B,MAAM,EAAE,cAAc,CAAC;CACxB;AAED,MAAM,MAAM,gBAAgB,GAAG,mBAAmB,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAExE;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,IAAI,CAAC;IACb,QAAQ,EAAE,gBAAgB,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,kBAAkB,CAAC;IAC3B,QAAQ,EAAE,gBAAgB,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,MAAM,iBAAiB,GAAG,qBAAqB,GAAG,gBAAgB,CAAC;AAoBzE;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,iBAAiB,GACvB,KAAK,IAAI,gBAAgB,CAE3B;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,CAAC,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;gBA/D3C,kBAAkB;;WAoInB,KAAK,GAAG,IAAI;YACX,KAAK,EAAE;eACJ,OAAO;eACP,OAAO;aACT,OAAO;cACN,OAAO;kBACH,OAAO;gBACT,OAAO;eACR,OAAO;aACT,MAAM,OAAO,CAAC,IAAI,CAAC;EAb7B;AAmDD;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,SAAS,GAChB,MAAM,IAAI,kBAAkB,CAE9B;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAC/B,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,IAAI,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0ClC;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,CAAC,EAAE,MAAM;;WArH9C,KAAK,GAAG,IAAI;YACX,KAAK,EAAE;eACJ,OAAO;eACP,OAAO;aACT,OAAO;cACN,OAAO;kBACH,OAAO;gBACT,OAAO;eACR,OAAO;aACT,MAAM,OAAO,CAAC,IAAI,CAAC;EAiP7B;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS;;;;;;;;;;;;;;;;;;;;;;;;iBAoElE"}
|
package/dist/mcp/mcp-hooks.js
CHANGED
|
@@ -39,11 +39,43 @@ exports.isConnectedMcpServer = isConnectedMcpServer;
|
|
|
39
39
|
exports.useTamboMcpPrompt = useTamboMcpPrompt;
|
|
40
40
|
exports.useTamboMcpResourceList = useTamboMcpResourceList;
|
|
41
41
|
exports.useTamboMcpResource = useTamboMcpResource;
|
|
42
|
+
const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
42
43
|
const React = __importStar(require("react"));
|
|
43
44
|
const hooks_1 = require("../hooks");
|
|
44
45
|
const tambo_registry_provider_1 = require("../providers/tambo-registry-provider");
|
|
45
46
|
const mcp_constants_1 = require("./mcp-constants");
|
|
46
47
|
const tambo_mcp_provider_1 = require("./tambo-mcp-provider");
|
|
48
|
+
/**
|
|
49
|
+
* Check if an error is an MCP MethodNotFound error (-32601).
|
|
50
|
+
* This error occurs when a server doesn't support a particular method.
|
|
51
|
+
*/
|
|
52
|
+
function isMethodNotFoundError(error) {
|
|
53
|
+
return error instanceof types_js_1.McpError && error.code === types_js_1.ErrorCode.MethodNotFound;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Check if an MCP server supports listing prompts.
|
|
57
|
+
* Returns true if capabilities are unknown (undefined) to maintain backward compatibility,
|
|
58
|
+
* since some servers don't properly report capabilities.
|
|
59
|
+
*/
|
|
60
|
+
function serverSupportsPrompts(server) {
|
|
61
|
+
const capabilities = server.client.getServerCapabilities?.();
|
|
62
|
+
// If capabilities are undefined, assume the server supports prompts (optimistic approach)
|
|
63
|
+
if (capabilities === undefined)
|
|
64
|
+
return true;
|
|
65
|
+
return capabilities.prompts != null;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Check if an MCP server supports listing resources.
|
|
69
|
+
* Returns true if capabilities are unknown (undefined) to maintain backward compatibility,
|
|
70
|
+
* since some servers don't properly report capabilities.
|
|
71
|
+
*/
|
|
72
|
+
function serverSupportsResources(server) {
|
|
73
|
+
const capabilities = server.client.getServerCapabilities?.();
|
|
74
|
+
// If capabilities are undefined, assume the server supports resources (optimistic approach)
|
|
75
|
+
if (capabilities === undefined)
|
|
76
|
+
return true;
|
|
77
|
+
return capabilities.resources != null;
|
|
78
|
+
}
|
|
47
79
|
function toPublicResourceEntry(entry) {
|
|
48
80
|
if (entry.server === null) {
|
|
49
81
|
const { isDynamic: _isDynamic, ...publicEntry } = entry;
|
|
@@ -76,14 +108,25 @@ function useTamboMcpPromptList(search) {
|
|
|
76
108
|
// Fast path: if this server doesn't have a client, skip work
|
|
77
109
|
if (!isConnectedMcpServer(mcpServer))
|
|
78
110
|
return [];
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
111
|
+
// Skip if server doesn't support prompts capability
|
|
112
|
+
if (!serverSupportsPrompts(mcpServer))
|
|
113
|
+
return [];
|
|
114
|
+
try {
|
|
115
|
+
const result = await mcpServer.client.client.listPrompts();
|
|
116
|
+
const prompts = result?.prompts ?? [];
|
|
117
|
+
// Return prompts without prefixes - we'll apply prefixing in combine
|
|
118
|
+
const promptsEntries = prompts.map((prompt) => ({
|
|
119
|
+
server: mcpServer,
|
|
120
|
+
prompt,
|
|
121
|
+
}));
|
|
122
|
+
return promptsEntries;
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
// Gracefully handle MethodNotFound - server doesn't support this method
|
|
126
|
+
if (isMethodNotFoundError(error))
|
|
127
|
+
return [];
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
87
130
|
},
|
|
88
131
|
})),
|
|
89
132
|
combine: (results) => {
|
|
@@ -214,14 +257,25 @@ function useTamboMcpResourceList(search) {
|
|
|
214
257
|
// Fast path: if this server doesn't have a client, skip work
|
|
215
258
|
if (!isConnectedMcpServer(mcpServer))
|
|
216
259
|
return [];
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
260
|
+
// Skip if server doesn't support resources capability
|
|
261
|
+
if (!serverSupportsResources(mcpServer))
|
|
262
|
+
return [];
|
|
263
|
+
try {
|
|
264
|
+
const result = await mcpServer.client.client.listResources();
|
|
265
|
+
const resources = result?.resources ?? [];
|
|
266
|
+
// Return resources without prefixes - we'll apply prefixing in combine
|
|
267
|
+
const resourceEntries = resources.map((resource) => ({
|
|
268
|
+
server: mcpServer,
|
|
269
|
+
resource,
|
|
270
|
+
}));
|
|
271
|
+
return resourceEntries;
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
// Gracefully handle MethodNotFound - server doesn't support this method
|
|
275
|
+
if (isMethodNotFoundError(error))
|
|
276
|
+
return [];
|
|
277
|
+
throw error;
|
|
278
|
+
}
|
|
225
279
|
},
|
|
226
280
|
})),
|
|
227
281
|
// Dynamic resource source query (if exists) - search IS in queryKey to allow dynamic generation
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp-hooks.js","sourceRoot":"","sources":["../../src/mcp/mcp-hooks.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,gDAIC;AAOD,sDAwDC;AAyDD,oDAIC;AAQD,8CA4CC;AAQD,0DA4HC;AASD,kDAoEC;AAtcD,6CAA+B;AAC/B,oCAA0D;AAC1D,kFAAwE;AACxE,mDAAsD;AACtD,6DAI8B;AA0C9B,SAAS,qBAAqB,CAC5B,KAAgC;IAEhC,IAAI,KAAK,CAAC,MAAM,KAAK,IAAI,EAAE,CAAC;QAC1B,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,WAAW,EAAE,GAAG,KAAK,CAAC;QACxD,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,SAAgB,kBAAkB,CAChC,KAAwB;IAExB,OAAO,KAAK,CAAC,MAAM,KAAK,IAAI,IAAI,oBAAoB,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AACrE,CAAC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB,CAAC,MAAe;IACnD,MAAM,UAAU,GAAG,IAAA,uCAAkB,GAAE,CAAC;IAExC,MAAM,OAAO,GAAG,IAAA,uBAAe,EAAC;QAC9B,OAAO,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;YACtC,+DAA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CAC9B,WAAW,IAAI,CAAC,oBAAoB,IAAI,qBAAqB,CAAC,CAC/D,CAAC;IAEF,MAAM,WAAW,GACf,kBAAkB,IAAI,iBAAiB;QACrC,CAAC,CAAC,mCAAmB;QACrB,CAAC,CAAC,SAAS,EAAE,GAAG,CAAC;IAErB,OAAO,IAAA,qBAAa,EAAC;QACnB,QAAQ,EAAE,CAAC,UAAU,EAAE,WAAW,EAAE,WAAW,CAAC;QAChD,OAAO,EAAE,gBAAgB;QACzB,OAAO,EAAE,KAAK,IAAwC,EAAE;YACtD,IAAI,CAAC,mBAAmB,EAAE,CAAC;gBACzB,OAAO,IAAI,CAAC;YACd,CAAC;YAED,oDAAoD;YACpD,IAAI,cAAc,IAAI,CAAC,kBAAkB,IAAI,iBAAiB,CAAC,EAAE,CAAC;gBAChE,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,WAAW,CAAC,mBAAmB,CAAC,CAAC;gBACrE,OAAO,MAAM,IAAI,IAAI,CAAC;YACxB,CAAC;YAED,+BAA+B;YAC/B,IAAI,SAAS,IAAI,oBAAoB,CAAC,SAAS,CAAC,EAAE,CAAC;gBACjD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC;oBACxD,GAAG,EAAE,mBAAmB;iBACzB,CAAC,CAAC;gBACH,OAAO,MAAM,IAAI,IAAI,CAAC;YACxB,CAAC;YAED,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n GetPromptResult,\n type ListPromptsResult,\n type ListResourcesResult,\n type ReadResourceResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { UseQueryResult } from \"@tanstack/react-query\";\nimport * as React from \"react\";\nimport { useTamboQueries, useTamboQuery } from \"../hooks\";\nimport { useTamboRegistry } from \"../providers/tambo-registry-provider\";\nimport { REGISTRY_SERVER_KEY } from \"./mcp-constants\";\nimport {\n type ConnectedMcpServer,\n type McpServer,\n useTamboMcpServers,\n} from \"./tambo-mcp-provider\";\n\nexport type ListPromptItem = ListPromptsResult[\"prompts\"][number];\nexport interface ListPromptEntry {\n // Only connected servers produce prompt entries, so expose the connected type\n server: ConnectedMcpServer;\n prompt: ListPromptItem;\n}\n\nexport type ListResourceItem = ListResourcesResult[\"resources\"][number];\n\n/**\n * Registry resource entry - resources from the local registry (not MCP servers).\n *\n * These entries always have `server === null`.\n */\nexport interface RegistryResourceEntry {\n server: null;\n resource: ListResourceItem;\n}\n\n/**\n * MCP server resource entry - resources from connected MCP servers.\n */\nexport interface McpResourceEntry {\n server: ConnectedMcpServer;\n resource: ListResourceItem;\n}\n\n/**\n * Union type for all resource entries returned by `useTamboMcpResourceList`.\n */\nexport type ListResourceEntry = RegistryResourceEntry | McpResourceEntry;\n\ntype InternalRegistryResourceEntry = RegistryResourceEntry & {\n isDynamic: boolean;\n};\n\ntype InternalListResourceEntry =\n | McpResourceEntry\n | InternalRegistryResourceEntry;\n\nfunction toPublicResourceEntry(\n entry: InternalListResourceEntry,\n): ListResourceEntry {\n if (entry.server === null) {\n const { isDynamic: _isDynamic, ...publicEntry } = entry;\n return publicEntry;\n }\n return entry;\n}\n\n/**\n * Type guard for narrowing a `ListResourceEntry` to an MCP-backed resource.\n * @param entry - The resource entry to check\n * @returns True if the entry is from an MCP server, false if it's from the registry\n */\nexport function isMcpResourceEntry(\n entry: ListResourceEntry,\n): entry is McpResourceEntry {\n return entry.server !== null && isConnectedMcpServer(entry.server);\n}\n\n/**\n * Hook to get the prompts for all the registered MCP servers.\n * @param search - Optional search string to filter prompts by name (case-insensitive).\n * @returns The prompts for the MCP servers, including the server that the prompt was found on.\n */\nexport function useTamboMcpPromptList(search?: string) {\n const mcpServers = useTamboMcpServers();\n\n const queries = useTamboQueries({\n queries: mcpServers.map((mcpServer) => ({\n // search is NOT in queryKey - we filter locally after fetching\n queryKey: [\"mcp-prompts\", mcpServer.key],\n // Only run for connected servers that have a client\n enabled: isConnectedMcpServer(mcpServer),\n queryFn: async (): Promise<ListPromptEntry[]> => {\n // Fast path: if this server doesn't have a client, skip work\n if (!isConnectedMcpServer(mcpServer)) return [];\n\n const result = await mcpServer.client.client.listPrompts();\n const prompts: ListPromptItem[] = result?.prompts ?? [];\n // Return prompts without prefixes - we'll apply prefixing in combine\n const promptsEntries = prompts.map((prompt) => ({\n server: mcpServer,\n prompt,\n }));\n return promptsEntries;\n },\n })),\n combine: (results) => {\n const combined = combineArrayResults(results);\n\n // Always apply serverKey prefix to MCP prompts (breaking change for consistency with resources)\n // This ensures clear separation between local and remote prompts\n return {\n ...combined,\n data: combined.data.map((entry) => ({\n ...entry,\n prompt: {\n ...entry.prompt,\n name: `${entry.server.serverKey}:${entry.prompt.name}`,\n },\n })),\n };\n },\n });\n\n // Filter results by search string - runs on every search change (not just query completion)\n const filteredData = React.useMemo(() => {\n if (!search) return queries.data;\n\n const normalizedSearch = search.toLowerCase();\n return queries.data.filter((entry) => {\n const name = entry.prompt.name?.toLowerCase() ?? \"\";\n return name.includes(normalizedSearch);\n });\n }, [queries.data, search]);\n\n return {\n ...queries,\n data: filteredData,\n };\n}\n// TODO: find a more general place for this\nfunction combineArrayResults<T>(results: UseQueryResult<T[]>[]): {\n data: T[];\n error: Error | null;\n errors: Error[];\n isPending: boolean;\n isSuccess: boolean;\n isError: boolean;\n isPaused: boolean;\n isRefetching: boolean;\n isFetching: boolean;\n isLoading: boolean;\n refetch: () => Promise<void>;\n} {\n const errors = results\n .filter((result) => result.isError)\n .map((result) => result.error);\n\n // Treat queries that are idle (disabled) as non-blocking for aggregate status\n const enabledish = results.filter(\n (r) => r.fetchStatus !== \"idle\" || r.isSuccess || r.isError,\n );\n\n return {\n // Prefer flatMap to avoid extra intermediate arrays\n data: results.flatMap((result) =>\n result.isSuccess && Array.isArray(result.data) ? result.data : [],\n ),\n // Preserve a single error for compatibility and expose the full list for diagnostics\n error: errors[0] ?? null,\n errors,\n isPending: enabledish.some((result) => result.isPending),\n isSuccess:\n enabledish.length > 0 && enabledish.every((result) => result.isSuccess),\n isError: errors.length > 0,\n isPaused: enabledish.some((result) => result.isPaused),\n isRefetching: enabledish.some((result) => result.isRefetching),\n isFetching: enabledish.some((result) => result.isFetching),\n isLoading: enabledish.some((result) => result.isLoading),\n // Aggregate refetch to trigger all underlying queries\n refetch: async () => {\n await Promise.all(\n results.map(async (r) => {\n await r.refetch();\n }),\n );\n },\n };\n}\n\n/**\n * Type guard for narrowing McpServer to ConnectedMcpServer.\n * A connected server has a non-null client.\n * @param server - The MCP server to check\n * @returns True if the server is connected, false otherwise\n */\nexport function isConnectedMcpServer(\n server: McpServer,\n): server is ConnectedMcpServer {\n return \"client\" in server && server.client != null;\n}\n\n/**\n * Hook to get the prompt for the specified name.\n * @param promptName - The name of the prompt to get. Can be prefixed with serverKey (e.g., \"linear:issue\") or unprefixed.\n * @param args - The arguments to pass to the prompt.\n * @returns The prompt for the specified name.\n */\nexport function useTamboMcpPrompt(\n promptName: string | undefined,\n args: Record<string, string> = {},\n) {\n // figure out which server has the prompt\n const { data: promptEntries } = useTamboMcpPromptList();\n const promptEntry = promptEntries?.find(\n (prompt) => prompt.prompt.name === promptName,\n );\n // Use the stable server key (and the server instance itself) instead of brittle\n // name/url/transport matching.\n const mcpServer = promptEntry?.server;\n\n // Strip the prefix to get the original prompt name for the MCP server call\n const originalPromptName = promptName?.includes(\":\")\n ? promptName.split(\":\").slice(1).join(\":\")\n : promptName;\n\n // Canonicalize args to avoid unstable cache keys from object identity/order\n const sortedArgsEntries = Object.keys(args)\n .sort()\n .map((k) => [k, args[k]] as const);\n return useTamboQuery({\n // Include server identity and sorted args to prevent stale cache hits\n queryKey: [\"mcp-prompt\", promptName, mcpServer?.key, sortedArgsEntries],\n // Only run when we have a prompt name and a connected server\n enabled: Boolean(\n promptName && mcpServer && isConnectedMcpServer(mcpServer),\n ),\n queryFn: async (): Promise<GetPromptResult | null> => {\n if (\n !originalPromptName ||\n !mcpServer ||\n !isConnectedMcpServer(mcpServer)\n ) {\n return null;\n }\n const result = await mcpServer.client.client.getPrompt({\n name: originalPromptName,\n arguments: args,\n });\n return result ?? null; // return null because react-query doesn't like undefined results\n },\n });\n}\n\n/**\n * Hook to get the resources for all the registered MCP servers and registry.\n * @param search - Optional search string. For MCP servers, results are filtered locally after fetching.\n * For registry dynamic sources, the search is passed to listResources(search) for dynamic generation.\n * @returns The resources from MCP servers and the local registry, including the server that the resource was found on (null for registry resources).\n */\nexport function useTamboMcpResourceList(search?: string) {\n const mcpServers = useTamboMcpServers();\n const { resources: staticResources, resourceSource } = useTamboRegistry();\n\n // Build list of queries: MCP servers + optional dynamic resource source\n const queriesToRun = [\n // MCP server queries - search is NOT in queryKey so queries don't re-run on search change\n ...mcpServers.map((mcpServer) => ({\n queryKey: [\"mcp-resources\", mcpServer.key],\n // Only run for connected servers that have a client\n enabled: isConnectedMcpServer(mcpServer),\n queryFn: async (): Promise<McpResourceEntry[]> => {\n // Fast path: if this server doesn't have a client, skip work\n if (!isConnectedMcpServer(mcpServer)) return [];\n\n const result = await mcpServer.client.client.listResources();\n const resources: ListResourceItem[] = result?.resources ?? [];\n // Return resources without prefixes - we'll apply prefixing in combine\n const resourceEntries: McpResourceEntry[] = resources.map(\n (resource) => ({\n server: mcpServer,\n resource,\n }),\n );\n return resourceEntries;\n },\n })),\n // Dynamic resource source query (if exists) - search IS in queryKey to allow dynamic generation\n ...(resourceSource\n ? [\n {\n queryKey: [\"registry-resources\", \"dynamic\", search],\n enabled: true,\n queryFn: async (): Promise<InternalRegistryResourceEntry[]> => {\n if (!resourceSource) return [];\n const resources = await resourceSource.listResources(search);\n return resources.map((resource) => ({\n server: null,\n resource,\n isDynamic: true,\n }));\n },\n },\n ]\n : []),\n ];\n\n const queries = useTamboQueries({\n queries: queriesToRun,\n combine: (results) => {\n // Type assertion needed because queries can return different entry types\n const combined = combineArrayResults(\n results as UseQueryResult<InternalListResourceEntry[]>[],\n );\n\n // Add static registry resources (no query needed)\n const staticEntries: InternalRegistryResourceEntry[] =\n staticResources.map((resource) => ({\n server: null,\n resource,\n isDynamic: false,\n }));\n\n // Merge static resources with query results (registry resources first)\n const allData = [...staticEntries, ...combined.data];\n\n // Apply serverKey prefix to ALL resources for unified @serverKey:uri format\n // Registry resources get REGISTRY_SERVER_KEY prefix, MCP resources get their serverKey\n const prefixedData = allData.map((entry) => {\n if (entry.server === null) {\n // Registry resource - prefix with REGISTRY_SERVER_KEY\n return {\n ...entry,\n resource: {\n ...entry.resource,\n uri: `${REGISTRY_SERVER_KEY}:${entry.resource.uri}`,\n },\n };\n }\n // MCP resource - always prefix with serverKey\n return {\n ...entry,\n resource: {\n ...entry.resource,\n uri: `${entry.server.serverKey}:${entry.resource.uri}`,\n },\n };\n });\n\n return {\n ...combined,\n data: prefixedData,\n };\n },\n });\n\n // Filter results by search string - runs on every search change (not just query completion)\n // - MCP resources are filtered locally\n // - Static registry resources are filtered locally\n // - Dynamic registry resources are already filtered by listResources(search)\n const filteredData = React.useMemo((): InternalListResourceEntry[] => {\n if (!search) return queries.data;\n\n const normalizedSearch = search.toLowerCase();\n return queries.data.filter((entry) => {\n if (entry.server === null && entry.isDynamic) {\n return true;\n }\n\n const name = entry.resource.name?.toLowerCase() ?? \"\";\n const uri = entry.resource.uri.toLowerCase();\n return name.includes(normalizedSearch) || uri.includes(normalizedSearch);\n });\n }, [queries.data, search]);\n\n const publicData = React.useMemo(\n () => filteredData.map(toPublicResourceEntry),\n [filteredData],\n );\n\n return {\n ...queries,\n data: publicData,\n };\n}\n\n/**\n * Hook to get the resource for the specified URI.\n * @param resourceUri - The URI of the resource to get. Must be prefixed:\n * - MCP resources: prefixed with serverKey (e.g., \"linear:file://foo\")\n * - Registry resources: prefixed with \"registry:\" (e.g., \"registry:file://bar\")\n * @returns The resource for the specified URI.\n */\nexport function useTamboMcpResource(resourceUri: string | undefined) {\n const { resourceSource } = useTamboRegistry();\n const { data: resourceEntries } = useTamboMcpResourceList();\n\n // Find which server/source has the resource\n const resourceEntry = resourceEntries?.find(\n (entry) => entry.resource.uri === resourceUri,\n );\n\n // Determine if this is a registry resource or MCP resource\n const isRegistryResource = resourceEntry?.server === null;\n const mcpServer = resourceEntry?.server ?? null;\n\n // Check if the URI has the registry prefix\n const hasRegistryPrefix = Boolean(\n resourceUri?.startsWith(`${REGISTRY_SERVER_KEY}:`),\n );\n\n // Strip the prefix to get the original resource URI for fetching\n let originalResourceUri: string | undefined;\n if (isRegistryResource || hasRegistryPrefix) {\n const prefixLen = REGISTRY_SERVER_KEY.length + 1; // +1 for the colon\n originalResourceUri = resourceUri?.slice(prefixLen);\n } else if (mcpServer) {\n const prefixLen = mcpServer.serverKey.length + 1; // +1 for the colon\n originalResourceUri = resourceUri?.slice(prefixLen);\n }\n\n // Check if we can fetch this resource\n const hasRegistrySource = resourceSource != null;\n const hasConnectedMcpServer =\n mcpServer != null && isConnectedMcpServer(mcpServer);\n const canFetchFromRegistry =\n hasRegistrySource && (isRegistryResource || hasRegistryPrefix);\n const canFetchResource = Boolean(\n resourceUri && (canFetchFromRegistry || hasConnectedMcpServer),\n );\n\n const locationKey =\n isRegistryResource || hasRegistryPrefix\n ? REGISTRY_SERVER_KEY\n : mcpServer?.key;\n\n return useTamboQuery({\n queryKey: [\"resource\", resourceUri, locationKey],\n enabled: canFetchResource,\n queryFn: async (): Promise<ReadResourceResult | null> => {\n if (!originalResourceUri) {\n return null;\n }\n\n // Registry resource: use resourceSource.getResource\n if (resourceSource && (isRegistryResource || hasRegistryPrefix)) {\n const result = await resourceSource.getResource(originalResourceUri);\n return result ?? null;\n }\n\n // MCP resource: use MCP client\n if (mcpServer && isConnectedMcpServer(mcpServer)) {\n const result = await mcpServer.client.client.readResource({\n uri: originalResourceUri,\n });\n return result ?? null;\n }\n\n return null;\n },\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mcp-hooks.js","sourceRoot":"","sources":["../../src/mcp/mcp-hooks.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,g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CAAC,EAAE,CAAC;gBAChE,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,WAAW,CAAC,mBAAmB,CAAC,CAAC;gBACrE,OAAO,MAAM,IAAI,IAAI,CAAC;YACxB,CAAC;YAED,+BAA+B;YAC/B,IAAI,SAAS,IAAI,oBAAoB,CAAC,SAAS,CAAC,EAAE,CAAC;gBACjD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,YAAY,CAAC;oBACxD,GAAG,EAAE,mBAAmB;iBACzB,CAAC,CAAC;gBACH,OAAO,MAAM,IAAI,IAAI,CAAC;YACxB,CAAC;YAED,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n ErrorCode,\n GetPromptResult,\n type ListPromptsResult,\n type ListResourcesResult,\n McpError,\n type ReadResourceResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { UseQueryResult } from \"@tanstack/react-query\";\nimport * as React from \"react\";\nimport { useTamboQueries, useTamboQuery } from \"../hooks\";\nimport { useTamboRegistry } from \"../providers/tambo-registry-provider\";\nimport { REGISTRY_SERVER_KEY } from \"./mcp-constants\";\nimport {\n type ConnectedMcpServer,\n type McpServer,\n useTamboMcpServers,\n} from \"./tambo-mcp-provider\";\n\n/**\n * Check if an error is an MCP MethodNotFound error (-32601).\n * This error occurs when a server doesn't support a particular method.\n */\nfunction isMethodNotFoundError(error: unknown): boolean {\n return error instanceof McpError && error.code === ErrorCode.MethodNotFound;\n}\n\n/**\n * Check if an MCP server supports listing prompts.\n * Returns true if capabilities are unknown (undefined) to maintain backward compatibility,\n * since some servers don't properly report capabilities.\n */\nfunction serverSupportsPrompts(server: ConnectedMcpServer): boolean {\n const capabilities = server.client.getServerCapabilities?.();\n // If capabilities are undefined, assume the server supports prompts (optimistic approach)\n if (capabilities === undefined) return true;\n return capabilities.prompts != null;\n}\n\n/**\n * Check if an MCP server supports listing resources.\n * Returns true if capabilities are unknown (undefined) to maintain backward compatibility,\n * since some servers don't properly report capabilities.\n */\nfunction serverSupportsResources(server: ConnectedMcpServer): boolean {\n const capabilities = server.client.getServerCapabilities?.();\n // If capabilities are undefined, assume the server supports resources (optimistic approach)\n if (capabilities === undefined) return true;\n return capabilities.resources != null;\n}\n\nexport type ListPromptItem = ListPromptsResult[\"prompts\"][number];\nexport interface ListPromptEntry {\n // Only connected servers produce prompt entries, so expose the connected type\n server: ConnectedMcpServer;\n prompt: ListPromptItem;\n}\n\nexport type ListResourceItem = ListResourcesResult[\"resources\"][number];\n\n/**\n * Registry resource entry - resources from the local registry (not MCP servers).\n *\n * These entries always have `server === null`.\n */\nexport interface RegistryResourceEntry {\n server: null;\n resource: ListResourceItem;\n}\n\n/**\n * MCP server resource entry - resources from connected MCP servers.\n */\nexport interface McpResourceEntry {\n server: ConnectedMcpServer;\n resource: ListResourceItem;\n}\n\n/**\n * Union type for all resource entries returned by `useTamboMcpResourceList`.\n */\nexport type ListResourceEntry = RegistryResourceEntry | McpResourceEntry;\n\ntype InternalRegistryResourceEntry = RegistryResourceEntry & {\n isDynamic: boolean;\n};\n\ntype InternalListResourceEntry =\n | McpResourceEntry\n | InternalRegistryResourceEntry;\n\nfunction toPublicResourceEntry(\n entry: InternalListResourceEntry,\n): ListResourceEntry {\n if (entry.server === null) {\n const { isDynamic: _isDynamic, ...publicEntry } = entry;\n return publicEntry;\n }\n return entry;\n}\n\n/**\n * Type guard for narrowing a `ListResourceEntry` to an MCP-backed resource.\n * @param entry - The resource entry to check\n * @returns True if the entry is from an MCP server, false if it's from the registry\n */\nexport function isMcpResourceEntry(\n entry: ListResourceEntry,\n): entry is McpResourceEntry {\n return entry.server !== null && isConnectedMcpServer(entry.server);\n}\n\n/**\n * Hook to get the prompts for all the registered MCP servers.\n * @param search - Optional search string to filter prompts by name (case-insensitive).\n * @returns The prompts for the MCP servers, including the server that the prompt was found on.\n */\nexport function useTamboMcpPromptList(search?: string) {\n const mcpServers = useTamboMcpServers();\n\n const queries = useTamboQueries({\n queries: mcpServers.map((mcpServer) => ({\n // search is NOT in queryKey - we filter locally after fetching\n queryKey: [\"mcp-prompts\", mcpServer.key],\n // Only run for connected servers that have a client\n enabled: isConnectedMcpServer(mcpServer),\n queryFn: async (): Promise<ListPromptEntry[]> => {\n // Fast path: if this server doesn't have a client, skip work\n if (!isConnectedMcpServer(mcpServer)) return [];\n\n // Skip if server doesn't support prompts capability\n if (!serverSupportsPrompts(mcpServer)) return [];\n\n try {\n const result = await mcpServer.client.client.listPrompts();\n const prompts: ListPromptItem[] = result?.prompts ?? [];\n // Return prompts without prefixes - we'll apply prefixing in combine\n const promptsEntries = prompts.map((prompt) => ({\n server: mcpServer,\n prompt,\n }));\n return promptsEntries;\n } catch (error) {\n // Gracefully handle MethodNotFound - server doesn't support this method\n if (isMethodNotFoundError(error)) return [];\n throw error;\n }\n },\n })),\n combine: (results) => {\n const combined = combineArrayResults(results);\n\n // Always apply serverKey prefix to MCP prompts (breaking change for consistency with resources)\n // This ensures clear separation between local and remote prompts\n return {\n ...combined,\n data: combined.data.map((entry) => ({\n ...entry,\n prompt: {\n ...entry.prompt,\n name: `${entry.server.serverKey}:${entry.prompt.name}`,\n },\n })),\n };\n },\n });\n\n // Filter results by search string - runs on every search change (not just query completion)\n const filteredData = React.useMemo(() => {\n if (!search) return queries.data;\n\n const normalizedSearch = search.toLowerCase();\n return queries.data.filter((entry) => {\n const name = entry.prompt.name?.toLowerCase() ?? \"\";\n return name.includes(normalizedSearch);\n });\n }, [queries.data, search]);\n\n return {\n ...queries,\n data: filteredData,\n };\n}\n// TODO: find a more general place for this\nfunction combineArrayResults<T>(results: UseQueryResult<T[]>[]): {\n data: T[];\n error: Error | null;\n errors: Error[];\n isPending: boolean;\n isSuccess: boolean;\n isError: boolean;\n isPaused: boolean;\n isRefetching: boolean;\n isFetching: boolean;\n isLoading: boolean;\n refetch: () => Promise<void>;\n} {\n const errors = results\n .filter((result) => result.isError)\n .map((result) => result.error);\n\n // Treat queries that are idle (disabled) as non-blocking for aggregate status\n const enabledish = results.filter(\n (r) => r.fetchStatus !== \"idle\" || r.isSuccess || r.isError,\n );\n\n return {\n // Prefer flatMap to avoid extra intermediate arrays\n data: results.flatMap((result) =>\n result.isSuccess && Array.isArray(result.data) ? result.data : [],\n ),\n // Preserve a single error for compatibility and expose the full list for diagnostics\n error: errors[0] ?? null,\n errors,\n isPending: enabledish.some((result) => result.isPending),\n isSuccess:\n enabledish.length > 0 && enabledish.every((result) => result.isSuccess),\n isError: errors.length > 0,\n isPaused: enabledish.some((result) => result.isPaused),\n isRefetching: enabledish.some((result) => result.isRefetching),\n isFetching: enabledish.some((result) => result.isFetching),\n isLoading: enabledish.some((result) => result.isLoading),\n // Aggregate refetch to trigger all underlying queries\n refetch: async () => {\n await Promise.all(\n results.map(async (r) => {\n await r.refetch();\n }),\n );\n },\n };\n}\n\n/**\n * Type guard for narrowing McpServer to ConnectedMcpServer.\n * A connected server has a non-null client.\n * @param server - The MCP server to check\n * @returns True if the server is connected, false otherwise\n */\nexport function isConnectedMcpServer(\n server: McpServer,\n): server is ConnectedMcpServer {\n return \"client\" in server && server.client != null;\n}\n\n/**\n * Hook to get the prompt for the specified name.\n * @param promptName - The name of the prompt to get. Can be prefixed with serverKey (e.g., \"linear:issue\") or unprefixed.\n * @param args - The arguments to pass to the prompt.\n * @returns The prompt for the specified name.\n */\nexport function useTamboMcpPrompt(\n promptName: string | undefined,\n args: Record<string, string> = {},\n) {\n // figure out which server has the prompt\n const { data: promptEntries } = useTamboMcpPromptList();\n const promptEntry = promptEntries?.find(\n (prompt) => prompt.prompt.name === promptName,\n );\n // Use the stable server key (and the server instance itself) instead of brittle\n // name/url/transport matching.\n const mcpServer = promptEntry?.server;\n\n // Strip the prefix to get the original prompt name for the MCP server call\n const originalPromptName = promptName?.includes(\":\")\n ? promptName.split(\":\").slice(1).join(\":\")\n : promptName;\n\n // Canonicalize args to avoid unstable cache keys from object identity/order\n const sortedArgsEntries = Object.keys(args)\n .sort()\n .map((k) => [k, args[k]] as const);\n return useTamboQuery({\n // Include server identity and sorted args to prevent stale cache hits\n queryKey: [\"mcp-prompt\", promptName, mcpServer?.key, sortedArgsEntries],\n // Only run when we have a prompt name and a connected server\n enabled: Boolean(\n promptName && mcpServer && isConnectedMcpServer(mcpServer),\n ),\n queryFn: async (): Promise<GetPromptResult | null> => {\n if (\n !originalPromptName ||\n !mcpServer ||\n !isConnectedMcpServer(mcpServer)\n ) {\n return null;\n }\n const result = await mcpServer.client.client.getPrompt({\n name: originalPromptName,\n arguments: args,\n });\n return result ?? null; // return null because react-query doesn't like undefined results\n },\n });\n}\n\n/**\n * Hook to get the resources for all the registered MCP servers and registry.\n * @param search - Optional search string. For MCP servers, results are filtered locally after fetching.\n * For registry dynamic sources, the search is passed to listResources(search) for dynamic generation.\n * @returns The resources from MCP servers and the local registry, including the server that the resource was found on (null for registry resources).\n */\nexport function useTamboMcpResourceList(search?: string) {\n const mcpServers = useTamboMcpServers();\n const { resources: staticResources, resourceSource } = useTamboRegistry();\n\n // Build list of queries: MCP servers + optional dynamic resource source\n const queriesToRun = [\n // MCP server queries - search is NOT in queryKey so queries don't re-run on search change\n ...mcpServers.map((mcpServer) => ({\n queryKey: [\"mcp-resources\", mcpServer.key],\n // Only run for connected servers that have a client\n enabled: isConnectedMcpServer(mcpServer),\n queryFn: async (): Promise<McpResourceEntry[]> => {\n // Fast path: if this server doesn't have a client, skip work\n if (!isConnectedMcpServer(mcpServer)) return [];\n\n // Skip if server doesn't support resources capability\n if (!serverSupportsResources(mcpServer)) return [];\n\n try {\n const result = await mcpServer.client.client.listResources();\n const resources: ListResourceItem[] = result?.resources ?? [];\n // Return resources without prefixes - we'll apply prefixing in combine\n const resourceEntries: McpResourceEntry[] = resources.map(\n (resource) => ({\n server: mcpServer,\n resource,\n }),\n );\n return resourceEntries;\n } catch (error) {\n // Gracefully handle MethodNotFound - server doesn't support this method\n if (isMethodNotFoundError(error)) return [];\n throw error;\n }\n },\n })),\n // Dynamic resource source query (if exists) - search IS in queryKey to allow dynamic generation\n ...(resourceSource\n ? [\n {\n queryKey: [\"registry-resources\", \"dynamic\", search],\n enabled: true,\n queryFn: async (): Promise<InternalRegistryResourceEntry[]> => {\n if (!resourceSource) return [];\n const resources = await resourceSource.listResources(search);\n return resources.map((resource) => ({\n server: null,\n resource,\n isDynamic: true,\n }));\n },\n },\n ]\n : []),\n ];\n\n const queries = useTamboQueries({\n queries: queriesToRun,\n combine: (results) => {\n // Type assertion needed because queries can return different entry types\n const combined = combineArrayResults(\n results as UseQueryResult<InternalListResourceEntry[]>[],\n );\n\n // Add static registry resources (no query needed)\n const staticEntries: InternalRegistryResourceEntry[] =\n staticResources.map((resource) => ({\n server: null,\n resource,\n isDynamic: false,\n }));\n\n // Merge static resources with query results (registry resources first)\n const allData = [...staticEntries, ...combined.data];\n\n // Apply serverKey prefix to ALL resources for unified @serverKey:uri format\n // Registry resources get REGISTRY_SERVER_KEY prefix, MCP resources get their serverKey\n const prefixedData = allData.map((entry) => {\n if (entry.server === null) {\n // Registry resource - prefix with REGISTRY_SERVER_KEY\n return {\n ...entry,\n resource: {\n ...entry.resource,\n uri: `${REGISTRY_SERVER_KEY}:${entry.resource.uri}`,\n },\n };\n }\n // MCP resource - always prefix with serverKey\n return {\n ...entry,\n resource: {\n ...entry.resource,\n uri: `${entry.server.serverKey}:${entry.resource.uri}`,\n },\n };\n });\n\n return {\n ...combined,\n data: prefixedData,\n };\n },\n });\n\n // Filter results by search string - runs on every search change (not just query completion)\n // - MCP resources are filtered locally\n // - Static registry resources are filtered locally\n // - Dynamic registry resources are already filtered by listResources(search)\n const filteredData = React.useMemo((): InternalListResourceEntry[] => {\n if (!search) return queries.data;\n\n const normalizedSearch = search.toLowerCase();\n return queries.data.filter((entry) => {\n if (entry.server === null && entry.isDynamic) {\n return true;\n }\n\n const name = entry.resource.name?.toLowerCase() ?? \"\";\n const uri = entry.resource.uri.toLowerCase();\n return name.includes(normalizedSearch) || uri.includes(normalizedSearch);\n });\n }, [queries.data, search]);\n\n const publicData = React.useMemo(\n () => filteredData.map(toPublicResourceEntry),\n [filteredData],\n );\n\n return {\n ...queries,\n data: publicData,\n };\n}\n\n/**\n * Hook to get the resource for the specified URI.\n * @param resourceUri - The URI of the resource to get. Must be prefixed:\n * - MCP resources: prefixed with serverKey (e.g., \"linear:file://foo\")\n * - Registry resources: prefixed with \"registry:\" (e.g., \"registry:file://bar\")\n * @returns The resource for the specified URI.\n */\nexport function useTamboMcpResource(resourceUri: string | undefined) {\n const { resourceSource } = useTamboRegistry();\n const { data: resourceEntries } = useTamboMcpResourceList();\n\n // Find which server/source has the resource\n const resourceEntry = resourceEntries?.find(\n (entry) => entry.resource.uri === resourceUri,\n );\n\n // Determine if this is a registry resource or MCP resource\n const isRegistryResource = resourceEntry?.server === null;\n const mcpServer = resourceEntry?.server ?? null;\n\n // Check if the URI has the registry prefix\n const hasRegistryPrefix = Boolean(\n resourceUri?.startsWith(`${REGISTRY_SERVER_KEY}:`),\n );\n\n // Strip the prefix to get the original resource URI for fetching\n let originalResourceUri: string | undefined;\n if (isRegistryResource || hasRegistryPrefix) {\n const prefixLen = REGISTRY_SERVER_KEY.length + 1; // +1 for the colon\n originalResourceUri = resourceUri?.slice(prefixLen);\n } else if (mcpServer) {\n const prefixLen = mcpServer.serverKey.length + 1; // +1 for the colon\n originalResourceUri = resourceUri?.slice(prefixLen);\n }\n\n // Check if we can fetch this resource\n const hasRegistrySource = resourceSource != null;\n const hasConnectedMcpServer =\n mcpServer != null && isConnectedMcpServer(mcpServer);\n const canFetchFromRegistry =\n hasRegistrySource && (isRegistryResource || hasRegistryPrefix);\n const canFetchResource = Boolean(\n resourceUri && (canFetchFromRegistry || hasConnectedMcpServer),\n );\n\n const locationKey =\n isRegistryResource || hasRegistryPrefix\n ? REGISTRY_SERVER_KEY\n : mcpServer?.key;\n\n return useTamboQuery({\n queryKey: [\"resource\", resourceUri, locationKey],\n enabled: canFetchResource,\n queryFn: async (): Promise<ReadResourceResult | null> => {\n if (!originalResourceUri) {\n return null;\n }\n\n // Registry resource: use resourceSource.getResource\n if (resourceSource && (isRegistryResource || hasRegistryPrefix)) {\n const result = await resourceSource.getResource(originalResourceUri);\n return result ?? null;\n }\n\n // MCP resource: use MCP client\n if (mcpServer && isConnectedMcpServer(mcpServer)) {\n const result = await mcpServer.client.client.readResource({\n uri: originalResourceUri,\n });\n return result ?? null;\n }\n\n return null;\n },\n });\n}\n"]}
|
|
@@ -17,10 +17,10 @@ jest.mock("./tambo-context-helpers-provider", () => ({
|
|
|
17
17
|
removeContextHelper: mockRemoveContextHelper,
|
|
18
18
|
}),
|
|
19
19
|
}));
|
|
20
|
-
// Mock the
|
|
20
|
+
// Mock the registry provider
|
|
21
21
|
const mockRegisterTool = jest.fn();
|
|
22
|
-
jest.mock("./tambo-
|
|
23
|
-
|
|
22
|
+
jest.mock("./tambo-registry-provider", () => ({
|
|
23
|
+
useTamboRegistry: () => ({
|
|
24
24
|
registerTool: mockRegisterTool,
|
|
25
25
|
}),
|
|
26
26
|
}));
|