@od-oneapp/ai-platform 0.1.0
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 +235 -0
- package/dist/agents-base.d.mts +12 -0
- package/dist/agents-base.d.mts.map +1 -0
- package/dist/agents-base.mjs +20 -0
- package/dist/agents-base.mjs.map +1 -0
- package/dist/agents-control-flow.d.mts +115 -0
- package/dist/agents-control-flow.d.mts.map +1 -0
- package/dist/agents-control-flow.mjs +514 -0
- package/dist/agents-control-flow.mjs.map +1 -0
- package/dist/agents-coordinator.d.mts +11 -0
- package/dist/agents-coordinator.d.mts.map +1 -0
- package/dist/agents-coordinator.mjs +12 -0
- package/dist/agents-coordinator.mjs.map +1 -0
- package/dist/agents-experimental.d.mts +153 -0
- package/dist/agents-experimental.d.mts.map +1 -0
- package/dist/agents-experimental.mjs +580 -0
- package/dist/agents-experimental.mjs.map +1 -0
- package/dist/agents-fallback.d.mts +10 -0
- package/dist/agents-fallback.d.mts.map +1 -0
- package/dist/agents-fallback.mjs +15 -0
- package/dist/agents-fallback.mjs.map +1 -0
- package/dist/agents-multi-swarm.d.mts +9 -0
- package/dist/agents-multi-swarm.d.mts.map +1 -0
- package/dist/agents-multi-swarm.mjs +44 -0
- package/dist/agents-multi-swarm.mjs.map +1 -0
- package/dist/agents-multi.d.mts +10 -0
- package/dist/agents-multi.d.mts.map +1 -0
- package/dist/agents-multi.mjs +44 -0
- package/dist/agents-multi.mjs.map +1 -0
- package/dist/agents-observability.d.mts +161 -0
- package/dist/agents-observability.d.mts.map +1 -0
- package/dist/agents-observability.mjs +550 -0
- package/dist/agents-observability.mjs.map +1 -0
- package/dist/agents-patterns.d.mts +9 -0
- package/dist/agents-patterns.d.mts.map +1 -0
- package/dist/agents-patterns.mjs +18 -0
- package/dist/agents-patterns.mjs.map +1 -0
- package/dist/agents-persistence.d.mts +234 -0
- package/dist/agents-persistence.d.mts.map +1 -0
- package/dist/agents-persistence.mjs +447 -0
- package/dist/agents-persistence.mjs.map +1 -0
- package/dist/agents-triage.d.mts +11 -0
- package/dist/agents-triage.d.mts.map +1 -0
- package/dist/agents-triage.mjs +13 -0
- package/dist/agents-triage.mjs.map +1 -0
- package/dist/agents-workflows.d.mts +9 -0
- package/dist/agents-workflows.d.mts.map +1 -0
- package/dist/agents-workflows.mjs +9 -0
- package/dist/agents-workflows.mjs.map +1 -0
- package/dist/agents.d.mts +30 -0
- package/dist/agents.d.mts.map +1 -0
- package/dist/agents.mjs +50 -0
- package/dist/agents.mjs.map +1 -0
- package/dist/aggregation-8KJF1uzp.d.mts +276 -0
- package/dist/aggregation-8KJF1uzp.d.mts.map +1 -0
- package/dist/aggregation-BDop87kL.mjs +1180 -0
- package/dist/aggregation-BDop87kL.mjs.map +1 -0
- package/dist/ai-runtime-CDzQztTt.mjs +85 -0
- package/dist/ai-runtime-CDzQztTt.mjs.map +1 -0
- package/dist/ai-runtime-DIwOEc6g.d.mts +56 -0
- package/dist/ai-runtime-DIwOEc6g.d.mts.map +1 -0
- package/dist/ai-sdk-error-integration-D0GDqrM0.d.mts +553 -0
- package/dist/ai-sdk-error-integration-D0GDqrM0.d.mts.map +1 -0
- package/dist/approval-queue-BcDDQ4oQ.mjs +104 -0
- package/dist/approval-queue-BcDDQ4oQ.mjs.map +1 -0
- package/dist/approval-queue-CiKiFT9z.d.mts +21 -0
- package/dist/approval-queue-CiKiFT9z.d.mts.map +1 -0
- package/dist/audio-BzvN7r10.d.mts +79 -0
- package/dist/audio-BzvN7r10.d.mts.map +1 -0
- package/dist/audio-vBG_62ME.mjs +226 -0
- package/dist/audio-vBG_62ME.mjs.map +1 -0
- package/dist/audit-logger-Bb2JIcIk.d.mts +12 -0
- package/dist/audit-logger-Bb2JIcIk.d.mts.map +1 -0
- package/dist/audit-logger-CHIP8bRO.mjs +596 -0
- package/dist/audit-logger-CHIP8bRO.mjs.map +1 -0
- package/dist/auto-resume-BpUNbPtp.d.mts +160 -0
- package/dist/auto-resume-BpUNbPtp.d.mts.map +1 -0
- package/dist/auto-resume-BuFRNvAX.mjs +638 -0
- package/dist/auto-resume-BuFRNvAX.mjs.map +1 -0
- package/dist/budget-guard-C83KCH9V.d.mts +52 -0
- package/dist/budget-guard-C83KCH9V.d.mts.map +1 -0
- package/dist/budget-guard-d_b5rq4u.mjs +158 -0
- package/dist/budget-guard-d_b5rq4u.mjs.map +1 -0
- package/dist/budget-guard-gyhJS00s.mjs +234 -0
- package/dist/budget-guard-gyhJS00s.mjs.map +1 -0
- package/dist/buffer-BC8mvXHE.d.mts +98 -0
- package/dist/buffer-BC8mvXHE.d.mts.map +1 -0
- package/dist/buffer-CefJGbRy.mjs +289 -0
- package/dist/buffer-CefJGbRy.mjs.map +1 -0
- package/dist/caching-adapters.d.mts +5 -0
- package/dist/caching-adapters.mjs +3 -0
- package/dist/caching-strategies.d.mts +52 -0
- package/dist/caching-strategies.d.mts.map +1 -0
- package/dist/caching-strategies.mjs +703 -0
- package/dist/caching-strategies.mjs.map +1 -0
- package/dist/caching.d.mts +14 -0
- package/dist/caching.d.mts.map +1 -0
- package/dist/caching.mjs +15 -0
- package/dist/caching.mjs.map +1 -0
- package/dist/catalog.d.mts +19 -0
- package/dist/catalog.d.mts.map +1 -0
- package/dist/catalog.mjs +1114 -0
- package/dist/catalog.mjs.map +1 -0
- package/dist/chunk-CkzbjWQW.mjs +20 -0
- package/dist/circuit-breaker-DoKWPORd.mjs +262 -0
- package/dist/circuit-breaker-DoKWPORd.mjs.map +1 -0
- package/dist/circuit-breaker-Mey3E7tW.d.mts +64 -0
- package/dist/circuit-breaker-Mey3E7tW.d.mts.map +1 -0
- package/dist/citation-generator-C-9RpbHq.mjs +103 -0
- package/dist/citation-generator-C-9RpbHq.mjs.map +1 -0
- package/dist/citation-generator-CDSymDs_.d.mts +18 -0
- package/dist/citation-generator-CDSymDs_.d.mts.map +1 -0
- package/dist/client-CpacYDIE.mjs +882 -0
- package/dist/client-CpacYDIE.mjs.map +1 -0
- package/dist/client.d.mts +103 -0
- package/dist/client.d.mts.map +1 -0
- package/dist/client.mjs +470 -0
- package/dist/client.mjs.map +1 -0
- package/dist/compliance-approval-queue-DQGLojAm.mjs +172 -0
- package/dist/compliance-approval-queue-DQGLojAm.mjs.map +1 -0
- package/dist/compliance-approval-queue-IrMxFfSJ.d.mts +99 -0
- package/dist/compliance-approval-queue-IrMxFfSJ.d.mts.map +1 -0
- package/dist/compliance-wrapper-CrOMHhHN.mjs +528 -0
- package/dist/compliance-wrapper-CrOMHhHN.mjs.map +1 -0
- package/dist/conditions-DmQ6Y1Wt.mjs +179 -0
- package/dist/conditions-DmQ6Y1Wt.mjs.map +1 -0
- package/dist/conditions-zDrKfrc3.d.mts +42 -0
- package/dist/conditions-zDrKfrc3.d.mts.map +1 -0
- package/dist/console-BGMxxPZN.mjs +181 -0
- package/dist/console-BGMxxPZN.mjs.map +1 -0
- package/dist/console-DqEqZd4A.d.mts +76 -0
- package/dist/console-DqEqZd4A.d.mts.map +1 -0
- package/dist/controller-BOy3-xbC.mjs +501 -0
- package/dist/controller-BOy3-xbC.mjs.map +1 -0
- package/dist/controller-Y0NGosbJ.d.mts +104 -0
- package/dist/controller-Y0NGosbJ.d.mts.map +1 -0
- package/dist/coordinator-agent-BglqZLwo.d.mts +54 -0
- package/dist/coordinator-agent-BglqZLwo.d.mts.map +1 -0
- package/dist/coordinator-agent-WFWBRL-G.mjs +236 -0
- package/dist/coordinator-agent-WFWBRL-G.mjs.map +1 -0
- package/dist/crypto-8ABhc3TD.mjs +40 -0
- package/dist/crypto-8ABhc3TD.mjs.map +1 -0
- package/dist/environment-CSoJb0SW.mjs +255 -0
- package/dist/environment-CSoJb0SW.mjs.map +1 -0
- package/dist/error-handling-DNVkm6RY.mjs +1334 -0
- package/dist/error-handling-DNVkm6RY.mjs.map +1 -0
- package/dist/errors-CQ8tF4dP.mjs +985 -0
- package/dist/errors-CQ8tF4dP.mjs.map +1 -0
- package/dist/errors-CfYdVeum.d.mts +212 -0
- package/dist/errors-CfYdVeum.d.mts.map +1 -0
- package/dist/errors-Dtn-UeRi.mjs +61 -0
- package/dist/errors-Dtn-UeRi.mjs.map +1 -0
- package/dist/evaluator-Cs84qkr8.mjs +91 -0
- package/dist/evaluator-Cs84qkr8.mjs.map +1 -0
- package/dist/evaluator-optimizer-De67_mJC.mjs +1086 -0
- package/dist/evaluator-optimizer-De67_mJC.mjs.map +1 -0
- package/dist/evaluator-optimizer-pattern-B5939s2Z.mjs +367 -0
- package/dist/evaluator-optimizer-pattern-B5939s2Z.mjs.map +1 -0
- package/dist/evaluator-optimizer-pattern-D1AJrzBD.d.mts +72 -0
- package/dist/evaluator-optimizer-pattern-D1AJrzBD.d.mts.map +1 -0
- package/dist/factory-DP6VSl8C.mjs +307 -0
- package/dist/factory-DP6VSl8C.mjs.map +1 -0
- package/dist/generative-ui-catalog.d.mts +8 -0
- package/dist/generative-ui-catalog.d.mts.map +1 -0
- package/dist/generative-ui-catalog.mjs +679 -0
- package/dist/generative-ui-catalog.mjs.map +1 -0
- package/dist/generative-ui-registry.d.mts +195 -0
- package/dist/generative-ui-registry.d.mts.map +1 -0
- package/dist/generative-ui-registry.mjs +250 -0
- package/dist/generative-ui-registry.mjs.map +1 -0
- package/dist/generative-ui-stream.d.mts +23 -0
- package/dist/generative-ui-stream.d.mts.map +1 -0
- package/dist/generative-ui-stream.mjs +219 -0
- package/dist/generative-ui-stream.mjs.map +1 -0
- package/dist/generative-ui-types.d.mts +123 -0
- package/dist/generative-ui-types.d.mts.map +1 -0
- package/dist/generative-ui-types.mjs +1 -0
- package/dist/generative-ui.d.mts +13 -0
- package/dist/generative-ui.d.mts.map +1 -0
- package/dist/generative-ui.mjs +21 -0
- package/dist/generative-ui.mjs.map +1 -0
- package/dist/governance-audit.d.mts +3 -0
- package/dist/governance-audit.mjs +3 -0
- package/dist/governance-compliance.d.mts +5 -0
- package/dist/governance-compliance.mjs +4 -0
- package/dist/governance-policies.d.mts +4 -0
- package/dist/governance-policies.mjs +4 -0
- package/dist/governance-tenancy.d.mts +3 -0
- package/dist/governance-tenancy.mjs +3 -0
- package/dist/governance.d.mts +88 -0
- package/dist/governance.d.mts.map +1 -0
- package/dist/governance.mjs +432 -0
- package/dist/governance.mjs.map +1 -0
- package/dist/grounding-attribution.d.mts +63 -0
- package/dist/grounding-attribution.d.mts.map +1 -0
- package/dist/grounding-attribution.mjs +259 -0
- package/dist/grounding-attribution.mjs.map +1 -0
- package/dist/grounding-citation.d.mts +2 -0
- package/dist/grounding-citation.mjs +3 -0
- package/dist/grounding-context.d.mts +9 -0
- package/dist/grounding-context.d.mts.map +1 -0
- package/dist/grounding-context.mjs +19 -0
- package/dist/grounding-context.mjs.map +1 -0
- package/dist/grounding-embed.d.mts +102 -0
- package/dist/grounding-embed.d.mts.map +1 -0
- package/dist/grounding-embed.mjs +417 -0
- package/dist/grounding-embed.mjs.map +1 -0
- package/dist/grounding-hallucination.d.mts +44 -0
- package/dist/grounding-hallucination.d.mts.map +1 -0
- package/dist/grounding-hallucination.mjs +115 -0
- package/dist/grounding-hallucination.mjs.map +1 -0
- package/dist/grounding-proof-map.d.mts +9 -0
- package/dist/grounding-proof-map.d.mts.map +1 -0
- package/dist/grounding-proof-map.mjs +26 -0
- package/dist/grounding-proof-map.mjs.map +1 -0
- package/dist/grounding-rag.d.mts +10 -0
- package/dist/grounding-rag.d.mts.map +1 -0
- package/dist/grounding-rag.mjs +27 -0
- package/dist/grounding-rag.mjs.map +1 -0
- package/dist/grounding-verification.d.mts +48 -0
- package/dist/grounding-verification.d.mts.map +1 -0
- package/dist/grounding-verification.mjs +224 -0
- package/dist/grounding-verification.mjs.map +1 -0
- package/dist/grounding.d.mts +24 -0
- package/dist/grounding.d.mts.map +1 -0
- package/dist/grounding.mjs +77 -0
- package/dist/grounding.mjs.map +1 -0
- package/dist/hitl-active-learning.d.mts +41 -0
- package/dist/hitl-active-learning.d.mts.map +1 -0
- package/dist/hitl-active-learning.mjs +178 -0
- package/dist/hitl-active-learning.mjs.map +1 -0
- package/dist/hitl-annotation.d.mts +74 -0
- package/dist/hitl-annotation.d.mts.map +1 -0
- package/dist/hitl-annotation.mjs +170 -0
- package/dist/hitl-annotation.mjs.map +1 -0
- package/dist/hitl-approval.d.mts +2 -0
- package/dist/hitl-approval.mjs +3 -0
- package/dist/hitl-feedback.d.mts +59 -0
- package/dist/hitl-feedback.d.mts.map +1 -0
- package/dist/hitl-feedback.mjs +137 -0
- package/dist/hitl-feedback.mjs.map +1 -0
- package/dist/hitl-review.d.mts +2 -0
- package/dist/hitl-review.mjs +3 -0
- package/dist/hitl.d.mts +14 -0
- package/dist/hitl.d.mts.map +1 -0
- package/dist/hitl.mjs +22 -0
- package/dist/hitl.mjs.map +1 -0
- package/dist/index-B17HT-VL.d.mts +285 -0
- package/dist/index-B17HT-VL.d.mts.map +1 -0
- package/dist/index-BDwgsK9B.d.mts +101 -0
- package/dist/index-BDwgsK9B.d.mts.map +1 -0
- package/dist/index-BGgMn_Ev.d.mts +2615 -0
- package/dist/index-BGgMn_Ev.d.mts.map +1 -0
- package/dist/index-DOqe5r9G.d.mts +318 -0
- package/dist/index-DOqe5r9G.d.mts.map +1 -0
- package/dist/index-DotINT7o.d.mts +1004 -0
- package/dist/index-DotINT7o.d.mts.map +1 -0
- package/dist/index-URlW7aD1.d.mts +67 -0
- package/dist/index-URlW7aD1.d.mts.map +1 -0
- package/dist/index.d.mts +64 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +46 -0
- package/dist/index.mjs.map +1 -0
- package/dist/integrations-blob-storage.d.mts +25 -0
- package/dist/integrations-blob-storage.d.mts.map +1 -0
- package/dist/integrations-blob-storage.mjs +3 -0
- package/dist/integrations-notifications.d.mts +2 -0
- package/dist/integrations-notifications.mjs +3 -0
- package/dist/integrations-rate-limit.d.mts +27 -0
- package/dist/integrations-rate-limit.d.mts.map +1 -0
- package/dist/integrations-rate-limit.mjs +30 -0
- package/dist/integrations-rate-limit.mjs.map +1 -0
- package/dist/integrations-redis.d.mts +3 -0
- package/dist/integrations-redis.mjs +3 -0
- package/dist/integrations-stream.d.mts +14 -0
- package/dist/integrations-stream.d.mts.map +1 -0
- package/dist/integrations-stream.mjs +3 -0
- package/dist/integrations.d.mts +7 -0
- package/dist/integrations.mjs +7 -0
- package/dist/log-adapter-BLegSZtz.d.mts +16 -0
- package/dist/log-adapter-BLegSZtz.d.mts.map +1 -0
- package/dist/log-adapter-PPe_2Pwv.mjs +28 -0
- package/dist/log-adapter-PPe_2Pwv.mjs.map +1 -0
- package/dist/loop-BOYEtr2g.mjs +520 -0
- package/dist/loop-BOYEtr2g.mjs.map +1 -0
- package/dist/loop-C-tBBOqi.d.mts +219 -0
- package/dist/loop-C-tBBOqi.d.mts.map +1 -0
- package/dist/middleware-5wQ9bANW.mjs +306 -0
- package/dist/middleware-5wQ9bANW.mjs.map +1 -0
- package/dist/middleware-C1apSrj0.mjs +613 -0
- package/dist/middleware-C1apSrj0.mjs.map +1 -0
- package/dist/middleware-C7k0uItW.d.mts +9 -0
- package/dist/middleware-C7k0uItW.d.mts.map +1 -0
- package/dist/middleware-CZQCTHfl.mjs +366 -0
- package/dist/middleware-CZQCTHfl.mjs.map +1 -0
- package/dist/models.d.mts +11 -0
- package/dist/models.d.mts.map +1 -0
- package/dist/models.mjs +32 -0
- package/dist/models.mjs.map +1 -0
- package/dist/observability-analytics.d.mts +107 -0
- package/dist/observability-analytics.d.mts.map +1 -0
- package/dist/observability-analytics.mjs +409 -0
- package/dist/observability-analytics.mjs.map +1 -0
- package/dist/observability-cost.d.mts +10 -0
- package/dist/observability-cost.d.mts.map +1 -0
- package/dist/observability-cost.mjs +15 -0
- package/dist/observability-cost.mjs.map +1 -0
- package/dist/observability-telemetry.d.mts +111 -0
- package/dist/observability-telemetry.d.mts.map +1 -0
- package/dist/observability-telemetry.mjs +343 -0
- package/dist/observability-telemetry.mjs.map +1 -0
- package/dist/observability-tracing.d.mts +10 -0
- package/dist/observability-tracing.d.mts.map +1 -0
- package/dist/observability-tracing.mjs +17 -0
- package/dist/observability-tracing.mjs.map +1 -0
- package/dist/observability.d.mts +15 -0
- package/dist/observability.d.mts.map +1 -0
- package/dist/observability.mjs +17 -0
- package/dist/observability.mjs.map +1 -0
- package/dist/optimizer-DhXXpci6.mjs +97 -0
- package/dist/optimizer-DhXXpci6.mjs.map +1 -0
- package/dist/output-multimodal.d.mts +9 -0
- package/dist/output-multimodal.d.mts.map +1 -0
- package/dist/output-multimodal.mjs +18 -0
- package/dist/output-multimodal.mjs.map +1 -0
- package/dist/output.d.mts +11 -0
- package/dist/output.d.mts.map +1 -0
- package/dist/output.mjs +40 -0
- package/dist/output.mjs.map +1 -0
- package/dist/pii-filter-3AxmYSiu.d.mts +23 -0
- package/dist/pii-filter-3AxmYSiu.d.mts.map +1 -0
- package/dist/pipelines.d.mts +448 -0
- package/dist/pipelines.d.mts.map +1 -0
- package/dist/pipelines.mjs +1534 -0
- package/dist/pipelines.mjs.map +1 -0
- package/dist/prompt-injection-DQXchzsV.d.mts +8 -0
- package/dist/prompt-injection-DQXchzsV.d.mts.map +1 -0
- package/dist/prompt-injection-RpoLPwSa.mjs +52 -0
- package/dist/prompt-injection-RpoLPwSa.mjs.map +1 -0
- package/dist/prompts.d.mts +192 -0
- package/dist/prompts.d.mts.map +1 -0
- package/dist/prompts.mjs +732 -0
- package/dist/prompts.mjs.map +1 -0
- package/dist/protocol-DfBiEsnl.d.mts +112 -0
- package/dist/protocol-DfBiEsnl.d.mts.map +1 -0
- package/dist/quota-manager-0iPMkQWN.d.mts +62 -0
- package/dist/quota-manager-0iPMkQWN.d.mts.map +1 -0
- package/dist/quota-manager-D_N7FuQ2.mjs +180 -0
- package/dist/quota-manager-D_N7FuQ2.mjs.map +1 -0
- package/dist/redaction-utils-DcQwsiNh.mjs +438 -0
- package/dist/redaction-utils-DcQwsiNh.mjs.map +1 -0
- package/dist/redis-CpsSrF8K.mjs +102 -0
- package/dist/redis-CpsSrF8K.mjs.map +1 -0
- package/dist/redis-CwguYFGh.d.mts +33 -0
- package/dist/redis-CwguYFGh.d.mts.map +1 -0
- package/dist/registry-CsD3iTIx.mjs +190 -0
- package/dist/registry-CsD3iTIx.mjs.map +1 -0
- package/dist/registry-DVPWzkXR.d.mts +36 -0
- package/dist/registry-DVPWzkXR.d.mts.map +1 -0
- package/dist/reranking-BpWYhYzl.d.mts +72 -0
- package/dist/reranking-BpWYhYzl.d.mts.map +1 -0
- package/dist/reranking-Ck8aKZW7.mjs +331 -0
- package/dist/reranking-Ck8aKZW7.mjs.map +1 -0
- package/dist/resumable-adapter-CO1HtsgJ.mjs +21 -0
- package/dist/resumable-adapter-CO1HtsgJ.mjs.map +1 -0
- package/dist/review-trigger-DmAsiQlM.d.mts +24 -0
- package/dist/review-trigger-DmAsiQlM.d.mts.map +1 -0
- package/dist/review-trigger-DwXfpww9.mjs +112 -0
- package/dist/review-trigger-DwXfpww9.mjs.map +1 -0
- package/dist/safe-context-BynhkTKR.d.mts +54 -0
- package/dist/safe-context-BynhkTKR.d.mts.map +1 -0
- package/dist/safe-context-C5A3Wv3b.mjs +143 -0
- package/dist/safe-context-C5A3Wv3b.mjs.map +1 -0
- package/dist/schema-Bu2noOZ4.mjs +27 -0
- package/dist/schema-Bu2noOZ4.mjs.map +1 -0
- package/dist/schema-CwFvuCnA.mjs +97 -0
- package/dist/schema-CwFvuCnA.mjs.map +1 -0
- package/dist/schema-Wz-1-ro9.d.mts +37 -0
- package/dist/schema-Wz-1-ro9.d.mts.map +1 -0
- package/dist/schemas-CxQtxIga.mjs +62 -0
- package/dist/schemas-CxQtxIga.mjs.map +1 -0
- package/dist/schemas-DBOhxgW7.d.mts +32 -0
- package/dist/schemas-DBOhxgW7.d.mts.map +1 -0
- package/dist/schemas-Dp_OCqBt.d.mts +63 -0
- package/dist/schemas-Dp_OCqBt.d.mts.map +1 -0
- package/dist/schemas-SwCsnT0z.mjs +83 -0
- package/dist/schemas-SwCsnT0z.mjs.map +1 -0
- package/dist/sdk-errors.d.mts +2 -0
- package/dist/sdk-errors.mjs +3 -0
- package/dist/sdk-experimental.d.mts +59 -0
- package/dist/sdk-experimental.d.mts.map +1 -0
- package/dist/sdk-experimental.mjs +193 -0
- package/dist/sdk-experimental.mjs.map +1 -0
- package/dist/sdk-stop-conditions.d.mts +3 -0
- package/dist/sdk-stop-conditions.mjs +3 -0
- package/dist/sdk.d.mts +15 -0
- package/dist/sdk.d.mts.map +1 -0
- package/dist/sdk.mjs +50 -0
- package/dist/sdk.mjs.map +1 -0
- package/dist/security-guardrails.d.mts +3 -0
- package/dist/security-guardrails.mjs +3 -0
- package/dist/security-injection.d.mts +2 -0
- package/dist/security-injection.mjs +3 -0
- package/dist/security.d.mts +12 -0
- package/dist/security.d.mts.map +1 -0
- package/dist/security.mjs +18 -0
- package/dist/security.mjs.map +1 -0
- package/dist/server.d.mts +420 -0
- package/dist/server.d.mts.map +1 -0
- package/dist/server.mjs +2225 -0
- package/dist/server.mjs.map +1 -0
- package/dist/shared.d.mts +2 -0
- package/dist/shared.mjs +3 -0
- package/dist/streaming-control.d.mts +2 -0
- package/dist/streaming-control.mjs +4 -0
- package/dist/streaming-core.d.mts +4 -0
- package/dist/streaming-core.mjs +3 -0
- package/dist/streaming-infra-resilience.d.mts +120 -0
- package/dist/streaming-infra-resilience.d.mts.map +1 -0
- package/dist/streaming-infra-resilience.mjs +358 -0
- package/dist/streaming-infra-resilience.mjs.map +1 -0
- package/dist/streaming-infra-transport.d.mts +57 -0
- package/dist/streaming-infra-transport.d.mts.map +1 -0
- package/dist/streaming-infra-transport.mjs +488 -0
- package/dist/streaming-infra-transport.mjs.map +1 -0
- package/dist/streaming-infra.d.mts +5 -0
- package/dist/streaming-infra.mjs +5 -0
- package/dist/streaming.d.mts +17 -0
- package/dist/streaming.d.mts.map +1 -0
- package/dist/streaming.mjs +71 -0
- package/dist/streaming.mjs.map +1 -0
- package/dist/telemetry-2eKMojIb.mjs +1046 -0
- package/dist/telemetry-2eKMojIb.mjs.map +1 -0
- package/dist/telemetry-C2t03dwD.d.mts +59 -0
- package/dist/telemetry-C2t03dwD.d.mts.map +1 -0
- package/dist/tool-Btbththq.d.mts +253 -0
- package/dist/tool-Btbththq.d.mts.map +1 -0
- package/dist/tool-JSf8JXZ8.mjs +1150 -0
- package/dist/tool-JSf8JXZ8.mjs.map +1 -0
- package/dist/tool-safety-CZO8a4D4.d.mts +60 -0
- package/dist/tool-safety-CZO8a4D4.d.mts.map +1 -0
- package/dist/tool-safety-DXtYDXod.mjs +319 -0
- package/dist/tool-safety-DXtYDXod.mjs.map +1 -0
- package/dist/tools-BuS2Uv0q.mjs +1708 -0
- package/dist/tools-BuS2Uv0q.mjs.map +1 -0
- package/dist/tools-approval.d.mts +99 -0
- package/dist/tools-approval.d.mts.map +1 -0
- package/dist/tools-approval.mjs +395 -0
- package/dist/tools-approval.mjs.map +1 -0
- package/dist/tools-compliance.d.mts +67 -0
- package/dist/tools-compliance.d.mts.map +1 -0
- package/dist/tools-compliance.mjs +330 -0
- package/dist/tools-compliance.mjs.map +1 -0
- package/dist/tools-computer.d.mts +25 -0
- package/dist/tools-computer.d.mts.map +1 -0
- package/dist/tools-computer.mjs +64 -0
- package/dist/tools-computer.mjs.map +1 -0
- package/dist/tools-core.d.mts +3 -0
- package/dist/tools-core.mjs +3 -0
- package/dist/tools-mcp.d.mts +3 -0
- package/dist/tools-mcp.mjs +5 -0
- package/dist/tools-superpowers.d.mts +2 -0
- package/dist/tools-superpowers.mjs +3 -0
- package/dist/tools.d.mts +401 -0
- package/dist/tools.d.mts.map +1 -0
- package/dist/tools.mjs +1921 -0
- package/dist/tools.mjs.map +1 -0
- package/dist/transport-selector-D-Ib05X1.mjs +1936 -0
- package/dist/transport-selector-D-Ib05X1.mjs.map +1 -0
- package/dist/triage-agent-BEsXg5sw.d.mts +63 -0
- package/dist/triage-agent-BEsXg5sw.d.mts.map +1 -0
- package/dist/triage-agent-CBsfX-HW.mjs +167 -0
- package/dist/triage-agent-CBsfX-HW.mjs.map +1 -0
- package/dist/types-BPnq3GQo.d.mts +23 -0
- package/dist/types-BPnq3GQo.d.mts.map +1 -0
- package/dist/types-BjWgimpY.d.mts +16 -0
- package/dist/types-BjWgimpY.d.mts.map +1 -0
- package/dist/types-BxD-5btB.d.mts +41 -0
- package/dist/types-BxD-5btB.d.mts.map +1 -0
- package/dist/types-By-r93bE.d.mts +36 -0
- package/dist/types-By-r93bE.d.mts.map +1 -0
- package/dist/types-CLBWFRZN.d.mts +69 -0
- package/dist/types-CLBWFRZN.d.mts.map +1 -0
- package/dist/types-CQ0HFd0u.d.mts +62 -0
- package/dist/types-CQ0HFd0u.d.mts.map +1 -0
- package/dist/types-D3zJb59_.d.mts +47 -0
- package/dist/types-D3zJb59_.d.mts.map +1 -0
- package/dist/types-DJnugQX0.d.mts +80 -0
- package/dist/types-DJnugQX0.d.mts.map +1 -0
- package/dist/types-DbUfMCnT.d.mts +70 -0
- package/dist/types-DbUfMCnT.d.mts.map +1 -0
- package/dist/upstash-adapter-D96Caq2O.mjs +22 -0
- package/dist/upstash-adapter-D96Caq2O.mjs.map +1 -0
- package/dist/upstash-adapter-DD4433dx.d.mts +8 -0
- package/dist/upstash-adapter-DD4433dx.d.mts.map +1 -0
- package/dist/utils-BlYhcD6M.mjs +319 -0
- package/dist/utils-BlYhcD6M.mjs.map +1 -0
- package/dist/utils-DpJGOb3y.d.mts +120 -0
- package/dist/utils-DpJGOb3y.d.mts.map +1 -0
- package/dist/vercel-blob-adapter-CkOXLT2D.mjs +25 -0
- package/dist/vercel-blob-adapter-CkOXLT2D.mjs.map +1 -0
- package/dist/xai-CbV_dCnP.mjs +1600 -0
- package/dist/xai-CbV_dCnP.mjs.map +1 -0
- package/package.json +479 -0
- package/src/agents/base/factory.ts +382 -0
- package/src/agents/base/index.ts +8 -0
- package/src/agents/base/schemas.ts +117 -0
- package/src/agents/base/types.ts +192 -0
- package/src/agents/control-flow/index.ts +683 -0
- package/src/agents/coordinator/coordinator-agent.ts +381 -0
- package/src/agents/coordinator/index.ts +6 -0
- package/src/agents/default-agent.ts +211 -0
- package/src/agents/evaluator-optimizer/README.md +612 -0
- package/src/agents/evaluator-optimizer/evaluator-optimizer.example.ts +437 -0
- package/src/agents/evaluator-optimizer/evaluator.ts +282 -0
- package/src/agents/evaluator-optimizer/index.test.ts +416 -0
- package/src/agents/evaluator-optimizer/index.ts +519 -0
- package/src/agents/evaluator-optimizer/optimizer.ts +322 -0
- package/src/agents/evaluator-optimizer/schema.ts +302 -0
- package/src/agents/evaluator-optimizer/utils.ts +42 -0
- package/src/agents/experimental/index.ts +1095 -0
- package/src/agents/experimental/types.ts +212 -0
- package/src/agents/fallback/index.ts +18 -0
- package/src/agents/fallback/recovery/circuit-breaker.ts +166 -0
- package/src/agents/fallback/strategies/model-fallback.ts +192 -0
- package/src/agents/fallback/types.ts +87 -0
- package/src/agents/governance-agent.ts +446 -0
- package/src/agents/index.ts +79 -0
- package/src/agents/multi/coordination/index.ts +6 -0
- package/src/agents/multi/coordination/message-bus.ts +144 -0
- package/src/agents/multi/index.ts +6 -0
- package/src/agents/multi/state/index.ts +162 -0
- package/src/agents/multi/supervisor/index.ts +7 -0
- package/src/agents/multi/supervisor/supervisor.ts +254 -0
- package/src/agents/multi/swarm/aggregation.ts +466 -0
- package/src/agents/multi/swarm/communication.ts +388 -0
- package/src/agents/multi/swarm/coordination.ts +380 -0
- package/src/agents/multi/swarm/index.ts +73 -0
- package/src/agents/multi/swarm/swarm-executor.ts +479 -0
- package/src/agents/multi/types.ts +181 -0
- package/src/agents/observability/index.ts +914 -0
- package/src/agents/orchestrator.ts +218 -0
- package/src/agents/patterns/README.md +512 -0
- package/src/agents/patterns/evaluator-optimizer-pattern.example.ts +455 -0
- package/src/agents/patterns/evaluator-optimizer-pattern.ts +653 -0
- package/src/agents/patterns/index.ts +26 -0
- package/src/agents/persistence/index.ts +726 -0
- package/src/agents/tools/index.ts +291 -0
- package/src/agents/tools/mcp.ts +188 -0
- package/src/agents/triage/index.ts +6 -0
- package/src/agents/triage/triage-agent.ts +280 -0
- package/src/agents/workflows/index.ts +6 -0
- package/src/agents/workflows/interfaces.ts +36 -0
- package/src/agents/workflows/schema.ts +20 -0
- package/src/caching/adapters/index.ts +7 -0
- package/src/caching/adapters/memory.ts +77 -0
- package/src/caching/adapters/redis.ts +60 -0
- package/src/caching/index.ts +17 -0
- package/src/caching/middleware.ts +452 -0
- package/src/caching/strategies/index.ts +1008 -0
- package/src/caching/types.ts +47 -0
- package/src/catalog.ts +921 -0
- package/src/client/chat-usage.ts +53 -0
- package/src/client/hooks.ts +343 -0
- package/src/client/index.ts +36 -0
- package/src/client/message-utils.ts +29 -0
- package/src/client/use-generative-ui.ts +174 -0
- package/src/client/utils.ts +66 -0
- package/src/generative-ui/catalog.ts +653 -0
- package/src/generative-ui/index.ts +82 -0
- package/src/generative-ui/registry.ts +273 -0
- package/src/generative-ui/stream.ts +324 -0
- package/src/generative-ui/types.ts +376 -0
- package/src/governance/audit/audit-logger.ts +239 -0
- package/src/governance/audit/audit-schema.ts +82 -0
- package/src/governance/audit/index.ts +6 -0
- package/src/governance/compliance/abac/policy-engine.ts +175 -0
- package/src/governance/compliance/abac/types.ts +40 -0
- package/src/governance/compliance/approval/compliance-approval-queue.ts +217 -0
- package/src/governance/compliance/index.ts +16 -0
- package/src/governance/compliance/schemas.ts +68 -0
- package/src/governance/compliance/types.ts +143 -0
- package/src/governance/compliance/validators/phi-detector.ts +145 -0
- package/src/governance/compliance/validators/redaction-utils.ts +176 -0
- package/src/governance/compliance/validators/safe-harbor.ts +135 -0
- package/src/governance/entitlements/index.ts +585 -0
- package/src/governance/entitlements/middleware.ts +651 -0
- package/src/governance/entitlements/rate-limiter.ts +711 -0
- package/src/governance/index.ts +32 -0
- package/src/governance/policies/guardrails.ts +1121 -0
- package/src/governance/policies/index.ts +42 -0
- package/src/governance/policies/loop-controls.ts +136 -0
- package/src/governance/policies/telemetry.ts +63 -0
- package/src/governance/tenancy/index.ts +30 -0
- package/src/governance/tenancy/isolation/context.ts +92 -0
- package/src/governance/tenancy/isolation/index.ts +13 -0
- package/src/governance/tenancy/quotas/index.ts +11 -0
- package/src/governance/tenancy/quotas/quota-manager.ts +180 -0
- package/src/governance/tenancy/types.ts +66 -0
- package/src/governance/types.ts +16 -0
- package/src/governance/versioning/index.ts +573 -0
- package/src/grounding/attribution/index.ts +424 -0
- package/src/grounding/citation/citation-generator.ts +174 -0
- package/src/grounding/citation/index.ts +12 -0
- package/src/grounding/context/index.ts +32 -0
- package/src/grounding/context/safe-context.ts +116 -0
- package/src/grounding/context/types.ts +62 -0
- package/src/grounding/context-engineering/error-handling.ts +359 -0
- package/src/grounding/context-engineering/index.ts +23 -0
- package/src/grounding/context-engineering/memory.ts +559 -0
- package/src/grounding/context-engineering/tool-masking.ts +338 -0
- package/src/grounding/embed/index.ts +704 -0
- package/src/grounding/embed/reranking.ts +604 -0
- package/src/grounding/hallucination/index.ts +223 -0
- package/src/grounding/index.ts +82 -0
- package/src/grounding/proof-map/applyPatch.ts +172 -0
- package/src/grounding/proof-map/index.ts +41 -0
- package/src/grounding/proof-map/loop.ts +275 -0
- package/src/grounding/proof-map/schema.ts +217 -0
- package/src/grounding/rag/__tests__/pipeline.test.ts +274 -0
- package/src/grounding/rag/__tests__/tool.test.ts +202 -0
- package/src/grounding/rag/__tests__/trace.test.ts +229 -0
- package/src/grounding/rag/circuit-breaker.ts +152 -0
- package/src/grounding/rag/index.ts +64 -0
- package/src/grounding/rag/pipeline.ts +602 -0
- package/src/grounding/rag/tool.ts +281 -0
- package/src/grounding/rag/trace.ts +503 -0
- package/src/grounding/rag/types.ts +284 -0
- package/src/grounding/retrieval/in-memory-store.ts +107 -0
- package/src/grounding/sources/index.ts +943 -0
- package/src/grounding/tests/applyPatch.test.ts +194 -0
- package/src/grounding/tests/loop.test.ts +141 -0
- package/src/grounding/tests/schema.test.ts +160 -0
- package/src/grounding/types.ts +100 -0
- package/src/grounding/verification/index.ts +419 -0
- package/src/hitl/active-learning/index.ts +332 -0
- package/src/hitl/annotation/index.ts +362 -0
- package/src/hitl/approval/approval-queue.ts +132 -0
- package/src/hitl/approval/index.ts +5 -0
- package/src/hitl/feedback/index.ts +284 -0
- package/src/hitl/index.ts +69 -0
- package/src/hitl/review/index.ts +6 -0
- package/src/hitl/review/review-trigger.ts +162 -0
- package/src/hitl/types.ts +126 -0
- package/src/index.ts +125 -0
- package/src/integrations/blob-storage/index.ts +7 -0
- package/src/integrations/blob-storage/types.ts +28 -0
- package/src/integrations/blob-storage/vercel-blob-adapter.ts +35 -0
- package/src/integrations/index.ts +15 -0
- package/src/integrations/notifications/index.ts +7 -0
- package/src/integrations/notifications/log-adapter.ts +30 -0
- package/src/integrations/notifications/types.ts +27 -0
- package/src/integrations/rate-limit/index.ts +7 -0
- package/src/integrations/rate-limit/types.ts +26 -0
- package/src/integrations/rate-limit/upstash-adapter.ts +45 -0
- package/src/integrations/redis/index.ts +7 -0
- package/src/integrations/redis/types.ts +67 -0
- package/src/integrations/redis/upstash-adapter.ts +18 -0
- package/src/integrations/stream/index.ts +7 -0
- package/src/integrations/stream/resumable-adapter.ts +20 -0
- package/src/integrations/stream/types.ts +21 -0
- package/src/internal/__tests__/hallucination.test.ts +162 -0
- package/src/internal/__tests__/models.test.ts +104 -0
- package/src/internal/__tests__/sdk-errors.test.ts +201 -0
- package/src/internal/__tests__/stop-conditions.test.ts +210 -0
- package/src/internal/shared/ai-types.ts +942 -0
- package/src/internal/testing/evaluators.ts +575 -0
- package/src/internal/testing/index.ts +960 -0
- package/src/internal/ui/data-parts.ts +511 -0
- package/src/internal/ui/type-guards.ts +344 -0
- package/src/internal/ui-factories/__tests__/ui-factories.test.ts +548 -0
- package/src/internal/ui-factories/artifact-factory.ts +667 -0
- package/src/internal/ui-factories/index.ts +82 -0
- package/src/internal/ui-factories/shimmer-manager.ts +220 -0
- package/src/internal/ui-factories/status-helpers.ts +149 -0
- package/src/internal/ui-factories/tool-renderer.ts +167 -0
- package/src/internal/ui-factories/types.ts +235 -0
- package/src/models/capabilities.ts +88 -0
- package/src/models/index.ts +16 -0
- package/src/models/provider-factory.ts +229 -0
- package/src/models/providers/anthropic.ts +539 -0
- package/src/models/providers/google.ts +354 -0
- package/src/models/providers/index.ts +21 -0
- package/src/models/providers/openai.ts +346 -0
- package/src/models/providers/perplexity.ts +276 -0
- package/src/models/providers/shared.ts +90 -0
- package/src/models/providers/xai.ts +269 -0
- package/src/models/registry.ts +208 -0
- package/src/models/routing/index.ts +45 -0
- package/src/models/routing/intent-router.ts +143 -0
- package/src/models/routing/model-router.ts +300 -0
- package/src/models/routing/types.ts +106 -0
- package/src/models/types.ts +23 -0
- package/src/observability/analytics/index.ts +593 -0
- package/src/observability/cost/index.ts +16 -0
- package/src/observability/cost/tracking/budget-guard.ts +110 -0
- package/src/observability/cost/tracking/usage-tracker.ts +120 -0
- package/src/observability/cost/types.ts +85 -0
- package/src/observability/index.ts +17 -0
- package/src/observability/telemetry/index.ts +508 -0
- package/src/observability/tracing/index.ts +30 -0
- package/src/observability/tracing/otel/ai-instrumentation.ts +193 -0
- package/src/observability/tracing/otel/exporters/console.ts +58 -0
- package/src/observability/tracing/otel/exporters/index.ts +6 -0
- package/src/observability/tracing/provenance.ts +769 -0
- package/src/observability/tracing/types.ts +92 -0
- package/src/output/__tests__/output.test.ts +737 -0
- package/src/output/element-stream.ts +678 -0
- package/src/output/errors.ts +108 -0
- package/src/output/factories.ts +392 -0
- package/src/output/index.ts +98 -0
- package/src/output/multimodal/EXPORTS.md +306 -0
- package/src/output/multimodal/IMPLEMENTATION_SUMMARY.md +421 -0
- package/src/output/multimodal/README.md +349 -0
- package/src/output/multimodal/SETUP_GUIDE.md +472 -0
- package/src/output/multimodal/audio.ts +650 -0
- package/src/output/multimodal/image.ts +22 -0
- package/src/output/multimodal/index.ts +32 -0
- package/src/output/multimodal/providers.example.ts +375 -0
- package/src/output/validator.ts +495 -0
- package/src/pipelines/adapters/trace-storage-blob.ts +458 -0
- package/src/pipelines/adapters/trace-storage-memory.ts +319 -0
- package/src/pipelines/defaults.ts +109 -0
- package/src/pipelines/index.ts +24 -0
- package/src/pipelines/message-transforms.ts +107 -0
- package/src/pipelines/multi-step-wrapper.ts +433 -0
- package/src/pipelines/pipeline-presets.ts +339 -0
- package/src/pipelines/step-executor.ts +257 -0
- package/src/pipelines/storage-factory.ts +85 -0
- package/src/pipelines/trace-storage-interface.ts +216 -0
- package/src/pipelines/types.ts +255 -0
- package/src/pipelines/validation.ts +323 -0
- package/src/prompts/index.ts +271 -0
- package/src/prompts/model-variants.ts +410 -0
- package/src/prompts/templates.ts +327 -0
- package/src/sdk/errors/base.ts +296 -0
- package/src/sdk/errors/index.ts +31 -0
- package/src/sdk/errors/utils.ts +148 -0
- package/src/sdk/experimental/index.ts +286 -0
- package/src/sdk/index.ts +25 -0
- package/src/sdk/middleware/ai-middleware.ts +95 -0
- package/src/sdk/middleware/cache.ts +154 -0
- package/src/sdk/middleware/circuit-breaker.ts +388 -0
- package/src/sdk/middleware/compose.ts +81 -0
- package/src/sdk/middleware/deduplication.ts +307 -0
- package/src/sdk/middleware/index.ts +660 -0
- package/src/sdk/middleware/model-middleware.ts +200 -0
- package/src/sdk/stop-conditions/conditions.ts +209 -0
- package/src/sdk/stop-conditions/index.ts +35 -0
- package/src/sdk/stop-conditions/types.ts +59 -0
- package/src/security/guardrails/index.ts +6 -0
- package/src/security/guardrails/middleware.ts +465 -0
- package/src/security/guardrails/pii-filter.ts +396 -0
- package/src/security/index.ts +33 -0
- package/src/security/injection/index.ts +5 -0
- package/src/security/injection/prompt-injection.ts +64 -0
- package/src/security/types.ts +85 -0
- package/src/server/cache/crypto.ts +47 -0
- package/src/server/cache/performance.ts +79 -0
- package/src/server/error-handler.ts +93 -0
- package/src/server/errors.ts +73 -0
- package/src/server/helpers.ts +944 -0
- package/src/server/http.ts +156 -0
- package/src/server/index.ts +12 -0
- package/src/server/messages/__tests__/messages.test.ts +720 -0
- package/src/server/messages/converter.ts +245 -0
- package/src/server/messages/data-parts.ts +338 -0
- package/src/server/messages/extraction.ts +328 -0
- package/src/server/messages/index.ts +126 -0
- package/src/server/messages/types.ts +355 -0
- package/src/server/messages/window.ts +450 -0
- package/src/server/rate-limit/env.ts +8 -0
- package/src/server/rate-limit/rate-limit.ts +165 -0
- package/src/server/routes/HEALTH_CHECK.md +502 -0
- package/src/server/routes/IMPLEMENTATION_SUMMARY.md +432 -0
- package/src/server/routes/QUICK_START.md +327 -0
- package/src/server/routes/README.md +357 -0
- package/src/server/routes/__tests__/routes.test.ts +628 -0
- package/src/server/routes/agent-route.ts +224 -0
- package/src/server/routes/agent-routes.ts +191 -0
- package/src/server/routes/embed-config.ts +181 -0
- package/src/server/routes/health-check.example.ts +507 -0
- package/src/server/routes/health-check.test.ts +533 -0
- package/src/server/routes/health-check.ts +639 -0
- package/src/server/routes/health-check.types.ts +217 -0
- package/src/server/routes/index.ts +32 -0
- package/src/server/routes/types.ts +274 -0
- package/src/shared/__tests__/schemas.test.ts +317 -0
- package/src/shared/ai-runtime.ts +139 -0
- package/src/shared/ai-types.ts +133 -0
- package/src/shared/index.ts +30 -0
- package/src/shared/sdk-runtime.ts +198 -0
- package/src/shared/sdk-types.ts +301 -0
- package/src/streaming/control/__tests__/streaming-control.test.ts +708 -0
- package/src/streaming/control/budget-guard.ts +264 -0
- package/src/streaming/control/controller.ts +255 -0
- package/src/streaming/control/index.ts +105 -0
- package/src/streaming/control/smoothing.ts +201 -0
- package/src/streaming/control/step-limit.ts +215 -0
- package/src/streaming/control/types.ts +234 -0
- package/src/streaming/core/auto-resume.ts +276 -0
- package/src/streaming/core/index.ts +85 -0
- package/src/streaming/core/multi-step.ts +471 -0
- package/src/streaming/core/protocol.ts +194 -0
- package/src/streaming/core/types.ts +182 -0
- package/src/streaming/index.ts +97 -0
- package/src/streaming/infra/backpressure/buffer.ts +210 -0
- package/src/streaming/infra/backpressure/index.ts +6 -0
- package/src/streaming/infra/index.ts +75 -0
- package/src/streaming/infra/multiplexing/index.ts +311 -0
- package/src/streaming/infra/resilience/index.ts +684 -0
- package/src/streaming/infra/transform/index.ts +15 -0
- package/src/streaming/infra/transform/stream-transforms.ts +166 -0
- package/src/streaming/infra/transport/index.ts +774 -0
- package/src/streaming/infra/types.ts +118 -0
- package/src/streaming/infra-extra/types.ts +118 -0
- package/src/tools/advanced/caching.ts +299 -0
- package/src/tools/advanced/generator.ts +267 -0
- package/src/tools/advanced/hitl.ts +251 -0
- package/src/tools/advanced/index.ts +9 -0
- package/src/tools/advanced/llm-tool.ts +208 -0
- package/src/tools/approval/FILES.md +449 -0
- package/src/tools/approval/IMPLEMENTATION_SUMMARY.md +567 -0
- package/src/tools/approval/QUICK_START.md +362 -0
- package/src/tools/approval/README.md +514 -0
- package/src/tools/approval/advanced-approval-queue.ts +7 -0
- package/src/tools/approval/approval.example.ts +571 -0
- package/src/tools/approval/in-memory-queue.ts +405 -0
- package/src/tools/approval/index.ts +737 -0
- package/src/tools/approval/middleware.ts +590 -0
- package/src/tools/approval/queue-factory.ts +162 -0
- package/src/tools/approval/redis-queue.ts +327 -0
- package/src/tools/approval/testing.ts +493 -0
- package/src/tools/approval/types.ts +221 -0
- package/src/tools/approval/with-approval.ts +366 -0
- package/src/tools/artifacts/artifact-tools.ts +273 -0
- package/src/tools/artifacts/index.ts +6 -0
- package/src/tools/compliance/compliance-wrapper.ts +789 -0
- package/src/tools/compliance/create-compliant-stream.ts +226 -0
- package/src/tools/compliance/index.ts +8 -0
- package/src/tools/compliance/phi-redaction.ts +406 -0
- package/src/tools/compliance/tool-wrapper.ts +306 -0
- package/src/tools/computer/index.ts +99 -0
- package/src/tools/computer/types.ts +41 -0
- package/src/tools/core/abort.ts +202 -0
- package/src/tools/core/factory.ts +197 -0
- package/src/tools/core/index.ts +8 -0
- package/src/tools/core/tool-safety.ts +112 -0
- package/src/tools/generic/index.ts +9 -0
- package/src/tools/generic/json-schema-tool.ts +301 -0
- package/src/tools/generic/tiptap-context.ts +619 -0
- package/src/tools/generic/web-search-tool.ts +82 -0
- package/src/tools/generic/web-search.ts +142 -0
- package/src/tools/index.ts +36 -0
- package/src/tools/mcp/ai-sdk-error-integration.ts +401 -0
- package/src/tools/mcp/client.ts +988 -0
- package/src/tools/mcp/connection-manager.ts +380 -0
- package/src/tools/mcp/connection-pool.ts +408 -0
- package/src/tools/mcp/edge-runtime.ts +318 -0
- package/src/tools/mcp/environment.ts +310 -0
- package/src/tools/mcp/index.ts +20 -0
- package/src/tools/mcp/next-pattern.ts +401 -0
- package/src/tools/mcp/stream-lifecycle-integration.ts +617 -0
- package/src/tools/mcp/tool-cache.ts +359 -0
- package/src/tools/mcp/transport-selector.ts +492 -0
- package/src/tools/mcp/transports.ts +99 -0
- package/src/tools/simple-factory.ts +55 -0
- package/src/tools/superpowers/index.ts +122 -0
- package/src/tools/superpowers/prompts/index.ts +533 -0
- package/src/tools/superpowers/schemas/index.ts +701 -0
- package/src/tools/superpowers/tools/index.ts +721 -0
- package/src/tools/validation-wrapper.ts +97 -0
|
@@ -0,0 +1,1936 @@
|
|
|
1
|
+
import { d as createMCPToolsFromConfigs, f as createTransportFromConfig, g as MCPErrorHandlerFactory, h as AISDKCompatibleMCPError, m as withRetryAndTimeout, n as DEFAULT_RETRY_CONFIG, p as globalMCPHealthMonitor, r as MCPConnectionError } from "./client-CpacYDIE.mjs";
|
|
2
|
+
import { createMCPClient } from "@ai-sdk/mcp";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { logError, logInfo, logWarn } from "@od-oneapp/shared/logs";
|
|
5
|
+
import "server-only";
|
|
6
|
+
|
|
7
|
+
//#region src/tools/mcp/stream-lifecycle-integration.ts
|
|
8
|
+
/**
|
|
9
|
+
* @fileoverview stream-lifecycle-integration.ts
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* AI SDK v6 Stream Lifecycle Integration for MCP
|
|
13
|
+
*
|
|
14
|
+
* Provides comprehensive stream lifecycle management that integrates with AI SDK v6
|
|
15
|
+
* streaming patterns and ensures proper resource cleanup throughout the stream lifecycle.
|
|
16
|
+
*
|
|
17
|
+
* Key Features:
|
|
18
|
+
* - Stream initialization with MCP client setup
|
|
19
|
+
* - Streaming event handling (onStart, onProgress, onComplete)
|
|
20
|
+
* - Stream error recovery and fallback mechanisms
|
|
21
|
+
* - Proper resource cleanup at stream end
|
|
22
|
+
* - Integration with AI SDK v6 streaming callbacks
|
|
23
|
+
* - Memory management during long streams
|
|
24
|
+
* - Stream abort handling
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* Stream lifecycle phases for proper state management
|
|
28
|
+
*/
|
|
29
|
+
let StreamLifecyclePhase = /* @__PURE__ */ function(StreamLifecyclePhase) {
|
|
30
|
+
StreamLifecyclePhase["INITIALIZING"] = "initializing";
|
|
31
|
+
StreamLifecyclePhase["CONNECTED"] = "connected";
|
|
32
|
+
StreamLifecyclePhase["STREAMING"] = "streaming";
|
|
33
|
+
StreamLifecyclePhase["PAUSED"] = "paused";
|
|
34
|
+
StreamLifecyclePhase["COMPLETING"] = "completing";
|
|
35
|
+
StreamLifecyclePhase["COMPLETED"] = "completed";
|
|
36
|
+
StreamLifecyclePhase["ERROR"] = "error";
|
|
37
|
+
StreamLifecyclePhase["ABORTED"] = "aborted";
|
|
38
|
+
StreamLifecyclePhase["CLEANUP"] = "cleanup";
|
|
39
|
+
return StreamLifecyclePhase;
|
|
40
|
+
}({});
|
|
41
|
+
/**
|
|
42
|
+
* Default stream lifecycle configuration
|
|
43
|
+
*/
|
|
44
|
+
const DEFAULT_STREAM_LIFECYCLE_CONFIG = {
|
|
45
|
+
enableHealthChecks: true,
|
|
46
|
+
healthCheckIntervalMs: 3e4,
|
|
47
|
+
streamTimeoutMs: 3e5,
|
|
48
|
+
maxRetryAttempts: 3,
|
|
49
|
+
backoffStrategy: "exponential",
|
|
50
|
+
enableMemoryMonitoring: true,
|
|
51
|
+
maxMemoryUsageMB: 200,
|
|
52
|
+
enableAbortHandling: true,
|
|
53
|
+
gracefulShutdownTimeoutMs: 1e4
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Stream lifecycle manager for MCP clients
|
|
57
|
+
* Handles the complete lifecycle of AI SDK streams with MCP tool integration
|
|
58
|
+
*/
|
|
59
|
+
var MCPStreamLifecycleManager = class {
|
|
60
|
+
phase = StreamLifecyclePhase.INITIALIZING;
|
|
61
|
+
eventHistory = [];
|
|
62
|
+
config;
|
|
63
|
+
clients = [];
|
|
64
|
+
tools = {};
|
|
65
|
+
closeAllClients = async () => {};
|
|
66
|
+
errorHandlers = [];
|
|
67
|
+
abortController;
|
|
68
|
+
healthCheckInterval;
|
|
69
|
+
memoryMonitorInterval;
|
|
70
|
+
streamStartTime;
|
|
71
|
+
constructor(clientConfigs, config = {}) {
|
|
72
|
+
this.clientConfigs = clientConfigs;
|
|
73
|
+
this.config = {
|
|
74
|
+
...DEFAULT_STREAM_LIFECYCLE_CONFIG,
|
|
75
|
+
...config
|
|
76
|
+
};
|
|
77
|
+
this.logEvent(StreamLifecyclePhase.INITIALIZING, { clientCount: clientConfigs.length });
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Initialize the stream lifecycle with MCP clients
|
|
81
|
+
*/
|
|
82
|
+
async initialize() {
|
|
83
|
+
try {
|
|
84
|
+
this.streamStartTime = /* @__PURE__ */ new Date();
|
|
85
|
+
this.logEvent(StreamLifecyclePhase.INITIALIZING, { startTime: this.streamStartTime.toISOString() });
|
|
86
|
+
if (this.config.enableAbortHandling) this.abortController = new AbortController();
|
|
87
|
+
const { createMCPToolsFromConfigs } = await import("./client-CpacYDIE.mjs").then((n) => n.l);
|
|
88
|
+
const result = await createMCPToolsFromConfigs(this.clientConfigs, { gracefulDegradation: true });
|
|
89
|
+
this.clients = result.clients;
|
|
90
|
+
this.tools = result.tools;
|
|
91
|
+
this.closeAllClients = result.closeAllClients;
|
|
92
|
+
this.errorHandlers = this.clientConfigs.map((config) => new MCPErrorHandlerFactory(config.name, "stream-lifecycle"));
|
|
93
|
+
this.phase = StreamLifecyclePhase.CONNECTED;
|
|
94
|
+
this.logEvent(StreamLifecyclePhase.CONNECTED, {
|
|
95
|
+
clientCount: this.clients.length,
|
|
96
|
+
toolCount: Object.keys(this.tools).length
|
|
97
|
+
});
|
|
98
|
+
this.startMonitoring();
|
|
99
|
+
const streamCallbacks = this.createStreamCallbacks();
|
|
100
|
+
return {
|
|
101
|
+
tools: this.tools,
|
|
102
|
+
clients: this.clients,
|
|
103
|
+
streamCallbacks
|
|
104
|
+
};
|
|
105
|
+
} catch (error) {
|
|
106
|
+
this.phase = StreamLifecyclePhase.ERROR;
|
|
107
|
+
const aiError = new AISDKCompatibleMCPError("Failed to initialize MCP stream lifecycle", "connection-error", error instanceof Error ? error : new Error(String(error)), { phase: this.phase }, true);
|
|
108
|
+
this.logEvent(StreamLifecyclePhase.ERROR, { error: aiError.message });
|
|
109
|
+
throw aiError;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Create AI SDK v6 compatible stream callbacks
|
|
114
|
+
*/
|
|
115
|
+
createStreamCallbacks() {
|
|
116
|
+
return {
|
|
117
|
+
onStart: () => {
|
|
118
|
+
this.phase = StreamLifecyclePhase.STREAMING;
|
|
119
|
+
this.logEvent(StreamLifecyclePhase.STREAMING, { elapsedMs: this.getElapsedTime() });
|
|
120
|
+
logInfo("MCP stream started", {
|
|
121
|
+
operation: "mcp_stream_start",
|
|
122
|
+
metadata: {
|
|
123
|
+
clientCount: this.clients.length,
|
|
124
|
+
toolCount: Object.keys(this.tools).length,
|
|
125
|
+
phase: this.phase
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
},
|
|
129
|
+
onProgress: (data) => {
|
|
130
|
+
if (this.config.enableMemoryMonitoring) this.checkMemoryUsage();
|
|
131
|
+
if (this.abortController?.signal.aborted) {
|
|
132
|
+
this.handleAbort();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
this.logEvent(StreamLifecyclePhase.STREAMING, {
|
|
136
|
+
progressData: data,
|
|
137
|
+
elapsedMs: this.getElapsedTime()
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
onFinish: async (event) => {
|
|
141
|
+
this.phase = StreamLifecyclePhase.COMPLETING;
|
|
142
|
+
this.logEvent(StreamLifecyclePhase.COMPLETING, {
|
|
143
|
+
finishEvent: event,
|
|
144
|
+
elapsedMs: this.getElapsedTime()
|
|
145
|
+
});
|
|
146
|
+
try {
|
|
147
|
+
await this.performGracefulCleanup();
|
|
148
|
+
this.phase = StreamLifecyclePhase.COMPLETED;
|
|
149
|
+
this.logEvent(StreamLifecyclePhase.COMPLETED, {
|
|
150
|
+
totalElapsedMs: this.getElapsedTime(),
|
|
151
|
+
eventCount: this.eventHistory.length
|
|
152
|
+
});
|
|
153
|
+
logInfo("MCP stream completed successfully", {
|
|
154
|
+
operation: "mcp_stream_complete",
|
|
155
|
+
metadata: {
|
|
156
|
+
totalElapsedMs: this.getElapsedTime(),
|
|
157
|
+
toolCallCount: event?.toolResults?.length ?? 0,
|
|
158
|
+
usage: event?.usage
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
} catch (error) {
|
|
162
|
+
this.phase = StreamLifecyclePhase.ERROR;
|
|
163
|
+
const aiError = new AISDKCompatibleMCPError("Failed to complete MCP stream lifecycle", "resource-exhausted", error instanceof Error ? error : new Error(String(error)), {
|
|
164
|
+
phase: this.phase,
|
|
165
|
+
elapsedMs: this.getElapsedTime()
|
|
166
|
+
}, false);
|
|
167
|
+
this.logEvent(StreamLifecyclePhase.ERROR, { error: aiError.message });
|
|
168
|
+
logError("MCP stream completion failed", {
|
|
169
|
+
operation: "mcp_stream_completion_error",
|
|
170
|
+
error: aiError,
|
|
171
|
+
metadata: { phase: this.phase }
|
|
172
|
+
});
|
|
173
|
+
throw aiError;
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
onError: async (error) => {
|
|
177
|
+
this.phase = StreamLifecyclePhase.ERROR;
|
|
178
|
+
const aiError = new AISDKCompatibleMCPError("MCP stream error occurred", "tool-execution-error", error, {
|
|
179
|
+
phase: this.phase,
|
|
180
|
+
elapsedMs: this.getElapsedTime(),
|
|
181
|
+
errorLocation: "stream_callback"
|
|
182
|
+
}, true);
|
|
183
|
+
this.logEvent(StreamLifecyclePhase.ERROR, {
|
|
184
|
+
error: aiError.message,
|
|
185
|
+
errorType: aiError.errorType
|
|
186
|
+
});
|
|
187
|
+
logError("MCP stream error", {
|
|
188
|
+
operation: "mcp_stream_error",
|
|
189
|
+
error: aiError,
|
|
190
|
+
metadata: {
|
|
191
|
+
phase: this.phase,
|
|
192
|
+
clientCount: this.clients.length
|
|
193
|
+
}
|
|
194
|
+
});
|
|
195
|
+
try {
|
|
196
|
+
await this.performEmergencyCleanup();
|
|
197
|
+
} catch (cleanupError) {
|
|
198
|
+
logError("Emergency cleanup failed after stream error", {
|
|
199
|
+
operation: "mcp_emergency_cleanup_failure",
|
|
200
|
+
error: cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError)),
|
|
201
|
+
metadata: { originalError: aiError.message }
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
onUncaughtError: (error) => {
|
|
206
|
+
this.phase = StreamLifecyclePhase.ERROR;
|
|
207
|
+
const aiError = new AISDKCompatibleMCPError("Uncaught error in MCP stream", "unknown-error", error, {
|
|
208
|
+
phase: this.phase,
|
|
209
|
+
elapsedMs: this.getElapsedTime(),
|
|
210
|
+
errorLocation: "uncaught"
|
|
211
|
+
}, false);
|
|
212
|
+
this.logEvent(StreamLifecyclePhase.ERROR, {
|
|
213
|
+
error: aiError.message,
|
|
214
|
+
errorType: "uncaught"
|
|
215
|
+
});
|
|
216
|
+
logError("Uncaught MCP stream error", {
|
|
217
|
+
operation: "mcp_stream_uncaught_error",
|
|
218
|
+
error: aiError,
|
|
219
|
+
metadata: {
|
|
220
|
+
phase: this.phase,
|
|
221
|
+
stackTrace: error.stack
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
this.errorHandlers.forEach((handler) => {
|
|
225
|
+
handler.createUncaughtErrorHandler(() => this.performEmergencyCleanup(), { enableRecovery: false })(error);
|
|
226
|
+
});
|
|
227
|
+
},
|
|
228
|
+
onAbort: () => {
|
|
229
|
+
this.handleAbort();
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Handle stream abortion
|
|
235
|
+
*/
|
|
236
|
+
handleAbort() {
|
|
237
|
+
this.phase = StreamLifecyclePhase.ABORTED;
|
|
238
|
+
this.logEvent(StreamLifecyclePhase.ABORTED, {
|
|
239
|
+
elapsedMs: this.getElapsedTime(),
|
|
240
|
+
reason: "user_requested"
|
|
241
|
+
});
|
|
242
|
+
logWarn("MCP stream aborted", {
|
|
243
|
+
operation: "mcp_stream_abort",
|
|
244
|
+
metadata: {
|
|
245
|
+
phase: this.phase,
|
|
246
|
+
elapsedMs: this.getElapsedTime()
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
this.performAsyncCleanup("mcp_abort_cleanup_failure");
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Start monitoring services
|
|
253
|
+
*/
|
|
254
|
+
startMonitoring() {
|
|
255
|
+
if (this.config.enableHealthChecks) this.healthCheckInterval = setInterval(() => {
|
|
256
|
+
this.performHealthCheck();
|
|
257
|
+
}, this.config.healthCheckIntervalMs);
|
|
258
|
+
if (this.config.enableMemoryMonitoring) this.memoryMonitorInterval = setInterval(() => {
|
|
259
|
+
this.checkMemoryUsage();
|
|
260
|
+
}, 1e4);
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Perform health check on MCP clients
|
|
264
|
+
*/
|
|
265
|
+
performHealthCheck() {
|
|
266
|
+
const healthStatus = this.clients.length > 0 ? "healthy" : "degraded";
|
|
267
|
+
this.logEvent(this.phase, { healthCheck: {
|
|
268
|
+
status: healthStatus,
|
|
269
|
+
clientCount: this.clients.length,
|
|
270
|
+
toolCount: Object.keys(this.tools).length,
|
|
271
|
+
elapsedMs: this.getElapsedTime()
|
|
272
|
+
} });
|
|
273
|
+
if (healthStatus === "degraded") logWarn("MCP stream health degraded", {
|
|
274
|
+
operation: "mcp_stream_health_check",
|
|
275
|
+
metadata: {
|
|
276
|
+
clientCount: this.clients.length,
|
|
277
|
+
phase: this.phase
|
|
278
|
+
}
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Check memory usage
|
|
283
|
+
*/
|
|
284
|
+
checkMemoryUsage() {
|
|
285
|
+
if (typeof process !== "undefined" && process.memoryUsage) {
|
|
286
|
+
const heapUsedMB = process.memoryUsage().heapUsed / 1024 / 1024;
|
|
287
|
+
if (heapUsedMB > this.config.maxMemoryUsageMB) {
|
|
288
|
+
logWarn("MCP stream memory usage high", {
|
|
289
|
+
operation: "mcp_stream_memory_warning",
|
|
290
|
+
metadata: {
|
|
291
|
+
heapUsedMB: Math.round(heapUsedMB),
|
|
292
|
+
maxMemoryUsageMB: this.config.maxMemoryUsageMB,
|
|
293
|
+
phase: this.phase
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
if (global.gc) global.gc();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Perform graceful cleanup
|
|
302
|
+
*/
|
|
303
|
+
async performGracefulCleanup() {
|
|
304
|
+
this.phase = StreamLifecyclePhase.CLEANUP;
|
|
305
|
+
this.logEvent(StreamLifecyclePhase.CLEANUP, {
|
|
306
|
+
cleanupType: "graceful",
|
|
307
|
+
elapsedMs: this.getElapsedTime()
|
|
308
|
+
});
|
|
309
|
+
if (this.healthCheckInterval) {
|
|
310
|
+
clearInterval(this.healthCheckInterval);
|
|
311
|
+
this.healthCheckInterval = void 0;
|
|
312
|
+
}
|
|
313
|
+
if (this.memoryMonitorInterval) {
|
|
314
|
+
clearInterval(this.memoryMonitorInterval);
|
|
315
|
+
this.memoryMonitorInterval = void 0;
|
|
316
|
+
}
|
|
317
|
+
const cleanupPromise = this.closeAllClients();
|
|
318
|
+
const timeoutPromise = new Promise((resolve, reject) => {
|
|
319
|
+
setTimeout(() => {
|
|
320
|
+
reject(/* @__PURE__ */ new Error("Graceful cleanup timeout"));
|
|
321
|
+
}, this.config.gracefulShutdownTimeoutMs);
|
|
322
|
+
});
|
|
323
|
+
try {
|
|
324
|
+
await Promise.race([cleanupPromise, timeoutPromise]);
|
|
325
|
+
logInfo("MCP stream graceful cleanup completed", {
|
|
326
|
+
operation: "mcp_stream_graceful_cleanup",
|
|
327
|
+
metadata: { elapsedMs: this.getElapsedTime() }
|
|
328
|
+
});
|
|
329
|
+
} catch (error) {
|
|
330
|
+
logWarn("Graceful cleanup timeout, performing emergency cleanup", {
|
|
331
|
+
operation: "mcp_graceful_cleanup_timeout",
|
|
332
|
+
metadata: { error: error instanceof Error ? error.message : String(error) }
|
|
333
|
+
});
|
|
334
|
+
await this.performEmergencyCleanup();
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Perform emergency cleanup
|
|
339
|
+
*/
|
|
340
|
+
async performEmergencyCleanup() {
|
|
341
|
+
this.logEvent(StreamLifecyclePhase.CLEANUP, {
|
|
342
|
+
cleanupType: "emergency",
|
|
343
|
+
elapsedMs: this.getElapsedTime()
|
|
344
|
+
});
|
|
345
|
+
if (this.healthCheckInterval) {
|
|
346
|
+
clearInterval(this.healthCheckInterval);
|
|
347
|
+
this.healthCheckInterval = void 0;
|
|
348
|
+
}
|
|
349
|
+
if (this.memoryMonitorInterval) {
|
|
350
|
+
clearInterval(this.memoryMonitorInterval);
|
|
351
|
+
this.memoryMonitorInterval = void 0;
|
|
352
|
+
}
|
|
353
|
+
this.performAsyncCleanup("mcp_emergency_cleanup_error");
|
|
354
|
+
logWarn("MCP stream emergency cleanup performed", {
|
|
355
|
+
operation: "mcp_stream_emergency_cleanup",
|
|
356
|
+
metadata: { elapsedMs: this.getElapsedTime() }
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Log lifecycle event
|
|
361
|
+
*/
|
|
362
|
+
logEvent(phase, metadata) {
|
|
363
|
+
const event = {
|
|
364
|
+
phase,
|
|
365
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
366
|
+
metadata: {
|
|
367
|
+
...metadata,
|
|
368
|
+
clientConfigs: this.clientConfigs.map((c) => c.name)
|
|
369
|
+
}
|
|
370
|
+
};
|
|
371
|
+
this.eventHistory.push(event);
|
|
372
|
+
if (this.eventHistory.length > 100) this.eventHistory = this.eventHistory.slice(-100);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Get elapsed time since stream start
|
|
376
|
+
*/
|
|
377
|
+
getElapsedTime() {
|
|
378
|
+
if (!this.streamStartTime) return 0;
|
|
379
|
+
return Date.now() - this.streamStartTime.getTime();
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Get current lifecycle status
|
|
383
|
+
*/
|
|
384
|
+
getStatus() {
|
|
385
|
+
return {
|
|
386
|
+
phase: this.phase,
|
|
387
|
+
elapsedMs: this.getElapsedTime(),
|
|
388
|
+
clientCount: this.clients.length,
|
|
389
|
+
toolCount: Object.keys(this.tools).length,
|
|
390
|
+
eventCount: this.eventHistory.length,
|
|
391
|
+
recentEvents: this.eventHistory.slice(-10)
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Request abort
|
|
396
|
+
*/
|
|
397
|
+
requestAbort() {
|
|
398
|
+
if (this.abortController && !this.abortController.signal.aborted) this.abortController.abort();
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Perform async cleanup with proper error handling
|
|
402
|
+
*/
|
|
403
|
+
async performAsyncCleanup(operationType) {
|
|
404
|
+
try {
|
|
405
|
+
await this.closeAllClients();
|
|
406
|
+
} catch (error) {
|
|
407
|
+
logError("Cleanup failed", {
|
|
408
|
+
operation: operationType,
|
|
409
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
/**
|
|
415
|
+
* Factory function to create MCP stream lifecycle manager
|
|
416
|
+
*/
|
|
417
|
+
function createMCPStreamLifecycleManager(clientConfigs, config) {
|
|
418
|
+
return new MCPStreamLifecycleManager(clientConfigs, config);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
//#endregion
|
|
422
|
+
//#region src/tools/mcp/next-pattern.ts
|
|
423
|
+
/**
|
|
424
|
+
* @fileoverview next-pattern.ts
|
|
425
|
+
*/
|
|
426
|
+
/**
|
|
427
|
+
* Helper function to handle async cleanup with error logging
|
|
428
|
+
*/
|
|
429
|
+
async function performCleanupWithLogging(cleanupFn, originalError, operationType) {
|
|
430
|
+
try {
|
|
431
|
+
await cleanupFn();
|
|
432
|
+
} catch (closeError) {
|
|
433
|
+
logError("Failed to close MCP clients after error", {
|
|
434
|
+
operation: operationType,
|
|
435
|
+
metadata: {
|
|
436
|
+
originalError: originalError.message,
|
|
437
|
+
closeError: closeError instanceof Error ? closeError.message : String(closeError)
|
|
438
|
+
},
|
|
439
|
+
error: closeError instanceof Error ? closeError : new Error(String(closeError))
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Next.js streamText-compatible MCP tools factory
|
|
445
|
+
* Follows the exact pattern from Next.js documentation:
|
|
446
|
+
* https://sdk.vercel.ai/docs/ai-sdk-ui/mcp-tools
|
|
447
|
+
*
|
|
448
|
+
* This implementation supports:
|
|
449
|
+
* - ✅ stdio transport (local processes)
|
|
450
|
+
* - ✅ SSE transport (Server-Sent Events)
|
|
451
|
+
* - ✅ HTTP transport (StreamableHTTP from @modelcontextprotocol/sdk)
|
|
452
|
+
* - ✅ Per-request client creation and cleanup
|
|
453
|
+
* - ✅ Graceful degradation when servers are unavailable
|
|
454
|
+
* - ✅ Environment-based configuration
|
|
455
|
+
* - ✅ AI SDK v6 error handling integration
|
|
456
|
+
* - ✅ Stream lifecycle management
|
|
457
|
+
* - ✅ Uncaught error handling
|
|
458
|
+
*
|
|
459
|
+
* Usage in streamText with AI SDK v6 error handling:
|
|
460
|
+
* ```typescript
|
|
461
|
+
* const { tools, closeAllClients, onUncaughtError } = await createMCPToolsForStreamText(configs);
|
|
462
|
+
*
|
|
463
|
+
* const result = streamText({
|
|
464
|
+
* model: openai('gpt-4o'),
|
|
465
|
+
* tools: {
|
|
466
|
+
* // Built-in tools
|
|
467
|
+
* someBuiltinTool,
|
|
468
|
+
* // MCP tools (following official docs pattern)
|
|
469
|
+
* ...tools,
|
|
470
|
+
* },
|
|
471
|
+
* prompt: 'Your prompt here',
|
|
472
|
+
* onFinish: async () => {
|
|
473
|
+
* await closeAllClients();
|
|
474
|
+
* },
|
|
475
|
+
* onError: (error) => {
|
|
476
|
+
* closeAllClients().catch((closeError) => {
|
|
477
|
+
* logError('Failed to close MCP clients on error', closeError instanceof Error ? closeError : new Error(String(closeError)));
|
|
478
|
+
* });
|
|
479
|
+
* },
|
|
480
|
+
* // AI SDK v6 uncaught error handling
|
|
481
|
+
* onUncaughtError: onUncaughtError,
|
|
482
|
+
* });
|
|
483
|
+
* ```
|
|
484
|
+
*/
|
|
485
|
+
async function createMCPToolsForStreamText(configs) {
|
|
486
|
+
const result = await createMCPToolsFromConfigs(configs, { gracefulDegradation: true });
|
|
487
|
+
const onUncaughtError = (error) => {
|
|
488
|
+
logError("MCP uncaught error detected", {
|
|
489
|
+
operation: "mcp_uncaught_error",
|
|
490
|
+
metadata: {
|
|
491
|
+
errorType: error.name,
|
|
492
|
+
errorMessage: error.message,
|
|
493
|
+
clientCount: result.clients.length,
|
|
494
|
+
toolCount: Object.keys(result.tools).length
|
|
495
|
+
},
|
|
496
|
+
error
|
|
497
|
+
});
|
|
498
|
+
performCleanupWithLogging(() => result.closeAllClients(), error, "mcp_cleanup_after_uncaught_error");
|
|
499
|
+
};
|
|
500
|
+
const onFinish = async () => {
|
|
501
|
+
try {
|
|
502
|
+
await result.closeAllClients();
|
|
503
|
+
logInfo("MCP clients successfully closed on finish", {
|
|
504
|
+
operation: "mcp_finish_cleanup",
|
|
505
|
+
metadata: {
|
|
506
|
+
clientCount: result.clients.length,
|
|
507
|
+
toolCount: Object.keys(result.tools).length
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
} catch (error) {
|
|
511
|
+
logError("Failed to close MCP clients on finish", {
|
|
512
|
+
operation: "mcp_finish_cleanup_error",
|
|
513
|
+
metadata: {
|
|
514
|
+
clientCount: result.clients.length,
|
|
515
|
+
error: error instanceof Error ? error.message : String(error)
|
|
516
|
+
},
|
|
517
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
518
|
+
});
|
|
519
|
+
throw error;
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
return {
|
|
523
|
+
...result,
|
|
524
|
+
onUncaughtError,
|
|
525
|
+
onFinish
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Simplified factory for basic MCP setup with AI SDK v6 integration
|
|
530
|
+
* Automatically handles common error cases and provides error callbacks
|
|
531
|
+
*/
|
|
532
|
+
async function createMCPToolsWithDefaults(configs, options = {}) {
|
|
533
|
+
const { gracefulDegradation = true, logErrors = true, includeAISDKCallbacks = true } = options;
|
|
534
|
+
const errors = [];
|
|
535
|
+
let tools = {};
|
|
536
|
+
let clients = [];
|
|
537
|
+
let closeAllClients = async () => {};
|
|
538
|
+
let isAvailable = false;
|
|
539
|
+
let onUncaughtError;
|
|
540
|
+
let onFinish;
|
|
541
|
+
if (configs.length === 0) {
|
|
542
|
+
if (logErrors) logInfo("No MCP configs provided", { operation: "mcp_tools_creation" });
|
|
543
|
+
return {
|
|
544
|
+
tools,
|
|
545
|
+
clients,
|
|
546
|
+
closeAllClients,
|
|
547
|
+
isAvailable,
|
|
548
|
+
errors,
|
|
549
|
+
onUncaughtError,
|
|
550
|
+
onFinish
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
try {
|
|
554
|
+
const result = await createMCPToolsFromConfigs(configs, { gracefulDegradation });
|
|
555
|
+
({tools, clients, closeAllClients} = result);
|
|
556
|
+
isAvailable = Object.keys(tools).length > 0;
|
|
557
|
+
if (includeAISDKCallbacks) {
|
|
558
|
+
onUncaughtError = (error) => {
|
|
559
|
+
if (logErrors) logError("MCP uncaught error in defaults setup", {
|
|
560
|
+
operation: "mcp_defaults_uncaught_error",
|
|
561
|
+
metadata: {
|
|
562
|
+
errorType: error.name,
|
|
563
|
+
errorMessage: error.message,
|
|
564
|
+
clientCount: clients.length,
|
|
565
|
+
toolCount: Object.keys(tools).length
|
|
566
|
+
},
|
|
567
|
+
error
|
|
568
|
+
});
|
|
569
|
+
if (logErrors) performCleanupWithLogging(closeAllClients, error, "mcp_defaults_cleanup_error");
|
|
570
|
+
else (async () => {
|
|
571
|
+
try {
|
|
572
|
+
await closeAllClients();
|
|
573
|
+
} catch {}
|
|
574
|
+
})();
|
|
575
|
+
};
|
|
576
|
+
onFinish = async () => {
|
|
577
|
+
try {
|
|
578
|
+
await closeAllClients();
|
|
579
|
+
if (logErrors) logInfo("MCP clients closed successfully on finish (defaults)", {
|
|
580
|
+
operation: "mcp_defaults_finish_cleanup",
|
|
581
|
+
metadata: {
|
|
582
|
+
clientCount: clients.length,
|
|
583
|
+
toolCount: Object.keys(tools).length
|
|
584
|
+
}
|
|
585
|
+
});
|
|
586
|
+
} catch (error) {
|
|
587
|
+
if (logErrors) logError("Failed to close MCP clients on finish (defaults)", {
|
|
588
|
+
operation: "mcp_defaults_finish_error",
|
|
589
|
+
metadata: {
|
|
590
|
+
clientCount: clients.length,
|
|
591
|
+
error: error instanceof Error ? error.message : String(error)
|
|
592
|
+
},
|
|
593
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
594
|
+
});
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
if (logErrors && isAvailable) logInfo(`MCP tools loaded: ${Object.keys(tools).join(", ")}`, {
|
|
600
|
+
toolCount: Object.keys(tools).length,
|
|
601
|
+
toolNames: Object.keys(tools),
|
|
602
|
+
operation: "mcp_tools_creation"
|
|
603
|
+
});
|
|
604
|
+
} catch (error) {
|
|
605
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown MCP error";
|
|
606
|
+
errors.push(errorMessage);
|
|
607
|
+
if (logErrors) logError("MCP tools failed to load", {
|
|
608
|
+
operation: "mcp_tools_creation",
|
|
609
|
+
errorMessage,
|
|
610
|
+
error: error instanceof Error ? error : new Error(errorMessage)
|
|
611
|
+
});
|
|
612
|
+
if (!gracefulDegradation) throw error;
|
|
613
|
+
}
|
|
614
|
+
return {
|
|
615
|
+
tools,
|
|
616
|
+
clients,
|
|
617
|
+
closeAllClients,
|
|
618
|
+
isAvailable,
|
|
619
|
+
errors,
|
|
620
|
+
onUncaughtError,
|
|
621
|
+
onFinish
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Test MCP connectivity without creating persistent connections
|
|
626
|
+
*/
|
|
627
|
+
async function testMCPConnectivity(configs) {
|
|
628
|
+
const results = [];
|
|
629
|
+
for (const config of configs) try {
|
|
630
|
+
const { tools, closeAllClients } = await createMCPToolsFromConfigs([config]);
|
|
631
|
+
const toolCount = Object.keys(tools).length;
|
|
632
|
+
results.push({
|
|
633
|
+
name: config.name,
|
|
634
|
+
success: true,
|
|
635
|
+
toolCount
|
|
636
|
+
});
|
|
637
|
+
await closeAllClients();
|
|
638
|
+
} catch (error) {
|
|
639
|
+
results.push({
|
|
640
|
+
name: config.name,
|
|
641
|
+
success: false,
|
|
642
|
+
error: error instanceof Error ? error.message : "Unknown error",
|
|
643
|
+
toolCount: 0
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
return {
|
|
647
|
+
results,
|
|
648
|
+
overallSuccess: results.every((r) => r.success)
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Advanced MCP tools factory with full AI SDK v6 stream lifecycle management
|
|
653
|
+
* Provides comprehensive error handling, monitoring, and resource management
|
|
654
|
+
*/
|
|
655
|
+
async function createMCPToolsWithStreamLifecycle(configs, lifecycleConfig) {
|
|
656
|
+
const lifecycleManager = createMCPStreamLifecycleManager(configs, lifecycleConfig);
|
|
657
|
+
const { tools, clients, streamCallbacks } = await lifecycleManager.initialize();
|
|
658
|
+
const closeAllClients = async () => {
|
|
659
|
+
try {
|
|
660
|
+
await streamCallbacks.onFinish({});
|
|
661
|
+
} catch (error) {
|
|
662
|
+
logError("Failed to close MCP clients via lifecycle manager", {
|
|
663
|
+
operation: "mcp_lifecycle_cleanup_error",
|
|
664
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
665
|
+
metadata: {
|
|
666
|
+
clientCount: clients.length,
|
|
667
|
+
toolCount: Object.keys(tools).length
|
|
668
|
+
}
|
|
669
|
+
});
|
|
670
|
+
throw error;
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
const compatibleOnFinish = async () => {
|
|
674
|
+
await streamCallbacks.onFinish({});
|
|
675
|
+
};
|
|
676
|
+
return {
|
|
677
|
+
tools,
|
|
678
|
+
clients,
|
|
679
|
+
closeAllClients,
|
|
680
|
+
onUncaughtError: streamCallbacks.onUncaughtError,
|
|
681
|
+
onFinish: compatibleOnFinish,
|
|
682
|
+
streamCallbacks,
|
|
683
|
+
lifecycleManager: {
|
|
684
|
+
getStatus: lifecycleManager.getStatus.bind(lifecycleManager),
|
|
685
|
+
requestAbort: lifecycleManager.requestAbort.bind(lifecycleManager)
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
//#endregion
|
|
691
|
+
//#region src/tools/mcp/connection-manager.ts
|
|
692
|
+
/**
|
|
693
|
+
* @fileoverview connection-manager.ts
|
|
694
|
+
*/
|
|
695
|
+
/**
|
|
696
|
+
* Enhanced MCP connection manager with pooling and monitoring
|
|
697
|
+
* Provides connection reuse, health checking, and monitoring for production use
|
|
698
|
+
*/
|
|
699
|
+
var MCPConnectionManager = class {
|
|
700
|
+
connections = /* @__PURE__ */ new Map();
|
|
701
|
+
config;
|
|
702
|
+
healthCheckTimer;
|
|
703
|
+
events = {};
|
|
704
|
+
constructor(config = {}) {
|
|
705
|
+
this.config = {
|
|
706
|
+
maxConnections: 10,
|
|
707
|
+
connectionTimeout: 3e4,
|
|
708
|
+
healthCheckInterval: 6e4,
|
|
709
|
+
retryAttempts: 3,
|
|
710
|
+
retryDelay: 1e3,
|
|
711
|
+
...config
|
|
712
|
+
};
|
|
713
|
+
this.startHealthChecking();
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Register event listeners
|
|
717
|
+
*/
|
|
718
|
+
on(event, listener) {
|
|
719
|
+
this.events[event] = listener;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Get or create a connection for the given config
|
|
723
|
+
*/
|
|
724
|
+
async getConnection(config) {
|
|
725
|
+
const key = this.getConnectionKey(config);
|
|
726
|
+
let connection = this.connections.get(key);
|
|
727
|
+
if (connection) {
|
|
728
|
+
connection.lastUsed = /* @__PURE__ */ new Date();
|
|
729
|
+
connection.useCount += 1;
|
|
730
|
+
return connection;
|
|
731
|
+
}
|
|
732
|
+
if (this.connections.size >= this.config.maxConnections) await this.evictOldestConnection();
|
|
733
|
+
connection = await this.createConnection(config);
|
|
734
|
+
this.connections.set(key, connection);
|
|
735
|
+
this.events.created?.(config);
|
|
736
|
+
return connection;
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Get all tools from active connections
|
|
740
|
+
*/
|
|
741
|
+
async getAllTools() {
|
|
742
|
+
const allTools = {};
|
|
743
|
+
for (const connection of this.connections.values()) if (connection.isHealthy) Object.assign(allTools, connection.tools);
|
|
744
|
+
return allTools;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Get connection statistics
|
|
748
|
+
*/
|
|
749
|
+
getStats() {
|
|
750
|
+
const connections = Array.from(this.connections.values());
|
|
751
|
+
const healthyConnections = connections.filter((c) => c.isHealthy);
|
|
752
|
+
const totalUseCount = connections.reduce((sum, c) => sum + c.useCount, 0);
|
|
753
|
+
const createdDates = connections.map((c) => c.createdAt);
|
|
754
|
+
const oldestConnection = createdDates.length > 0 ? new Date(Math.min(...createdDates.map((d) => d.getTime()))) : void 0;
|
|
755
|
+
const newestConnection = createdDates.length > 0 ? new Date(Math.max(...createdDates.map((d) => d.getTime()))) : void 0;
|
|
756
|
+
return {
|
|
757
|
+
totalConnections: connections.length,
|
|
758
|
+
healthyConnections: healthyConnections.length,
|
|
759
|
+
totalUseCount,
|
|
760
|
+
oldestConnection,
|
|
761
|
+
newestConnection
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Close specific connection
|
|
766
|
+
*/
|
|
767
|
+
async closeConnection(config) {
|
|
768
|
+
const key = this.getConnectionKey(config);
|
|
769
|
+
const connection = this.connections.get(key);
|
|
770
|
+
if (connection) {
|
|
771
|
+
try {
|
|
772
|
+
await connection.client.close();
|
|
773
|
+
} catch (error) {
|
|
774
|
+
logWarn(`Failed to close MCP connection ${config.name}`, {
|
|
775
|
+
connectionName: config.name,
|
|
776
|
+
error: error instanceof Error ? error.message : String(error),
|
|
777
|
+
operation: "mcp_close_connection"
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
this.connections.delete(key);
|
|
781
|
+
this.events.destroyed?.(config);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Close all connections and cleanup
|
|
786
|
+
*/
|
|
787
|
+
async closeAll() {
|
|
788
|
+
if (this.healthCheckTimer) clearInterval(this.healthCheckTimer);
|
|
789
|
+
const closePromises = Array.from(this.connections.values()).map(async (connection) => {
|
|
790
|
+
try {
|
|
791
|
+
await connection.client.close();
|
|
792
|
+
} catch (error) {
|
|
793
|
+
logWarn(`Failed to close MCP connection ${connection.config.name}`, {
|
|
794
|
+
connectionName: connection.config.name,
|
|
795
|
+
error: error instanceof Error ? error.message : String(error),
|
|
796
|
+
operation: "mcp_close_all_connections"
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
});
|
|
800
|
+
await Promise.all(closePromises);
|
|
801
|
+
this.connections.clear();
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Perform health check on all connections
|
|
805
|
+
*/
|
|
806
|
+
async performHealthCheck() {
|
|
807
|
+
const healthCheckPromises = Array.from(this.connections.values()).map(async (connection) => {
|
|
808
|
+
try {
|
|
809
|
+
await connection.client.tools();
|
|
810
|
+
connection.isHealthy = true;
|
|
811
|
+
connection.lastHealthCheck = /* @__PURE__ */ new Date();
|
|
812
|
+
this.events.healthCheck?.(connection.config, true);
|
|
813
|
+
} catch (error) {
|
|
814
|
+
connection.isHealthy = false;
|
|
815
|
+
connection.lastHealthCheck = /* @__PURE__ */ new Date();
|
|
816
|
+
this.events.healthCheck?.(connection.config, false);
|
|
817
|
+
this.events.error?.(connection.config, error instanceof Error ? error : new Error(String(error)));
|
|
818
|
+
const key = this.getConnectionKey(connection.config);
|
|
819
|
+
this.connections.delete(key);
|
|
820
|
+
try {
|
|
821
|
+
await connection.client.close();
|
|
822
|
+
} catch (closeError) {
|
|
823
|
+
logWarn(`Failed to close unhealthy connection ${connection.config.name}`, {
|
|
824
|
+
connectionName: connection.config.name,
|
|
825
|
+
error: closeError instanceof Error ? closeError.message : String(closeError),
|
|
826
|
+
operation: "mcp_close_unhealthy_connection"
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
});
|
|
831
|
+
await Promise.all(healthCheckPromises);
|
|
832
|
+
}
|
|
833
|
+
getConnectionKey(config) {
|
|
834
|
+
const { transport } = config;
|
|
835
|
+
const normalizedTransport = transport.type === "stdio" ? {
|
|
836
|
+
type: transport.type,
|
|
837
|
+
command: transport.command,
|
|
838
|
+
args: transport.args,
|
|
839
|
+
cwd: transport.cwd
|
|
840
|
+
} : {
|
|
841
|
+
type: transport.type,
|
|
842
|
+
url: transport.url ?? transport.httpUrl,
|
|
843
|
+
sessionId: transport.sessionId
|
|
844
|
+
};
|
|
845
|
+
const hash = createHash("sha256").update(JSON.stringify(normalizedTransport)).digest("hex").slice(0, 12);
|
|
846
|
+
return `${config.name}-${transport.type}-${hash}`;
|
|
847
|
+
}
|
|
848
|
+
async createConnection(config) {
|
|
849
|
+
let attempt = 0;
|
|
850
|
+
let lastError;
|
|
851
|
+
while (attempt < this.config.retryAttempts) try {
|
|
852
|
+
const client = await createMCPClient({ transport: createTransportFromConfig(config.transport) });
|
|
853
|
+
return {
|
|
854
|
+
config,
|
|
855
|
+
client,
|
|
856
|
+
tools: await client.tools(),
|
|
857
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
858
|
+
lastUsed: /* @__PURE__ */ new Date(),
|
|
859
|
+
useCount: 1,
|
|
860
|
+
isHealthy: true,
|
|
861
|
+
lastHealthCheck: /* @__PURE__ */ new Date()
|
|
862
|
+
};
|
|
863
|
+
} catch (error) {
|
|
864
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
865
|
+
attempt++;
|
|
866
|
+
if (attempt < this.config.retryAttempts) await new Promise((resolve) => setTimeout(resolve, this.config.retryDelay * attempt));
|
|
867
|
+
}
|
|
868
|
+
throw lastError ?? /* @__PURE__ */ new Error("All connection attempts failed");
|
|
869
|
+
}
|
|
870
|
+
async evictOldestConnection() {
|
|
871
|
+
let oldestConnection = null;
|
|
872
|
+
for (const [key, connection] of this.connections.entries()) if (!oldestConnection || connection.lastUsed < oldestConnection.connection.lastUsed) oldestConnection = {
|
|
873
|
+
key,
|
|
874
|
+
connection
|
|
875
|
+
};
|
|
876
|
+
if (oldestConnection) await this.closeConnection(oldestConnection.connection.config);
|
|
877
|
+
}
|
|
878
|
+
startHealthChecking() {
|
|
879
|
+
this.healthCheckTimer = setInterval(() => {
|
|
880
|
+
(async () => {
|
|
881
|
+
try {
|
|
882
|
+
await this.performHealthCheck();
|
|
883
|
+
} catch (error) {
|
|
884
|
+
logWarn("Health check failed", {
|
|
885
|
+
error: error instanceof Error ? error.message : String(error),
|
|
886
|
+
operation: "mcp_health_check"
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
})();
|
|
890
|
+
}, this.config.healthCheckInterval);
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
/**
|
|
894
|
+
* Global connection manager instance
|
|
895
|
+
* Provides a singleton for connection pooling across the application
|
|
896
|
+
*/
|
|
897
|
+
let globalConnectionManager = null;
|
|
898
|
+
function getGlobalConnectionManager(config) {
|
|
899
|
+
if (!globalConnectionManager) globalConnectionManager = new MCPConnectionManager(config);
|
|
900
|
+
return globalConnectionManager;
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Create MCP tools with connection pooling
|
|
904
|
+
* This provides better performance and resource management for production use
|
|
905
|
+
*/
|
|
906
|
+
async function createPooledMCPTools(configs, options = {}) {
|
|
907
|
+
const manager = options.useGlobalPool ? getGlobalConnectionManager(options.poolConfig) : new MCPConnectionManager(options.poolConfig);
|
|
908
|
+
const tools = {};
|
|
909
|
+
for (const config of configs) try {
|
|
910
|
+
const connection = await manager.getConnection(config);
|
|
911
|
+
Object.assign(tools, connection.tools);
|
|
912
|
+
} catch (error) {
|
|
913
|
+
logWarn(`Failed to get connection for ${config.name}`, {
|
|
914
|
+
connectionName: config.name,
|
|
915
|
+
error: error instanceof Error ? error.message : String(error),
|
|
916
|
+
operation: "mcp_get_connection"
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
return {
|
|
920
|
+
tools,
|
|
921
|
+
manager
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
//#endregion
|
|
926
|
+
//#region src/tools/mcp/tool-cache.ts
|
|
927
|
+
/**
|
|
928
|
+
* @fileoverview tool-cache.ts
|
|
929
|
+
*/
|
|
930
|
+
/**
|
|
931
|
+
* Default tool cache configuration
|
|
932
|
+
*/
|
|
933
|
+
const DEFAULT_CACHE_CONFIG = {
|
|
934
|
+
enabled: true,
|
|
935
|
+
maxEntries: 1e3,
|
|
936
|
+
ttlMs: 3e5,
|
|
937
|
+
maxMemoryMB: 50,
|
|
938
|
+
compressionEnabled: false
|
|
939
|
+
};
|
|
940
|
+
/**
|
|
941
|
+
* MCP Tool Cache
|
|
942
|
+
* Caches frequently used MCP tools to improve performance
|
|
943
|
+
*/
|
|
944
|
+
var MCPToolCache = class {
|
|
945
|
+
cache = /* @__PURE__ */ new Map();
|
|
946
|
+
config;
|
|
947
|
+
stats = {
|
|
948
|
+
hits: 0,
|
|
949
|
+
misses: 0,
|
|
950
|
+
totalAccessTime: 0,
|
|
951
|
+
accessCount: 0
|
|
952
|
+
};
|
|
953
|
+
cleanupInterval;
|
|
954
|
+
constructor(config = {}) {
|
|
955
|
+
this.config = {
|
|
956
|
+
...DEFAULT_CACHE_CONFIG,
|
|
957
|
+
...config
|
|
958
|
+
};
|
|
959
|
+
if (this.config.enabled) this.startCleanupTask();
|
|
960
|
+
}
|
|
961
|
+
/**
|
|
962
|
+
* Get tools from cache if available
|
|
963
|
+
*/
|
|
964
|
+
get(clientConfig) {
|
|
965
|
+
if (!this.config.enabled) return null;
|
|
966
|
+
const key = this.getCacheKey(clientConfig);
|
|
967
|
+
const entry = this.cache.get(key);
|
|
968
|
+
if (!entry) {
|
|
969
|
+
this.stats.misses++;
|
|
970
|
+
return null;
|
|
971
|
+
}
|
|
972
|
+
const now = /* @__PURE__ */ new Date();
|
|
973
|
+
if (now.getTime() - entry.createdAt.getTime() > this.config.ttlMs) {
|
|
974
|
+
this.cache.delete(key);
|
|
975
|
+
this.stats.misses++;
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
entry.lastAccessed = now;
|
|
979
|
+
entry.accessCount++;
|
|
980
|
+
this.stats.hits++;
|
|
981
|
+
return entry.tools;
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Store tools in cache
|
|
985
|
+
*/
|
|
986
|
+
set(clientConfig, tools) {
|
|
987
|
+
if (!this.config.enabled) return;
|
|
988
|
+
const key = this.getCacheKey(clientConfig);
|
|
989
|
+
const size = this.estimateSize(tools);
|
|
990
|
+
const now = /* @__PURE__ */ new Date();
|
|
991
|
+
if (this.shouldEvictForMemory(size)) this.evictLeastRecentlyUsed();
|
|
992
|
+
if (this.cache.size >= this.config.maxEntries) this.evictOldestEntry();
|
|
993
|
+
const entry = {
|
|
994
|
+
tools,
|
|
995
|
+
createdAt: now,
|
|
996
|
+
lastAccessed: now,
|
|
997
|
+
accessCount: 1,
|
|
998
|
+
size
|
|
999
|
+
};
|
|
1000
|
+
this.cache.set(key, entry);
|
|
1001
|
+
}
|
|
1002
|
+
/**
|
|
1003
|
+
* Clear all cached tools for a specific client
|
|
1004
|
+
*/
|
|
1005
|
+
invalidate(clientConfig) {
|
|
1006
|
+
const key = this.getCacheKey(clientConfig);
|
|
1007
|
+
this.cache.delete(key);
|
|
1008
|
+
}
|
|
1009
|
+
/**
|
|
1010
|
+
* Clear all cached tools
|
|
1011
|
+
*/
|
|
1012
|
+
clear() {
|
|
1013
|
+
this.cache.clear();
|
|
1014
|
+
this.resetStats();
|
|
1015
|
+
}
|
|
1016
|
+
/**
|
|
1017
|
+
* Get cache statistics
|
|
1018
|
+
*/
|
|
1019
|
+
getStats() {
|
|
1020
|
+
const entries = Array.from(this.cache.values());
|
|
1021
|
+
const totalSize = entries.reduce((sum, entry) => sum + entry.size, 0);
|
|
1022
|
+
const totalRequests = this.stats.hits + this.stats.misses;
|
|
1023
|
+
const hitRate = totalRequests > 0 ? this.stats.hits / totalRequests : 0;
|
|
1024
|
+
const avgAccessTime = this.stats.accessCount > 0 ? this.stats.totalAccessTime / this.stats.accessCount : 0;
|
|
1025
|
+
return {
|
|
1026
|
+
hits: this.stats.hits,
|
|
1027
|
+
misses: this.stats.misses,
|
|
1028
|
+
entries: this.cache.size,
|
|
1029
|
+
totalSize,
|
|
1030
|
+
hitRate,
|
|
1031
|
+
avgAccessTime,
|
|
1032
|
+
oldestEntry: entries.length > 0 ? new Date(Math.min(...entries.map((e) => e.createdAt.getTime()))) : void 0,
|
|
1033
|
+
newestEntry: entries.length > 0 ? new Date(Math.max(...entries.map((e) => e.createdAt.getTime()))) : void 0
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* Generate cache key for client configuration
|
|
1038
|
+
*/
|
|
1039
|
+
getCacheKey(clientConfig) {
|
|
1040
|
+
return `mcp:${clientConfig.name}:${clientConfig.transport.type}:${JSON.stringify(clientConfig.transport)}`;
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* Estimate memory size of tools object
|
|
1044
|
+
*/
|
|
1045
|
+
estimateSize(tools) {
|
|
1046
|
+
try {
|
|
1047
|
+
return JSON.stringify(tools).length * 2;
|
|
1048
|
+
} catch {
|
|
1049
|
+
return 1024;
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Check if we should evict entries to stay within memory limits
|
|
1054
|
+
*/
|
|
1055
|
+
shouldEvictForMemory(newEntrySize) {
|
|
1056
|
+
const currentSize = Array.from(this.cache.values()).reduce((sum, entry) => sum + entry.size, 0);
|
|
1057
|
+
const maxSizeBytes = this.config.maxMemoryMB * 1024 * 1024;
|
|
1058
|
+
return currentSize + newEntrySize > maxSizeBytes;
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Evict least recently used entries
|
|
1062
|
+
*/
|
|
1063
|
+
evictLeastRecentlyUsed() {
|
|
1064
|
+
if (this.cache.size === 0) return;
|
|
1065
|
+
const entries = Array.from(this.cache.entries()).sort(([, a], [, b]) => a.lastAccessed.getTime() - b.lastAccessed.getTime());
|
|
1066
|
+
const toRemove = Math.max(1, Math.floor(entries.length * .25));
|
|
1067
|
+
for (let i = 0; i < toRemove; i++) {
|
|
1068
|
+
const entry = entries[i];
|
|
1069
|
+
if (!entry) continue;
|
|
1070
|
+
const [key] = entry;
|
|
1071
|
+
this.cache.delete(key);
|
|
1072
|
+
}
|
|
1073
|
+
logWarn(`Evicted ${toRemove} LRU entries from MCP tool cache`, {
|
|
1074
|
+
operation: "mcp_cache_lru_eviction",
|
|
1075
|
+
metadata: {
|
|
1076
|
+
evictedCount: toRemove,
|
|
1077
|
+
remainingEntries: this.cache.size
|
|
1078
|
+
}
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
/**
|
|
1082
|
+
* Evict oldest entry
|
|
1083
|
+
*/
|
|
1084
|
+
evictOldestEntry() {
|
|
1085
|
+
if (this.cache.size === 0) return;
|
|
1086
|
+
let oldestKey = null;
|
|
1087
|
+
let oldestTime = Date.now();
|
|
1088
|
+
for (const [key, entry] of this.cache.entries()) if (entry.createdAt.getTime() < oldestTime) {
|
|
1089
|
+
oldestTime = entry.createdAt.getTime();
|
|
1090
|
+
oldestKey = key;
|
|
1091
|
+
}
|
|
1092
|
+
if (oldestKey) this.cache.delete(oldestKey);
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Start periodic cleanup task
|
|
1096
|
+
*/
|
|
1097
|
+
startCleanupTask() {
|
|
1098
|
+
this.cleanupInterval = setInterval(() => {
|
|
1099
|
+
this.cleanupExpiredEntries();
|
|
1100
|
+
}, 6e4);
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Clean up expired entries
|
|
1104
|
+
*/
|
|
1105
|
+
cleanupExpiredEntries() {
|
|
1106
|
+
const now = /* @__PURE__ */ new Date();
|
|
1107
|
+
const expiredKeys = [];
|
|
1108
|
+
for (const [key, entry] of this.cache.entries()) if (now.getTime() - entry.createdAt.getTime() > this.config.ttlMs) expiredKeys.push(key);
|
|
1109
|
+
for (const key of expiredKeys) this.cache.delete(key);
|
|
1110
|
+
if (expiredKeys.length > 0) logWarn(`Cleaned up ${expiredKeys.length} expired entries from MCP tool cache`, {
|
|
1111
|
+
operation: "mcp_cache_cleanup",
|
|
1112
|
+
metadata: {
|
|
1113
|
+
expiredCount: expiredKeys.length,
|
|
1114
|
+
remainingEntries: this.cache.size
|
|
1115
|
+
}
|
|
1116
|
+
});
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* Reset statistics
|
|
1120
|
+
*/
|
|
1121
|
+
resetStats() {
|
|
1122
|
+
this.stats = {
|
|
1123
|
+
hits: 0,
|
|
1124
|
+
misses: 0,
|
|
1125
|
+
totalAccessTime: 0,
|
|
1126
|
+
accessCount: 0
|
|
1127
|
+
};
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Disable caching
|
|
1131
|
+
*/
|
|
1132
|
+
disable() {
|
|
1133
|
+
this.config.enabled = false;
|
|
1134
|
+
this.clear();
|
|
1135
|
+
if (this.cleanupInterval) {
|
|
1136
|
+
clearInterval(this.cleanupInterval);
|
|
1137
|
+
this.cleanupInterval = void 0;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Enable caching
|
|
1142
|
+
*/
|
|
1143
|
+
enable() {
|
|
1144
|
+
this.config.enabled = true;
|
|
1145
|
+
this.startCleanupTask();
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Cleanup resources
|
|
1149
|
+
*/
|
|
1150
|
+
cleanup() {
|
|
1151
|
+
if (this.cleanupInterval) {
|
|
1152
|
+
clearInterval(this.cleanupInterval);
|
|
1153
|
+
this.cleanupInterval = void 0;
|
|
1154
|
+
}
|
|
1155
|
+
this.clear();
|
|
1156
|
+
}
|
|
1157
|
+
};
|
|
1158
|
+
/**
|
|
1159
|
+
* Global MCP tool cache instance
|
|
1160
|
+
*/
|
|
1161
|
+
const globalMCPToolCache = new MCPToolCache();
|
|
1162
|
+
|
|
1163
|
+
//#endregion
|
|
1164
|
+
//#region src/tools/mcp/connection-pool.ts
|
|
1165
|
+
/**
|
|
1166
|
+
* @fileoverview connection-pool.ts
|
|
1167
|
+
*/
|
|
1168
|
+
/**
|
|
1169
|
+
* Default connection pool configuration
|
|
1170
|
+
*/
|
|
1171
|
+
const DEFAULT_POOL_CONFIG = {
|
|
1172
|
+
maxConnections: 10,
|
|
1173
|
+
minConnections: 2,
|
|
1174
|
+
idleTimeoutMs: 3e5,
|
|
1175
|
+
connectionTimeoutMs: 3e4,
|
|
1176
|
+
healthCheckEnabled: true
|
|
1177
|
+
};
|
|
1178
|
+
/**
|
|
1179
|
+
* MCP Connection Pool
|
|
1180
|
+
* Manages a pool of reusable MCP client connections for better performance
|
|
1181
|
+
*/
|
|
1182
|
+
var MCPConnectionPool = class {
|
|
1183
|
+
connections = /* @__PURE__ */ new Map();
|
|
1184
|
+
poolConfig;
|
|
1185
|
+
cleanupInterval;
|
|
1186
|
+
constructor(config = {}) {
|
|
1187
|
+
this.poolConfig = {
|
|
1188
|
+
...DEFAULT_POOL_CONFIG,
|
|
1189
|
+
...config
|
|
1190
|
+
};
|
|
1191
|
+
this.startCleanupTask();
|
|
1192
|
+
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Get a connection from the pool or create a new one
|
|
1195
|
+
*/
|
|
1196
|
+
async getConnection(config) {
|
|
1197
|
+
const poolKey = this.getPoolKey(config);
|
|
1198
|
+
let pool = this.connections.get(poolKey);
|
|
1199
|
+
if (!pool) {
|
|
1200
|
+
pool = [];
|
|
1201
|
+
this.connections.set(poolKey, pool);
|
|
1202
|
+
}
|
|
1203
|
+
const availableConnection = pool.find((conn) => !conn.inUse);
|
|
1204
|
+
if (availableConnection) {
|
|
1205
|
+
availableConnection.inUse = true;
|
|
1206
|
+
availableConnection.lastUsed = /* @__PURE__ */ new Date();
|
|
1207
|
+
return availableConnection;
|
|
1208
|
+
}
|
|
1209
|
+
if (pool.length >= this.poolConfig.maxConnections) return this.waitForAvailableConnection(poolKey);
|
|
1210
|
+
return this.createConnection(config, poolKey);
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Return a connection to the pool
|
|
1214
|
+
*/
|
|
1215
|
+
releaseConnection(connection) {
|
|
1216
|
+
connection.inUse = false;
|
|
1217
|
+
connection.lastUsed = /* @__PURE__ */ new Date();
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Get tools from a pooled connection with caching
|
|
1221
|
+
*/
|
|
1222
|
+
async getTools(config) {
|
|
1223
|
+
const cachedTools = globalMCPToolCache.get(config);
|
|
1224
|
+
if (cachedTools) return cachedTools;
|
|
1225
|
+
if (this.poolConfig.healthCheckEnabled && globalMCPHealthMonitor.shouldExclude(config.name)) if (config.gracefulDegradation) {
|
|
1226
|
+
logWarn(`Skipping unhealthy MCP client '${config.name}' in pool`, {
|
|
1227
|
+
operation: "mcp_pool_skip_unhealthy",
|
|
1228
|
+
metadata: {
|
|
1229
|
+
clientName: config.name,
|
|
1230
|
+
healthStatus: globalMCPHealthMonitor.getHealthStatus(config.name)
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
return emptyToolSet();
|
|
1234
|
+
} else throw new MCPConnectionError(`MCP client '${config.name}' is marked as unhealthy`, config.name, config.transport.type);
|
|
1235
|
+
let connection = null;
|
|
1236
|
+
try {
|
|
1237
|
+
connection = await this.getConnection(config);
|
|
1238
|
+
const tools = await withRetryAndTimeout(() => {
|
|
1239
|
+
if (!connection) throw new Error("Connection is null");
|
|
1240
|
+
return connection.client.tools();
|
|
1241
|
+
}, config.retry ?? DEFAULT_RETRY_CONFIG, config.timeoutMs || this.poolConfig.connectionTimeoutMs, `MCP pooled tools retrieval (${config.name})`);
|
|
1242
|
+
globalMCPToolCache.set(config, tools);
|
|
1243
|
+
return tools;
|
|
1244
|
+
} catch (error) {
|
|
1245
|
+
if (connection) await this.removeConnection(connection);
|
|
1246
|
+
const mcpError = new MCPConnectionError(`Failed to get tools from pooled MCP client '${config.name}'`, config.name, config.transport.type, error instanceof Error ? error : new Error(String(error)));
|
|
1247
|
+
if (config.gracefulDegradation) {
|
|
1248
|
+
logWarn(`Pooled MCP client '${config.name}' failed, continuing with degraded functionality`, {
|
|
1249
|
+
operation: "mcp_pool_degraded",
|
|
1250
|
+
metadata: {
|
|
1251
|
+
clientName: config.name,
|
|
1252
|
+
transportType: config.transport.type,
|
|
1253
|
+
error: mcpError.message
|
|
1254
|
+
}
|
|
1255
|
+
});
|
|
1256
|
+
return emptyToolSet();
|
|
1257
|
+
}
|
|
1258
|
+
throw mcpError;
|
|
1259
|
+
} finally {
|
|
1260
|
+
if (connection) this.releaseConnection(connection);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Create a new pooled connection
|
|
1265
|
+
*/
|
|
1266
|
+
async createConnection(config, poolKey) {
|
|
1267
|
+
const connectionId = `${config.name}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
1268
|
+
try {
|
|
1269
|
+
const connection = {
|
|
1270
|
+
client: await withRetryAndTimeout(async () => {
|
|
1271
|
+
return createMCPClient({ transport: createTransportFromConfig(config.transport) });
|
|
1272
|
+
}, config.retry ?? DEFAULT_RETRY_CONFIG, config.timeoutMs || this.poolConfig.connectionTimeoutMs, `MCP pool connection creation (${config.name})`),
|
|
1273
|
+
config,
|
|
1274
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
1275
|
+
lastUsed: /* @__PURE__ */ new Date(),
|
|
1276
|
+
inUse: true,
|
|
1277
|
+
id: connectionId
|
|
1278
|
+
};
|
|
1279
|
+
const pool = this.connections.get(poolKey);
|
|
1280
|
+
if (!pool) throw new Error(`Pool not found for key: ${poolKey}`);
|
|
1281
|
+
pool.push(connection);
|
|
1282
|
+
if (this.poolConfig.healthCheckEnabled) globalMCPHealthMonitor.startMonitoring(config);
|
|
1283
|
+
return connection;
|
|
1284
|
+
} catch (error) {
|
|
1285
|
+
throw new MCPConnectionError(`Failed to create pooled MCP client '${config.name}'`, config.name, config.transport.type, error instanceof Error ? error : new Error(String(error)));
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
/**
|
|
1289
|
+
* Wait for an available connection
|
|
1290
|
+
*/
|
|
1291
|
+
async waitForAvailableConnection(poolKey) {
|
|
1292
|
+
const maxWaitTime = 3e4;
|
|
1293
|
+
const checkInterval = 100;
|
|
1294
|
+
const startTime = Date.now();
|
|
1295
|
+
while (Date.now() - startTime < maxWaitTime) {
|
|
1296
|
+
const pool = this.connections.get(poolKey);
|
|
1297
|
+
if (pool) {
|
|
1298
|
+
const availableConnection = pool.find((conn) => !conn.inUse);
|
|
1299
|
+
if (availableConnection) {
|
|
1300
|
+
availableConnection.inUse = true;
|
|
1301
|
+
availableConnection.lastUsed = /* @__PURE__ */ new Date();
|
|
1302
|
+
return availableConnection;
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
await new Promise((resolve) => setTimeout(resolve, checkInterval));
|
|
1306
|
+
}
|
|
1307
|
+
throw new Error(`Timeout waiting for available MCP connection (pool: ${poolKey})`);
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* Remove a connection from the pool
|
|
1311
|
+
*/
|
|
1312
|
+
async removeConnection(connection) {
|
|
1313
|
+
const poolKey = this.getPoolKey(connection.config);
|
|
1314
|
+
const pool = this.connections.get(poolKey);
|
|
1315
|
+
if (pool) {
|
|
1316
|
+
const index = pool.findIndex((conn) => conn.id === connection.id);
|
|
1317
|
+
if (index >= 0) {
|
|
1318
|
+
pool.splice(index, 1);
|
|
1319
|
+
try {
|
|
1320
|
+
await connection.client.close();
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
logWarn(`Failed to close removed pooled connection ${connection.id}`, {
|
|
1323
|
+
operation: "mcp_pool_connection_close_failed",
|
|
1324
|
+
metadata: {
|
|
1325
|
+
connectionId: connection.id,
|
|
1326
|
+
clientName: connection.config.name,
|
|
1327
|
+
error: error instanceof Error ? error.message : String(error)
|
|
1328
|
+
}
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Generate a pool key for a client configuration
|
|
1336
|
+
*/
|
|
1337
|
+
getPoolKey(config) {
|
|
1338
|
+
return `${config.transport.type}:${JSON.stringify(config.transport)}`;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Start periodic cleanup of idle connections
|
|
1342
|
+
*/
|
|
1343
|
+
startCleanupTask() {
|
|
1344
|
+
this.cleanupInterval = setInterval(() => {
|
|
1345
|
+
this.cleanupIdleConnections();
|
|
1346
|
+
}, 6e4);
|
|
1347
|
+
}
|
|
1348
|
+
/**
|
|
1349
|
+
* Clean up idle connections
|
|
1350
|
+
*/
|
|
1351
|
+
async cleanupIdleConnections() {
|
|
1352
|
+
const now = /* @__PURE__ */ new Date();
|
|
1353
|
+
const idleThreshold = new Date(now.getTime() - this.poolConfig.idleTimeoutMs);
|
|
1354
|
+
for (const [poolKey, pool] of this.connections.entries()) {
|
|
1355
|
+
const connectionsToRemove = [];
|
|
1356
|
+
for (const connection of pool) if (!connection.inUse && connection.lastUsed < idleThreshold) {
|
|
1357
|
+
if (pool.length - connectionsToRemove.length > this.poolConfig.minConnections) connectionsToRemove.push(connection);
|
|
1358
|
+
}
|
|
1359
|
+
for (const connection of connectionsToRemove) await this.removeConnection(connection);
|
|
1360
|
+
if (pool.length === 0) this.connections.delete(poolKey);
|
|
1361
|
+
}
|
|
1362
|
+
}
|
|
1363
|
+
/**
|
|
1364
|
+
* Get pool statistics
|
|
1365
|
+
*/
|
|
1366
|
+
getPoolStats() {
|
|
1367
|
+
const stats = {};
|
|
1368
|
+
for (const [poolKey, pool] of this.connections.entries()) {
|
|
1369
|
+
const inUse = pool.filter((conn) => conn.inUse).length;
|
|
1370
|
+
const idle = pool.filter((conn) => !conn.inUse).length;
|
|
1371
|
+
stats[poolKey] = {
|
|
1372
|
+
total: pool.length,
|
|
1373
|
+
inUse,
|
|
1374
|
+
idle
|
|
1375
|
+
};
|
|
1376
|
+
}
|
|
1377
|
+
return stats;
|
|
1378
|
+
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Cleanup all connections and stop background tasks
|
|
1381
|
+
*/
|
|
1382
|
+
async cleanup() {
|
|
1383
|
+
if (this.cleanupInterval) {
|
|
1384
|
+
clearInterval(this.cleanupInterval);
|
|
1385
|
+
this.cleanupInterval = void 0;
|
|
1386
|
+
}
|
|
1387
|
+
const closePromises = [];
|
|
1388
|
+
for (const pool of this.connections.values()) for (const connection of pool) closePromises.push((async () => {
|
|
1389
|
+
try {
|
|
1390
|
+
await connection.client.close();
|
|
1391
|
+
} catch (error) {
|
|
1392
|
+
logError(`Failed to close pooled connection ${connection.id}`, {
|
|
1393
|
+
operation: "mcp_pool_cleanup_failed",
|
|
1394
|
+
metadata: {
|
|
1395
|
+
connectionId: connection.id,
|
|
1396
|
+
clientName: connection.config.name
|
|
1397
|
+
},
|
|
1398
|
+
error: error instanceof Error ? error : new Error(String(error))
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
})());
|
|
1402
|
+
await Promise.all(closePromises);
|
|
1403
|
+
this.connections.clear();
|
|
1404
|
+
}
|
|
1405
|
+
};
|
|
1406
|
+
function emptyToolSet() {
|
|
1407
|
+
return {};
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Global MCP connection pool instance
|
|
1411
|
+
*/
|
|
1412
|
+
const globalMCPConnectionPool = new MCPConnectionPool();
|
|
1413
|
+
|
|
1414
|
+
//#endregion
|
|
1415
|
+
//#region src/tools/mcp/edge-runtime.ts
|
|
1416
|
+
/**
|
|
1417
|
+
* @fileoverview edge-runtime.ts
|
|
1418
|
+
*/
|
|
1419
|
+
/**
|
|
1420
|
+
* Check if we're running in edge runtime
|
|
1421
|
+
*/
|
|
1422
|
+
function isEdgeRuntime() {
|
|
1423
|
+
try {
|
|
1424
|
+
const runtimeGlobal = globalThis;
|
|
1425
|
+
return typeof process === "undefined" || process.env.VERCEL_REGION !== void 0 || typeof runtimeGlobal.WorkerGlobalScope !== "undefined" || typeof runtimeGlobal.EdgeRuntime !== "undefined";
|
|
1426
|
+
} catch {
|
|
1427
|
+
return true;
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
/**
|
|
1431
|
+
* Filter MCP configurations for edge runtime compatibility
|
|
1432
|
+
*/
|
|
1433
|
+
function getEdgeCompatibleConfigs(configs) {
|
|
1434
|
+
return configs.filter((config) => config.transport.type !== "stdio").map((config) => ({
|
|
1435
|
+
name: config.name,
|
|
1436
|
+
transport: config.transport
|
|
1437
|
+
}));
|
|
1438
|
+
}
|
|
1439
|
+
/**
|
|
1440
|
+
* Create edge-compatible MCP tools
|
|
1441
|
+
* This function works in both Node.js and edge runtimes
|
|
1442
|
+
*/
|
|
1443
|
+
async function createEdgeMCPTools(configs, options = {}) {
|
|
1444
|
+
const clients = [];
|
|
1445
|
+
const toolSets = [];
|
|
1446
|
+
const timeout = options.timeout ?? 1e4;
|
|
1447
|
+
const withTimeout = async (operation, label) => {
|
|
1448
|
+
let timer;
|
|
1449
|
+
try {
|
|
1450
|
+
return await Promise.race([operation(), new Promise((_resolve, reject) => {
|
|
1451
|
+
timer = setTimeout(() => {
|
|
1452
|
+
reject(/* @__PURE__ */ new Error(`${label} timed out after ${timeout}ms`));
|
|
1453
|
+
}, timeout);
|
|
1454
|
+
})]);
|
|
1455
|
+
} finally {
|
|
1456
|
+
if (timer) clearTimeout(timer);
|
|
1457
|
+
}
|
|
1458
|
+
};
|
|
1459
|
+
const clientPromises = configs.map(async (config) => {
|
|
1460
|
+
try {
|
|
1461
|
+
const transport = buildEdgeTransport(config.transport);
|
|
1462
|
+
const { client, toolSet } = await withTimeout(async () => {
|
|
1463
|
+
const clientInstance = await createMCPClient({ transport });
|
|
1464
|
+
return {
|
|
1465
|
+
client: clientInstance,
|
|
1466
|
+
toolSet: await clientInstance.tools()
|
|
1467
|
+
};
|
|
1468
|
+
}, `MCP client ${config.name}`);
|
|
1469
|
+
return {
|
|
1470
|
+
client,
|
|
1471
|
+
toolSet,
|
|
1472
|
+
config
|
|
1473
|
+
};
|
|
1474
|
+
} catch (error) {
|
|
1475
|
+
if (options.gracefulDegradation) {
|
|
1476
|
+
logWarn(`Failed to create edge MCP client ${config.name}`, {
|
|
1477
|
+
clientName: config.name,
|
|
1478
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1479
|
+
operation: "mcp_edge_client_creation"
|
|
1480
|
+
});
|
|
1481
|
+
return null;
|
|
1482
|
+
} else throw error;
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
const results = await Promise.all(clientPromises);
|
|
1486
|
+
for (const result of results) if (result) {
|
|
1487
|
+
clients.push(result.client);
|
|
1488
|
+
toolSets.push(result.toolSet);
|
|
1489
|
+
}
|
|
1490
|
+
const tools = Object.assign({}, ...toolSets);
|
|
1491
|
+
const closeAllClients = async () => {
|
|
1492
|
+
await Promise.all(clients.map((client) => client.close().catch((error) => {
|
|
1493
|
+
logWarn("Failed to close edge MCP client", {
|
|
1494
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1495
|
+
operation: "mcp_edge_client_close"
|
|
1496
|
+
});
|
|
1497
|
+
})));
|
|
1498
|
+
};
|
|
1499
|
+
return {
|
|
1500
|
+
tools,
|
|
1501
|
+
clients,
|
|
1502
|
+
closeAllClients
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
function buildEdgeTransport(transport) {
|
|
1506
|
+
const url = transport.url ?? transport.httpUrl;
|
|
1507
|
+
if (!url) throw new Error("HTTP URL is required for HTTP transport");
|
|
1508
|
+
const headers = { ...transport.headers };
|
|
1509
|
+
if (transport.type === "http" && transport.sessionId) headers["x-mcp-session-id"] = transport.sessionId;
|
|
1510
|
+
return {
|
|
1511
|
+
type: transport.type,
|
|
1512
|
+
url,
|
|
1513
|
+
headers: Object.keys(headers).length > 0 ? headers : void 0,
|
|
1514
|
+
authProvider: transport.authProvider
|
|
1515
|
+
};
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Pre-configured edge-compatible MCP transports
|
|
1519
|
+
*/
|
|
1520
|
+
const edgeMCPTransports = {
|
|
1521
|
+
sse: (name, url, headers) => ({
|
|
1522
|
+
name,
|
|
1523
|
+
transport: {
|
|
1524
|
+
type: "sse",
|
|
1525
|
+
url,
|
|
1526
|
+
headers
|
|
1527
|
+
}
|
|
1528
|
+
}),
|
|
1529
|
+
http: (name, httpUrl, sessionId) => ({
|
|
1530
|
+
name,
|
|
1531
|
+
transport: {
|
|
1532
|
+
type: "http",
|
|
1533
|
+
url: httpUrl,
|
|
1534
|
+
sessionId
|
|
1535
|
+
}
|
|
1536
|
+
}),
|
|
1537
|
+
zapier: (apiKey) => ({
|
|
1538
|
+
name: "zapier",
|
|
1539
|
+
transport: {
|
|
1540
|
+
type: "sse",
|
|
1541
|
+
url: `https://actions.zapier.com/mcp/${apiKey}/sse`
|
|
1542
|
+
}
|
|
1543
|
+
}),
|
|
1544
|
+
search: (baseUrl, apiKey) => ({
|
|
1545
|
+
name: "search",
|
|
1546
|
+
transport: {
|
|
1547
|
+
type: "sse",
|
|
1548
|
+
url: `${baseUrl}/mcp/sse`,
|
|
1549
|
+
headers: apiKey ? { Authorization: `Bearer ${apiKey}` } : void 0
|
|
1550
|
+
}
|
|
1551
|
+
})
|
|
1552
|
+
};
|
|
1553
|
+
/**
|
|
1554
|
+
* Environment discovery for edge runtime
|
|
1555
|
+
*/
|
|
1556
|
+
function discoverEdgeMCPServers() {
|
|
1557
|
+
const servers = [];
|
|
1558
|
+
if (typeof process !== "undefined" && process.env) {
|
|
1559
|
+
if (process.env.ZAPIER_MCP_API_KEY) servers.push(edgeMCPTransports.zapier(process.env.ZAPIER_MCP_API_KEY));
|
|
1560
|
+
const sseUrl = process.env.MCP_SSE_URL;
|
|
1561
|
+
if (sseUrl) {
|
|
1562
|
+
const headers = {};
|
|
1563
|
+
if (process.env.MCP_SSE_API_KEY) headers["Authorization"] = `Bearer ${process.env.MCP_SSE_API_KEY}`;
|
|
1564
|
+
servers.push(edgeMCPTransports.sse("custom-sse", sseUrl, headers));
|
|
1565
|
+
}
|
|
1566
|
+
const httpUrl = process.env.MCP_HTTP_URL;
|
|
1567
|
+
if (httpUrl) servers.push(edgeMCPTransports.http("custom-http", httpUrl, process.env.MCP_HTTP_SESSION_ID));
|
|
1568
|
+
}
|
|
1569
|
+
return servers;
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Smart MCP client factory that chooses the right implementation based on runtime
|
|
1573
|
+
*/
|
|
1574
|
+
async function createSmartMCPTools(nodeConfigs = [], edgeConfigs = [], options = {}) {
|
|
1575
|
+
const runtime = isEdgeRuntime() ? "edge" : "node";
|
|
1576
|
+
if (runtime === "edge") {
|
|
1577
|
+
let configs = edgeConfigs;
|
|
1578
|
+
if (options.discoverFromEnvironment) {
|
|
1579
|
+
const discovered = discoverEdgeMCPServers();
|
|
1580
|
+
configs = [...configs, ...discovered];
|
|
1581
|
+
}
|
|
1582
|
+
const edgeCompatible = getEdgeCompatibleConfigs(nodeConfigs);
|
|
1583
|
+
configs = [...configs, ...edgeCompatible];
|
|
1584
|
+
return {
|
|
1585
|
+
...await createEdgeMCPTools(configs, options),
|
|
1586
|
+
runtime
|
|
1587
|
+
};
|
|
1588
|
+
} else {
|
|
1589
|
+
const { createMCPToolsFromConfigs } = await import("./client-CpacYDIE.mjs").then((n) => n.l);
|
|
1590
|
+
let configs = nodeConfigs;
|
|
1591
|
+
if (options.discoverFromEnvironment) {
|
|
1592
|
+
const { getMCPServers } = await import("./environment-CSoJb0SW.mjs").then((n) => n.n);
|
|
1593
|
+
configs = getMCPServers(configs);
|
|
1594
|
+
}
|
|
1595
|
+
return {
|
|
1596
|
+
...await createMCPToolsFromConfigs(configs, options),
|
|
1597
|
+
runtime
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1602
|
+
//#endregion
|
|
1603
|
+
//#region src/tools/mcp/transport-selector.ts
|
|
1604
|
+
/**
|
|
1605
|
+
* Transport performance profiles
|
|
1606
|
+
*/
|
|
1607
|
+
const TRANSPORT_CHARACTERISTICS = {
|
|
1608
|
+
stdio: {
|
|
1609
|
+
latency: 9,
|
|
1610
|
+
reliability: 8,
|
|
1611
|
+
throughput: 7,
|
|
1612
|
+
scalability: 4,
|
|
1613
|
+
security: 7,
|
|
1614
|
+
complexity: 9,
|
|
1615
|
+
overhead: 9
|
|
1616
|
+
},
|
|
1617
|
+
sse: {
|
|
1618
|
+
latency: 6,
|
|
1619
|
+
reliability: 7,
|
|
1620
|
+
throughput: 6,
|
|
1621
|
+
scalability: 8,
|
|
1622
|
+
security: 6,
|
|
1623
|
+
complexity: 7,
|
|
1624
|
+
overhead: 6
|
|
1625
|
+
},
|
|
1626
|
+
http: {
|
|
1627
|
+
latency: 5,
|
|
1628
|
+
reliability: 6,
|
|
1629
|
+
throughput: 5,
|
|
1630
|
+
scalability: 9,
|
|
1631
|
+
security: 7,
|
|
1632
|
+
complexity: 8,
|
|
1633
|
+
overhead: 5
|
|
1634
|
+
}
|
|
1635
|
+
};
|
|
1636
|
+
/**
|
|
1637
|
+
* Default scoring weights based on use case
|
|
1638
|
+
*/
|
|
1639
|
+
const USE_CASE_WEIGHTS = {
|
|
1640
|
+
"real-time": {
|
|
1641
|
+
latency: .4,
|
|
1642
|
+
reliability: .2,
|
|
1643
|
+
throughput: .2,
|
|
1644
|
+
scalability: .1,
|
|
1645
|
+
security: .05,
|
|
1646
|
+
complexity: .03,
|
|
1647
|
+
overhead: .02
|
|
1648
|
+
},
|
|
1649
|
+
"batch-processing": {
|
|
1650
|
+
latency: .1,
|
|
1651
|
+
reliability: .3,
|
|
1652
|
+
throughput: .3,
|
|
1653
|
+
scalability: .2,
|
|
1654
|
+
security: .05,
|
|
1655
|
+
complexity: .03,
|
|
1656
|
+
overhead: .02
|
|
1657
|
+
},
|
|
1658
|
+
"high-availability": {
|
|
1659
|
+
latency: .15,
|
|
1660
|
+
reliability: .4,
|
|
1661
|
+
throughput: .15,
|
|
1662
|
+
scalability: .2,
|
|
1663
|
+
security: .05,
|
|
1664
|
+
complexity: .03,
|
|
1665
|
+
overhead: .02
|
|
1666
|
+
},
|
|
1667
|
+
development: {
|
|
1668
|
+
latency: .2,
|
|
1669
|
+
reliability: .2,
|
|
1670
|
+
throughput: .1,
|
|
1671
|
+
scalability: .1,
|
|
1672
|
+
security: .1,
|
|
1673
|
+
complexity: .25,
|
|
1674
|
+
overhead: .05
|
|
1675
|
+
},
|
|
1676
|
+
production: {
|
|
1677
|
+
latency: .2,
|
|
1678
|
+
reliability: .25,
|
|
1679
|
+
throughput: .2,
|
|
1680
|
+
scalability: .15,
|
|
1681
|
+
security: .15,
|
|
1682
|
+
complexity: .03,
|
|
1683
|
+
overhead: .02
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
/**
|
|
1687
|
+
* MCP Transport Selector
|
|
1688
|
+
* Intelligently selects the best transport based on use case requirements
|
|
1689
|
+
*/
|
|
1690
|
+
var MCPTransportSelector = class {
|
|
1691
|
+
/**
|
|
1692
|
+
* Select optimal transport based on criteria
|
|
1693
|
+
*/
|
|
1694
|
+
selectTransport(criteria, availableTransports = [
|
|
1695
|
+
"stdio",
|
|
1696
|
+
"sse",
|
|
1697
|
+
"http"
|
|
1698
|
+
]) {
|
|
1699
|
+
const weights = this.getWeightsForCriteria(criteria);
|
|
1700
|
+
const sortedScores = this.calculateTransportScores(weights, availableTransports).sort((a, b) => b.score - a.score);
|
|
1701
|
+
const best = sortedScores[0];
|
|
1702
|
+
if (!best) throw new Error("No transport available");
|
|
1703
|
+
const reasoningText = this.generateReasoning(criteria, best.transport);
|
|
1704
|
+
const alternatives = sortedScores.slice(1).map((result) => ({
|
|
1705
|
+
transport: result.transport,
|
|
1706
|
+
score: result.score,
|
|
1707
|
+
reason: this.getTransportReason(result.transport, criteria)
|
|
1708
|
+
}));
|
|
1709
|
+
return {
|
|
1710
|
+
recommendedTransport: best.transport,
|
|
1711
|
+
score: best.score,
|
|
1712
|
+
reasoningText,
|
|
1713
|
+
alternatives
|
|
1714
|
+
};
|
|
1715
|
+
}
|
|
1716
|
+
/**
|
|
1717
|
+
* Select optimal transport for common use cases
|
|
1718
|
+
*/
|
|
1719
|
+
selectForUseCase(useCase, availableTransports = [
|
|
1720
|
+
"stdio",
|
|
1721
|
+
"sse",
|
|
1722
|
+
"http"
|
|
1723
|
+
]) {
|
|
1724
|
+
const weights = USE_CASE_WEIGHTS[useCase];
|
|
1725
|
+
if (!weights) throw new Error(`Unknown use case: ${useCase}`);
|
|
1726
|
+
const sortedScores = this.calculateTransportScores(weights, availableTransports).sort((a, b) => b.score - a.score);
|
|
1727
|
+
const best = sortedScores[0];
|
|
1728
|
+
if (!best) throw new Error("No transport available");
|
|
1729
|
+
const reasoningText = [`Optimized for ${useCase} use case`];
|
|
1730
|
+
const alternatives = sortedScores.slice(1).map((result) => ({
|
|
1731
|
+
transport: result.transport,
|
|
1732
|
+
score: result.score,
|
|
1733
|
+
reason: `Alternative for ${useCase}`
|
|
1734
|
+
}));
|
|
1735
|
+
return {
|
|
1736
|
+
recommendedTransport: best.transport,
|
|
1737
|
+
score: best.score,
|
|
1738
|
+
reasoningText,
|
|
1739
|
+
alternatives
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
/**
|
|
1743
|
+
* Get transport recommendation for specific client config
|
|
1744
|
+
*/
|
|
1745
|
+
recommendForClient(config) {
|
|
1746
|
+
const criteria = this.inferCriteriaFromConfig(config);
|
|
1747
|
+
return this.selectTransport(criteria);
|
|
1748
|
+
}
|
|
1749
|
+
/**
|
|
1750
|
+
* Calculate weighted scores for available transports
|
|
1751
|
+
*/
|
|
1752
|
+
calculateTransportScores(weights, availableTransports) {
|
|
1753
|
+
return availableTransports.map((transport) => {
|
|
1754
|
+
const characteristics = TRANSPORT_CHARACTERISTICS[transport];
|
|
1755
|
+
if (!characteristics) return {
|
|
1756
|
+
transport,
|
|
1757
|
+
score: 0
|
|
1758
|
+
};
|
|
1759
|
+
return {
|
|
1760
|
+
transport,
|
|
1761
|
+
score: characteristics.latency * weights.latency + characteristics.reliability * weights.reliability + characteristics.throughput * weights.throughput + characteristics.scalability * weights.scalability + characteristics.security * weights.security + (10 - characteristics.complexity) * weights.complexity + (10 - characteristics.overhead) * weights.overhead
|
|
1762
|
+
};
|
|
1763
|
+
});
|
|
1764
|
+
}
|
|
1765
|
+
/**
|
|
1766
|
+
* Convert selection criteria to scoring weights
|
|
1767
|
+
*/
|
|
1768
|
+
getWeightsForCriteria(criteria) {
|
|
1769
|
+
const weights = {
|
|
1770
|
+
latency: 0,
|
|
1771
|
+
reliability: 0,
|
|
1772
|
+
throughput: 0,
|
|
1773
|
+
scalability: 0,
|
|
1774
|
+
security: 0,
|
|
1775
|
+
complexity: 0,
|
|
1776
|
+
overhead: 0
|
|
1777
|
+
};
|
|
1778
|
+
switch (criteria.latencyRequirement) {
|
|
1779
|
+
case "low":
|
|
1780
|
+
weights.latency = .1;
|
|
1781
|
+
break;
|
|
1782
|
+
case "medium":
|
|
1783
|
+
weights.latency = .25;
|
|
1784
|
+
break;
|
|
1785
|
+
case "high":
|
|
1786
|
+
weights.latency = .4;
|
|
1787
|
+
break;
|
|
1788
|
+
}
|
|
1789
|
+
switch (criteria.reliabilityRequirement) {
|
|
1790
|
+
case "basic":
|
|
1791
|
+
weights.reliability = .1;
|
|
1792
|
+
break;
|
|
1793
|
+
case "standard":
|
|
1794
|
+
weights.reliability = .25;
|
|
1795
|
+
break;
|
|
1796
|
+
case "high":
|
|
1797
|
+
weights.reliability = .4;
|
|
1798
|
+
break;
|
|
1799
|
+
}
|
|
1800
|
+
switch (criteria.throughputRequirement) {
|
|
1801
|
+
case "low":
|
|
1802
|
+
weights.throughput = .1;
|
|
1803
|
+
break;
|
|
1804
|
+
case "medium":
|
|
1805
|
+
weights.throughput = .2;
|
|
1806
|
+
break;
|
|
1807
|
+
case "high":
|
|
1808
|
+
weights.throughput = .3;
|
|
1809
|
+
break;
|
|
1810
|
+
}
|
|
1811
|
+
switch (criteria.scalabilityRequirement) {
|
|
1812
|
+
case "single":
|
|
1813
|
+
weights.scalability = .05;
|
|
1814
|
+
break;
|
|
1815
|
+
case "multiple":
|
|
1816
|
+
weights.scalability = .15;
|
|
1817
|
+
break;
|
|
1818
|
+
case "massive":
|
|
1819
|
+
weights.scalability = .3;
|
|
1820
|
+
break;
|
|
1821
|
+
}
|
|
1822
|
+
switch (criteria.securityRequirement) {
|
|
1823
|
+
case "basic":
|
|
1824
|
+
weights.security = .05;
|
|
1825
|
+
break;
|
|
1826
|
+
case "standard":
|
|
1827
|
+
weights.security = .1;
|
|
1828
|
+
break;
|
|
1829
|
+
case "high":
|
|
1830
|
+
weights.security = .2;
|
|
1831
|
+
break;
|
|
1832
|
+
}
|
|
1833
|
+
switch (criteria.networkEnvironment) {
|
|
1834
|
+
case "local":
|
|
1835
|
+
weights.complexity = .15;
|
|
1836
|
+
weights.overhead = .1;
|
|
1837
|
+
break;
|
|
1838
|
+
case "lan":
|
|
1839
|
+
weights.reliability = Math.min(weights.reliability + .1, .5);
|
|
1840
|
+
break;
|
|
1841
|
+
case "wan":
|
|
1842
|
+
case "internet":
|
|
1843
|
+
weights.scalability = Math.min(weights.scalability + .1, .4);
|
|
1844
|
+
weights.security = Math.min(weights.security + .1, .3);
|
|
1845
|
+
break;
|
|
1846
|
+
}
|
|
1847
|
+
const total = Object.values(weights).reduce((sum, weight) => sum + weight, 0);
|
|
1848
|
+
if (total > 0) Object.keys(weights).forEach((key) => {
|
|
1849
|
+
weights[key] /= total;
|
|
1850
|
+
});
|
|
1851
|
+
return weights;
|
|
1852
|
+
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Generate reasoning for transport selection
|
|
1855
|
+
*/
|
|
1856
|
+
generateReasoning(criteria, selectedTransport) {
|
|
1857
|
+
const reasoning = [];
|
|
1858
|
+
const characteristics = TRANSPORT_CHARACTERISTICS[selectedTransport];
|
|
1859
|
+
if (!characteristics) return reasoning;
|
|
1860
|
+
if (criteria.latencyRequirement === "high" && selectedTransport === "stdio") reasoning.push("STDIO selected for lowest latency via direct IPC");
|
|
1861
|
+
if (criteria.scalabilityRequirement === "massive" && selectedTransport === "http") reasoning.push("HTTP selected for maximum scalability in distributed environments");
|
|
1862
|
+
if (criteria.networkEnvironment === "local" && selectedTransport === "stdio") reasoning.push("STDIO optimal for local process communication");
|
|
1863
|
+
if (criteria.reliabilityRequirement === "high") reasoning.push(`Selected transport provides reliability score of ${characteristics.reliability}/10`);
|
|
1864
|
+
const strengths = [];
|
|
1865
|
+
if (characteristics.latency >= 8) strengths.push("excellent latency");
|
|
1866
|
+
if (characteristics.reliability >= 8) strengths.push("high reliability");
|
|
1867
|
+
if (characteristics.throughput >= 8) strengths.push("high throughput");
|
|
1868
|
+
if (characteristics.scalability >= 8) strengths.push("excellent scalability");
|
|
1869
|
+
if (characteristics.security >= 8) strengths.push("strong security");
|
|
1870
|
+
if (characteristics.complexity >= 8) strengths.push("simple setup");
|
|
1871
|
+
if (strengths.length > 0) reasoning.push(`Transport provides: ${strengths.join(", ")}`);
|
|
1872
|
+
return reasoning.length > 0 ? reasoning : ["Selected based on overall optimization criteria"];
|
|
1873
|
+
}
|
|
1874
|
+
/**
|
|
1875
|
+
* Get reason for alternative transport
|
|
1876
|
+
*/
|
|
1877
|
+
getTransportReason(transport, criteria) {
|
|
1878
|
+
switch (transport) {
|
|
1879
|
+
case "stdio": return "Best for low-latency local communication";
|
|
1880
|
+
case "sse": return "Good balance of features with streaming support";
|
|
1881
|
+
case "http": return "Best for scalable, distributed architectures";
|
|
1882
|
+
default: return "Alternative transport option";
|
|
1883
|
+
}
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Infer selection criteria from existing client configuration
|
|
1887
|
+
*/
|
|
1888
|
+
inferCriteriaFromConfig(config) {
|
|
1889
|
+
const criteria = {
|
|
1890
|
+
latencyRequirement: "medium",
|
|
1891
|
+
reliabilityRequirement: "standard",
|
|
1892
|
+
throughputRequirement: "medium",
|
|
1893
|
+
networkEnvironment: "local",
|
|
1894
|
+
securityRequirement: "standard",
|
|
1895
|
+
scalabilityRequirement: "multiple"
|
|
1896
|
+
};
|
|
1897
|
+
switch (config.transport.type) {
|
|
1898
|
+
case "stdio":
|
|
1899
|
+
criteria.networkEnvironment = "local";
|
|
1900
|
+
criteria.latencyRequirement = "high";
|
|
1901
|
+
criteria.scalabilityRequirement = "single";
|
|
1902
|
+
break;
|
|
1903
|
+
case "sse":
|
|
1904
|
+
criteria.networkEnvironment = "lan";
|
|
1905
|
+
criteria.throughputRequirement = "high";
|
|
1906
|
+
break;
|
|
1907
|
+
case "http":
|
|
1908
|
+
criteria.networkEnvironment = "internet";
|
|
1909
|
+
criteria.scalabilityRequirement = "massive";
|
|
1910
|
+
break;
|
|
1911
|
+
}
|
|
1912
|
+
if (config.gracefulDegradation) criteria.reliabilityRequirement = "high";
|
|
1913
|
+
if (config.timeoutMs && config.timeoutMs < 5e3) criteria.latencyRequirement = "high";
|
|
1914
|
+
return criteria;
|
|
1915
|
+
}
|
|
1916
|
+
};
|
|
1917
|
+
/**
|
|
1918
|
+
* Global transport selector instance
|
|
1919
|
+
*/
|
|
1920
|
+
const globalTransportSelector = new MCPTransportSelector();
|
|
1921
|
+
/**
|
|
1922
|
+
* Convenience function to get transport recommendation
|
|
1923
|
+
*/
|
|
1924
|
+
function selectOptimalTransport(criteria, availableTransports) {
|
|
1925
|
+
return globalTransportSelector.selectTransport(criteria, availableTransports);
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* Convenience function to get transport recommendation for use case
|
|
1929
|
+
*/
|
|
1930
|
+
function selectTransportForUseCase(useCase, availableTransports) {
|
|
1931
|
+
return globalTransportSelector.selectForUseCase(useCase, availableTransports);
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
//#endregion
|
|
1935
|
+
export { testMCPConnectivity as C, createMCPStreamLifecycleManager as D, StreamLifecyclePhase as E, createMCPToolsWithStreamLifecycle as S, MCPStreamLifecycleManager as T, MCPConnectionManager as _, createEdgeMCPTools as a, createMCPToolsForStreamText as b, edgeMCPTransports as c, DEFAULT_POOL_CONFIG as d, MCPConnectionPool as f, globalMCPToolCache as g, MCPToolCache as h, selectTransportForUseCase as i, getEdgeCompatibleConfigs as l, DEFAULT_CACHE_CONFIG as m, globalTransportSelector as n, createSmartMCPTools as o, globalMCPConnectionPool as p, selectOptimalTransport as r, discoverEdgeMCPServers as s, MCPTransportSelector as t, isEdgeRuntime as u, createPooledMCPTools as v, DEFAULT_STREAM_LIFECYCLE_CONFIG as w, createMCPToolsWithDefaults as x, getGlobalConnectionManager as y };
|
|
1936
|
+
//# sourceMappingURL=transport-selector-D-Ib05X1.mjs.map
|