@retrivora-ai/rag-engine 2.4.2 → 2.4.5

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.
Files changed (140) hide show
  1. package/dist/{BatchProcessor-zbQMaZHm.d.mts → BatchProcessor-Csy_K1qQ.d.mts} +2 -0
  2. package/dist/{BatchProcessor-D42E706a.d.ts → BatchProcessor-Dg18zZGk.d.ts} +2 -0
  3. package/dist/handlers/index.js +31 -5
  4. package/dist/handlers/index.mjs +31 -5
  5. package/dist/index.d.mts +3 -3
  6. package/dist/index.d.ts +3 -3
  7. package/dist/index.js +41 -21
  8. package/dist/index.min.css +2 -0
  9. package/dist/index.mjs +41 -21
  10. package/dist/server.d.mts +2 -2
  11. package/dist/server.d.ts +2 -2
  12. package/dist/server.js +32 -5
  13. package/dist/server.mjs +32 -5
  14. package/package.json +5 -4
  15. package/src/LicensedRetrivora.ts +0 -278
  16. package/src/app/api/chat/route.ts +0 -4
  17. package/src/app/api/health/route.ts +0 -5
  18. package/src/app/api/ingest/route.ts +0 -27
  19. package/src/app/api/suggestions/route.ts +0 -5
  20. package/src/app/api/upload/route.ts +0 -5
  21. package/src/app/constants.tsx +0 -270
  22. package/src/app/favicon.ico +0 -0
  23. package/src/app/globals.css +0 -449
  24. package/src/app/layout.tsx +0 -22
  25. package/src/app/page.tsx +0 -64
  26. package/src/app/types.ts +0 -30
  27. package/src/browser.tsx +0 -139
  28. package/src/components/ChatWidget.tsx +0 -393
  29. package/src/components/ChatWindow.tsx +0 -952
  30. package/src/components/CodeViewer.tsx +0 -56
  31. package/src/components/ConfigProvider.tsx +0 -123
  32. package/src/components/DocumentUpload.tsx +0 -354
  33. package/src/components/DynamicChart.tsx +0 -297
  34. package/src/components/HourglassLoader.tsx +0 -87
  35. package/src/components/MarkdownComponents.tsx +0 -186
  36. package/src/components/MessageBubble.tsx +0 -498
  37. package/src/components/ObservabilityPanel.tsx +0 -374
  38. package/src/components/ProductCard.tsx +0 -107
  39. package/src/components/ProductCarousel.tsx +0 -97
  40. package/src/components/SourceCard.tsx +0 -61
  41. package/src/components/ThemeProvider.tsx +0 -8
  42. package/src/components/ThemeToggle.tsx +0 -29
  43. package/src/components/ThinkingBlock.tsx +0 -75
  44. package/src/components/UIDispatcher.tsx +0 -342
  45. package/src/components/VisualizationRenderer.tsx +0 -621
  46. package/src/components/constants.tsx +0 -503
  47. package/src/config/ConfigBuilder.ts +0 -285
  48. package/src/config/EmbeddingStrategy.ts +0 -148
  49. package/src/config/LicenseConfigResolver.ts +0 -298
  50. package/src/config/RagConfig.ts +0 -328
  51. package/src/config/UniversalProfiles.ts +0 -82
  52. package/src/config/constants.ts +0 -64
  53. package/src/config/serverConfig.ts +0 -378
  54. package/src/config/uiConstants.ts +0 -47
  55. package/src/core/BatchProcessor.ts +0 -385
  56. package/src/core/CircuitBreaker.ts +0 -118
  57. package/src/core/ConfigFetcher.ts +0 -220
  58. package/src/core/ConfigResolver.ts +0 -165
  59. package/src/core/ConfigValidator.ts +0 -197
  60. package/src/core/DatabaseStorage.ts +0 -526
  61. package/src/core/FreeTierLimitsGuard.ts +0 -281
  62. package/src/core/LLMRouter.ts +0 -79
  63. package/src/core/LangChainAgent.ts +0 -132
  64. package/src/core/LicenseValidator.ts +0 -284
  65. package/src/core/LicenseVerifier.ts +0 -261
  66. package/src/core/MultiAgentCoordinator.ts +0 -239
  67. package/src/core/Pipeline.ts +0 -1279
  68. package/src/core/PluginManager.ts +0 -277
  69. package/src/core/ProjectSettings.ts +0 -247
  70. package/src/core/ProviderHealthCheck.ts +0 -133
  71. package/src/core/ProviderInterfaces.ts +0 -37
  72. package/src/core/ProviderRegistry.ts +0 -156
  73. package/src/core/QueryProcessor.ts +0 -399
  74. package/src/core/Retrivora.ts +0 -98
  75. package/src/core/VectorPlugin.ts +0 -193
  76. package/src/core/mcp.ts +0 -261
  77. package/src/exceptions/index.ts +0 -131
  78. package/src/handlers/index.ts +0 -1625
  79. package/src/hooks/useHydrated.ts +0 -13
  80. package/src/hooks/useProjectSettings.ts +0 -105
  81. package/src/hooks/useRagChat.ts +0 -436
  82. package/src/hooks/useStoredMessages.ts +0 -64
  83. package/src/index.css +0 -4269
  84. package/src/index.ts +0 -137
  85. package/src/lib/plugin.ts +0 -24
  86. package/src/llm/ILLMProvider.ts +0 -60
  87. package/src/llm/LLMFactory.ts +0 -141
  88. package/src/llm/providers/AnthropicProvider.ts +0 -215
  89. package/src/llm/providers/GeminiProvider.ts +0 -311
  90. package/src/llm/providers/GroqProvider.ts +0 -184
  91. package/src/llm/providers/OllamaProvider.ts +0 -232
  92. package/src/llm/providers/OpenAIProvider.ts +0 -188
  93. package/src/llm/providers/QwenProvider.ts +0 -199
  94. package/src/llm/providers/UniversalLLMAdapter.ts +0 -422
  95. package/src/llm/utils.ts +0 -46
  96. package/src/providers/graphdb/BaseGraphProvider.ts +0 -43
  97. package/src/providers/graphdb/SimpleGraphProvider.ts +0 -66
  98. package/src/providers/vectordb/BaseVectorProvider.ts +0 -98
  99. package/src/providers/vectordb/ChromaDBProvider.ts +0 -130
  100. package/src/providers/vectordb/MilvusProvider.ts +0 -134
  101. package/src/providers/vectordb/MongoDBProvider.ts +0 -250
  102. package/src/providers/vectordb/MultiTablePostgresProvider.ts +0 -461
  103. package/src/providers/vectordb/PineconeProvider.ts +0 -295
  104. package/src/providers/vectordb/PostgreSQLProvider.ts +0 -227
  105. package/src/providers/vectordb/QdrantProvider.ts +0 -294
  106. package/src/providers/vectordb/RedisProvider.ts +0 -105
  107. package/src/providers/vectordb/UniversalVectorProvider.ts +0 -221
  108. package/src/providers/vectordb/WeaviateProvider.ts +0 -172
  109. package/src/rag/DocumentChunker.ts +0 -144
  110. package/src/rag/EntityExtractor.ts +0 -90
  111. package/src/rag/LlamaIndexIngestor.ts +0 -60
  112. package/src/rag/Reranker.ts +0 -106
  113. package/src/rendering/IntentClassifier.ts +0 -167
  114. package/src/rendering/RendererRegistry.ts +0 -164
  115. package/src/rendering/RuleEngine.ts +0 -67
  116. package/src/rendering/VisualizationDecisionEngine.ts +0 -164
  117. package/src/rendering/__tests__/VisualizationDecisionEngine.test.ts +0 -237
  118. package/src/rendering/index.ts +0 -12
  119. package/src/rendering/rules/Rule1SpecificInfoRule.ts +0 -28
  120. package/src/rendering/rules/Rule2ComparisonRule.ts +0 -24
  121. package/src/rendering/rules/Rule3ProductDiscoveryRule.ts +0 -28
  122. package/src/rendering/rules/Rule4AnalyticalRule.ts +0 -38
  123. package/src/rendering/rules/Rule5MixedResponseRule.ts +0 -29
  124. package/src/rendering/rules/Rule6SmallResultSetRule.ts +0 -24
  125. package/src/rendering/rules/Rule7LargeTableRule.ts +0 -35
  126. package/src/rendering/types.ts +0 -96
  127. package/src/server.ts +0 -156
  128. package/src/tailwind.css +0 -194
  129. package/src/telemetry/TelemetryService.ts +0 -330
  130. package/src/types/chat.ts +0 -89
  131. package/src/types/index.ts +0 -278
  132. package/src/types/pdf-parse.d.ts +0 -13
  133. package/src/types/props.ts +0 -169
  134. package/src/utils/DocumentParser.ts +0 -111
  135. package/src/utils/ProductExtractor.ts +0 -350
  136. package/src/utils/SchemaMapper.ts +0 -176
  137. package/src/utils/UITransformer.ts +0 -1812
  138. package/src/utils/synonyms.ts +0 -80
  139. package/src/utils/templateUtils.ts +0 -78
  140. package/src/version.ts +0 -6
@@ -1,193 +0,0 @@
1
- import { RagConfig } from '../config/RagConfig';
2
- import { ConfigResolver } from './ConfigResolver';
3
- import { ConfigValidator } from './ConfigValidator';
4
- import { Pipeline } from './Pipeline';
5
- import { ProviderHealthCheck, HealthCheckResult } from './ProviderHealthCheck';
6
- import { IngestDocument, ChatResponse } from '../types';
7
- import { ChatMessage } from '../types';
8
- import { LicenseVerifier } from './LicenseVerifier';
9
- import { wrapError, RetrivoraErrorCode } from '../exceptions';
10
- import { FreeTierLimitsGuard } from './FreeTierLimitsGuard';
11
-
12
- /**
13
- * VectorPlugin — main orchestrator class.
14
- * This is the primary interface for host applications.
15
- *
16
- * Features:
17
- * - Configuration resolution from host + environment
18
- * - Configuration validation with detailed error messages
19
- * - Provider health checks before initialization
20
- * - Multi-provider support (Vector DBs & LLMs)
21
- * - Per-tenant data isolation via namespacing
22
- */
23
- export class VectorPlugin {
24
- private config: RagConfig;
25
- private pipeline: Pipeline;
26
- private validationPromise: Promise<void>;
27
-
28
- constructor(hostConfig?: Partial<RagConfig>) {
29
- const resolvedConfig = ConfigResolver.resolve(hostConfig);
30
- this.config = resolvedConfig;
31
-
32
- // Start validation early
33
- this.validationPromise = (async () => {
34
- await ConfigValidator.validateAndThrow(resolvedConfig);
35
- await LicenseVerifier.verifyAsync(
36
- resolvedConfig.licenseKey,
37
- resolvedConfig.projectId,
38
- resolvedConfig.vectorDb?.provider
39
- );
40
- })();
41
- // Prevent unhandled promise rejection warning
42
- this.validationPromise.catch(() => {});
43
-
44
- this.pipeline = new Pipeline(resolvedConfig);
45
- }
46
-
47
- /**
48
- * Get the current resolved configuration.
49
- */
50
- getConfig(): RagConfig {
51
- return this.config;
52
- }
53
-
54
- /**
55
- * Get the initialized LLM provider (available after the first request).
56
- * Used by handlers to pass to UITransformer.analyzeAndDecide() for
57
- * LLM-driven visualization decisions.
58
- */
59
- getLLMProvider() {
60
- return this.pipeline.getLLMProvider();
61
- }
62
-
63
- /**
64
- * Perform pre-flight health checks on all configured providers.
65
- * Useful to verify connectivity before running operations.
66
- *
67
- * @returns Health status for vector DB, LLM, and embedding providers
68
- */
69
- async checkHealth(): Promise<{
70
- vectorDb: HealthCheckResult;
71
- llm: HealthCheckResult;
72
- embedding?: HealthCheckResult;
73
- allHealthy: boolean;
74
- }> {
75
- return ProviderHealthCheck.checkAll(
76
- this.config.vectorDb,
77
- this.config.llm,
78
- this.config.embedding
79
- );
80
- }
81
-
82
- private estimateInputTokens(message: string, history: ChatMessage[] = []): number {
83
- const allContent =
84
- message.length +
85
- history.reduce((acc, m) => acc + ((m as any)?.content?.length || (m as any)?.text?.length || 0), 0);
86
- return Math.ceil(allContent / 4);
87
- }
88
-
89
- /**
90
- * Run a chat query.
91
- */
92
- async chat(message: string, history: ChatMessage[] = [], namespace?: string): Promise<ChatResponse> {
93
- try {
94
- await this.validationPromise;
95
- } catch (err) {
96
- throw wrapError(err, 'CONFIGURATION_ERROR');
97
- }
98
- try {
99
- const inputTokens = this.estimateInputTokens(message, history);
100
- const tokenCheck = (FreeTierLimitsGuard as any).checkRequestAllowed({
101
- operationType: 'chat',
102
- inputTokens,
103
- });
104
- if (!tokenCheck.allowed && tokenCheck.reason?.toLowerCase().includes('token')) {
105
- throw wrapError(new Error(tokenCheck.reason), 'RATE_LIMITED');
106
- }
107
- return await this.pipeline.ask(message, history, namespace);
108
- } catch (err) {
109
- const msg = String(err);
110
- let defaultCode: RetrivoraErrorCode = 'RETRIEVAL_FAILED';
111
- if (msg.includes('Embed') || msg.includes('embed')) {
112
- defaultCode = 'EMBEDDING_FAILED';
113
- }
114
- if (msg.toLowerCase().includes('token limit')) {
115
- defaultCode = 'RATE_LIMITED';
116
- }
117
- throw wrapError(err, defaultCode);
118
- }
119
- }
120
-
121
- /**
122
- * Run a streaming chat query.
123
- */
124
- async *chatStream(message: string, history: ChatMessage[] = [], namespace?: string) {
125
- try {
126
- await this.validationPromise;
127
- } catch (err) {
128
- throw wrapError(err, 'CONFIGURATION_ERROR');
129
- }
130
- try {
131
- const inputTokens = this.estimateInputTokens(message, history);
132
- const tokenCheck = (FreeTierLimitsGuard as any).checkRequestAllowed({
133
- operationType: 'chat_stream',
134
- inputTokens,
135
- });
136
- if (!tokenCheck.allowed && tokenCheck.reason?.toLowerCase().includes('token')) {
137
- throw wrapError(new Error(tokenCheck.reason), 'RATE_LIMITED');
138
- }
139
- const stream = this.pipeline.askStream(message, history, namespace);
140
- for await (const chunk of stream) {
141
- yield chunk;
142
- }
143
- } catch (err) {
144
- const msg = String(err);
145
- let defaultCode: RetrivoraErrorCode = 'RETRIEVAL_FAILED';
146
- if (msg.includes('Embed') || msg.includes('embed')) {
147
- defaultCode = 'EMBEDDING_FAILED';
148
- }
149
- if (msg.toLowerCase().includes('token limit')) {
150
- defaultCode = 'RATE_LIMITED';
151
- }
152
- throw wrapError(err, defaultCode);
153
- }
154
- }
155
-
156
- /**
157
- * Ingest documents into the vector database.
158
- */
159
- async ingest(documents: IngestDocument[], namespace?: string): Promise<Array<{ docId: string | number; chunksIngested: number }>> {
160
- try {
161
- await this.validationPromise;
162
- } catch (err) {
163
- throw wrapError(err, 'CONFIGURATION_ERROR');
164
- }
165
- try {
166
- return await this.pipeline.ingest(documents, namespace);
167
- } catch (err) {
168
- const msg = String(err);
169
- let defaultCode: RetrivoraErrorCode = 'RETRIEVAL_FAILED';
170
- if (msg.includes('Embed') || msg.includes('embed')) {
171
- defaultCode = 'EMBEDDING_FAILED';
172
- }
173
- throw wrapError(err, defaultCode);
174
- }
175
- }
176
-
177
- /**
178
- * Get auto-suggestions based on a query prefix.
179
- */
180
- async getSuggestions(query: string, namespace?: string): Promise<string[]> {
181
- try {
182
- await this.validationPromise;
183
- } catch (err) {
184
- throw wrapError(err, 'CONFIGURATION_ERROR');
185
- }
186
- try {
187
- return await this.pipeline.getSuggestions(query, namespace);
188
- } catch {
189
- return [];
190
- }
191
- }
192
- }
193
-
package/src/core/mcp.ts DELETED
@@ -1,261 +0,0 @@
1
- import { spawn, ChildProcess } from 'child_process';
2
- import { MCPServerConfig } from '../config/RagConfig';
3
-
4
- interface MCPTool {
5
- name: string;
6
- description?: string;
7
- inputSchema: any;
8
- }
9
-
10
- interface MCPCallResult {
11
- content: Array<{ type: string; text?: string;[key: string]: any }>;
12
- isError?: boolean;
13
- }
14
-
15
- export class MCPClient {
16
- private childProcess?: ChildProcess;
17
- private sseUrl?: string;
18
- private messageIdCounter = 0;
19
- private pendingRequests = new Map<number, { resolve: (val: any) => void; reject: (err: any) => void }>();
20
- private stdioBuffer = '';
21
- private initialized = false;
22
-
23
- constructor(private config: MCPServerConfig) { }
24
-
25
- private getNextMessageId(): number {
26
- return ++this.messageIdCounter;
27
- }
28
-
29
- /**
30
- * Connect and initialize the MCP server connection.
31
- */
32
- async connect(): Promise<void> {
33
- if (this.initialized) return;
34
-
35
- if (this.config.transport === 'stdio') {
36
- await this.connectStdio();
37
- } else {
38
- await this.connectSSE();
39
- }
40
-
41
- // Call initialize
42
- try {
43
- const response = await this.sendJsonRpc('initialize', {
44
- protocolVersion: '2024-11-05',
45
- capabilities: {},
46
- clientInfo: {
47
- name: 'retrivora-sdk',
48
- version: '1.0.0',
49
- },
50
- });
51
-
52
- // Send initialized notification
53
- await this.sendNotification('notifications/initialized');
54
- this.initialized = true;
55
- //console.log(`[MCPClient] Connected and initialized server "${this.config.name}" successfully.`);
56
- } catch (err: any) {
57
- this.disconnect();
58
- throw new Error(`[MCPClient] Failed to initialize server "${this.config.name}": ${err.message}`);
59
- }
60
- }
61
-
62
- private async connectStdio(): Promise<void> {
63
- const cmd = this.config.command;
64
- if (!cmd) {
65
- throw new Error(`[MCPClient] Command option is required for stdio transport on "${this.config.name}"`);
66
- }
67
-
68
- const args = this.config.args || [];
69
- const env = { ...process.env, ...(this.config.env || {}) };
70
-
71
- this.childProcess = spawn(cmd, args, { env, shell: true });
72
-
73
- if (!this.childProcess || !this.childProcess.stdout || !this.childProcess.stdin) {
74
- throw new Error(`[MCPClient] Failed to spawn stdio child process for "${this.config.name}"`);
75
- }
76
-
77
- this.childProcess.stdout.on('data', (data: Buffer) => {
78
- this.stdioBuffer += data.toString('utf-8');
79
- this.processStdioLines();
80
- });
81
-
82
- this.childProcess.stderr?.on('data', (data: Buffer) => {
83
- console.warn(`[MCPClient] [stderr] [${this.config.name}]:`, data.toString('utf-8'));
84
- });
85
-
86
- this.childProcess.on('close', (code) => {
87
- //console.log(`[MCPClient] Connection closed for "${this.config.name}" with exit code: ${code}`);
88
- this.disconnect();
89
- });
90
-
91
- // Wait a brief tick to ensure stdout is set up
92
- await new Promise((resolve) => setTimeout(resolve, 100));
93
- }
94
-
95
- private processStdioLines() {
96
- let newlineIndex: number;
97
- while ((newlineIndex = this.stdioBuffer.indexOf('\n')) !== -1) {
98
- const line = this.stdioBuffer.substring(0, newlineIndex).trim();
99
- this.stdioBuffer = this.stdioBuffer.substring(newlineIndex + 1);
100
-
101
- if (!line) continue;
102
-
103
- try {
104
- const payload = JSON.parse(line);
105
- if (payload.id !== undefined) {
106
- const req = this.pendingRequests.get(Number(payload.id));
107
- if (req) {
108
- this.pendingRequests.delete(Number(payload.id));
109
- if (payload.error) {
110
- req.reject(new Error(payload.error.message || JSON.stringify(payload.error)));
111
- } else {
112
- req.resolve(payload.result);
113
- }
114
- }
115
- }
116
- } catch (e) {
117
- console.warn(`[MCPClient] Error parsing stdio JSON-RPC line from "${this.config.name}":`, e, 'Line content:', line);
118
- }
119
- }
120
- }
121
-
122
- private async connectSSE(): Promise<void> {
123
- if (!this.config.url) {
124
- throw new Error(`[MCPClient] URL is required for sse transport on "${this.config.name}"`);
125
- }
126
-
127
- // Set up standard SSE handshake / SSE connection
128
- // In serverless contexts, we pull initial SSE transport configuration,
129
- // and route HTTP POSTs to the client URL.
130
- this.sseUrl = this.config.url;
131
- }
132
-
133
- private async sendJsonRpc(method: string, params: any): Promise<any> {
134
- const id = this.getNextMessageId();
135
- const request = {
136
- jsonrpc: '2.0',
137
- id,
138
- method,
139
- params,
140
- };
141
-
142
- if (this.config.transport === 'stdio') {
143
- if (!this.childProcess || !this.childProcess.stdin) {
144
- throw new Error(`[MCPClient] Server "${this.config.name}" is not connected (stdio process missing)`);
145
- }
146
- return new Promise((resolve, reject) => {
147
- this.pendingRequests.set(id, { resolve, reject });
148
- this.childProcess!.stdin!.write(JSON.stringify(request) + '\n', 'utf-8');
149
- });
150
- } else {
151
- // SSE / HTTP POST fallback for cloud/serverless setups
152
- if (!this.sseUrl) {
153
- throw new Error(`[MCPClient] Server "${this.config.name}" SSE URL is not initialized`);
154
- }
155
- const response = await fetch(this.sseUrl, {
156
- method: 'POST',
157
- headers: { 'Content-Type': 'application/json' },
158
- body: JSON.stringify(request),
159
- });
160
- if (!response.ok) {
161
- throw new Error(`SSE JSON-RPC POST failed with status ${response.status}`);
162
- }
163
- const payload = await response.json();
164
- if (payload.error) {
165
- throw new Error(payload.error.message || JSON.stringify(payload.error));
166
- }
167
- return payload.result;
168
- }
169
- }
170
-
171
- private async sendNotification(method: string, params?: any): Promise<void> {
172
- const notification = {
173
- jsonrpc: '2.0',
174
- method,
175
- params,
176
- };
177
-
178
- if (this.config.transport === 'stdio') {
179
- if (this.childProcess?.stdin) {
180
- this.childProcess.stdin.write(JSON.stringify(notification) + '\n', 'utf-8');
181
- }
182
- } else if (this.sseUrl) {
183
- await fetch(this.sseUrl, {
184
- method: 'POST',
185
- headers: { 'Content-Type': 'application/json' },
186
- body: JSON.stringify(notification),
187
- }).catch(err => console.warn('[MCPClient] Failed to send notification over SSE:', err));
188
- }
189
- }
190
-
191
- /**
192
- * List all tools offered by the MCP server.
193
- */
194
- async listTools(): Promise<MCPTool[]> {
195
- await this.connect();
196
- const result = await this.sendJsonRpc('tools/list', {});
197
- return result?.tools || [];
198
- }
199
-
200
- /**
201
- * Execute a tool on the MCP server.
202
- */
203
- async callTool(name: string, args: Record<string, any> = {}): Promise<MCPCallResult> {
204
- await this.connect();
205
- return await this.sendJsonRpc('tools/call', { name, arguments: args });
206
- }
207
-
208
- disconnect() {
209
- this.initialized = false;
210
- this.pendingRequests.forEach(req => req.reject(new Error('MCPClient disconnected')));
211
- this.pendingRequests.clear();
212
-
213
- if (this.childProcess) {
214
- try {
215
- this.childProcess.kill();
216
- } catch { /* silent */ }
217
- this.childProcess = undefined;
218
- }
219
- }
220
- }
221
-
222
- export class MCPRegistry {
223
- private clients: MCPClient[] = [];
224
-
225
- constructor(servers: MCPServerConfig[] = []) {
226
- this.clients = servers.map(cfg => new MCPClient(cfg));
227
- }
228
-
229
- async getAllTools(): Promise<Array<{ serverName: string; tool: MCPTool }>> {
230
- const list: Array<{ serverName: string; tool: MCPTool }> = [];
231
- await Promise.all(
232
- this.clients.map(async (client) => {
233
- try {
234
- const tools = await client.listTools();
235
- tools.forEach(t => list.push({ serverName: client['config'].name, tool: t }));
236
- } catch (e) {
237
- console.warn(`[MCPRegistry] Failed to fetch tools from server "${client['config'].name}":`, e);
238
- }
239
- })
240
- );
241
- return list;
242
- }
243
-
244
- async callTool(toolName: string, args: Record<string, any> = {}): Promise<MCPCallResult> {
245
- // Find client hosting this tool. (In standard MCP, tool names are unique per server block)
246
- // We will search across all connected clients.
247
- for (const client of this.clients) {
248
- try {
249
- const tools = await client.listTools();
250
- if (tools.some(t => t.name === toolName)) {
251
- return await client.callTool(toolName, args);
252
- }
253
- } catch { /* silent fallback */ }
254
- }
255
- throw new Error(`[MCPRegistry] Tool "${toolName}" not found on any registered MCP server.`);
256
- }
257
-
258
- disconnectAll() {
259
- this.clients.forEach(c => c.disconnect());
260
- }
261
- }
@@ -1,131 +0,0 @@
1
- /**
2
- * Named SDK exceptions make failures machine-readable for host applications.
3
- */
4
-
5
- export type RetrivoraErrorCode =
6
- | 'PROVIDER_NOT_FOUND'
7
- | 'EMBEDDING_FAILED'
8
- | 'RETRIEVAL_FAILED'
9
- | 'RATE_LIMITED'
10
- | 'CONFIGURATION_ERROR'
11
- | 'AUTHENTICATION_ERROR'
12
- | 'SDK_VERSION_UNSUPPORTED'
13
- | 'LICENSE_VALIDATION_ERROR';
14
-
15
- export class RetrivoraError extends Error {
16
- readonly code: RetrivoraErrorCode;
17
- readonly details?: unknown;
18
-
19
- constructor(message: string, code: RetrivoraErrorCode, details?: unknown) {
20
- super(message);
21
- this.name = new.target.name;
22
- this.code = code;
23
- this.details = details;
24
- }
25
- }
26
-
27
- export class ProviderNotFoundException extends RetrivoraError {
28
- constructor(providerType: string, provider: string, details?: unknown) {
29
- super(`Unsupported ${providerType} provider: ${provider}`, 'PROVIDER_NOT_FOUND', details);
30
- }
31
- }
32
-
33
- export class EmbeddingFailedException extends RetrivoraError {
34
- constructor(message = 'Embedding generation failed', details?: unknown) {
35
- super(message, 'EMBEDDING_FAILED', details);
36
- }
37
- }
38
-
39
- export class RetrievalException extends RetrivoraError {
40
- constructor(message = 'Retrieval failed', details?: unknown) {
41
- super(message, 'RETRIEVAL_FAILED', details);
42
- }
43
- }
44
-
45
- export class RateLimitException extends RetrivoraError {
46
- constructor(message = 'Provider rate limit exceeded', details?: unknown) {
47
- super(message, 'RATE_LIMITED', details);
48
- }
49
- }
50
-
51
- export class ConfigurationException extends RetrivoraError {
52
- constructor(message: string, details?: unknown) {
53
- super(message, 'CONFIGURATION_ERROR', details);
54
- }
55
- }
56
-
57
- export class AuthenticationException extends RetrivoraError {
58
- constructor(message = 'Provider authentication failed', details?: unknown) {
59
- super(message, 'AUTHENTICATION_ERROR', details);
60
- }
61
- }
62
-
63
- export class SDKVersionUnsupportedError extends RetrivoraError {
64
- constructor(message = 'This SDK version is no longer supported.', details?: unknown) {
65
- super(message, 'SDK_VERSION_UNSUPPORTED', details);
66
- }
67
- }
68
-
69
- export class LicenseValidationError extends RetrivoraError {
70
- constructor(message = 'License validation failed.', details?: unknown) {
71
- super(message, 'LICENSE_VALIDATION_ERROR', details);
72
- }
73
- }
74
-
75
- /**
76
- * Wraps any unknown error into an appropriate RetrivoraError subclass.
77
- */
78
- export function wrapError(
79
- err: unknown,
80
- defaultCode: RetrivoraErrorCode,
81
- defaultMessage?: string,
82
- ): RetrivoraError {
83
- if (err instanceof RetrivoraError) {
84
- return err;
85
- }
86
-
87
- const error = err as any;
88
- const message = error?.message || defaultMessage || String(err);
89
- const status = error?.status || error?.statusCode || error?.response?.status;
90
- const code = error?.code;
91
-
92
- // 1. Rate Limit Recognition
93
- if (status === 429 || /rate[- ]?limit/i.test(message) || code === 'RATE_LIMIT_EXCEEDED') {
94
- return new RateLimitException(message, err);
95
- }
96
-
97
- // 2. Authentication / License Recognition
98
- if (
99
- status === 401 ||
100
- status === 403 ||
101
- /unauthorized|auth|license|revoked|terminated|api[- ]?key/i.test(message) ||
102
- code === 'INVALID_API_KEY' ||
103
- code === 'LICENSE_DELETED' ||
104
- code === 'LICENSE_INACTIVE'
105
- ) {
106
- const isLicenseError = /403|license|revoked|terminated/i.test(message) || status === 403;
107
- const cleanMsg = isLicenseError
108
- ? 'Your Retrivora license key has been terminated, suspended, or revoked. Access denied.'
109
- : message;
110
- return new AuthenticationException(cleanMsg, err);
111
- }
112
-
113
- // Fallback Mapping based on defaultCode
114
- switch (defaultCode) {
115
- case 'PROVIDER_NOT_FOUND':
116
- return new ProviderNotFoundException('provider', message, err);
117
- case 'EMBEDDING_FAILED':
118
- return new EmbeddingFailedException(message, err);
119
- case 'RETRIEVAL_FAILED':
120
- return new RetrievalException(message, err);
121
- case 'RATE_LIMITED':
122
- return new RateLimitException(message, err);
123
- case 'CONFIGURATION_ERROR':
124
- return new ConfigurationException(message, err);
125
- case 'AUTHENTICATION_ERROR':
126
- return new AuthenticationException(message, err);
127
- default:
128
- return new RetrivoraError(message, defaultCode, err);
129
- }
130
- }
131
-