@devilsdev/rag-pipeline-utils 2.3.0 → 2.4.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.
Files changed (160) hide show
  1. package/README.md +293 -361
  2. package/contracts/loader-contract.json +11 -6
  3. package/contracts/reranker-contract.json +18 -26
  4. package/dist/index.cjs +21190 -47
  5. package/dist/index.d.ts +298 -68
  6. package/dist/index.mjs +9 -76
  7. package/package.json +20 -8
  8. package/src/agentic/agentic-pipeline.js +235 -0
  9. package/src/agentic/iterative-retriever.js +213 -0
  10. package/src/agentic/query-planner.js +208 -0
  11. package/src/agentic/self-critique.js +102 -0
  12. package/src/ai/adaptive-retrieval.js +0 -3
  13. package/src/ai/federated-learning.js +0 -3
  14. package/src/ai/federation.js +1 -6
  15. package/src/ai/index.js +9 -20
  16. package/src/ai/model-training.js +0 -3
  17. package/src/ai/multimodal-processing.js +0 -3
  18. package/src/ai/multimodal.js +1 -6
  19. package/src/ai/orchestrator.js +1 -6
  20. package/src/ai/retrieval-engine.js +1 -6
  21. package/src/chunking/chunking-engine.js +142 -0
  22. package/src/chunking/strategies/fixed-size.js +54 -0
  23. package/src/chunking/strategies/recursive.js +127 -0
  24. package/src/chunking/strategies/semantic.js +128 -0
  25. package/src/chunking/strategies/sentence.js +32 -0
  26. package/src/chunking/strategies/structure-aware.js +138 -0
  27. package/src/citation/citation-tracker.js +161 -0
  28. package/src/citation/hallucination-detector.js +74 -0
  29. package/src/citation/source-mapper.js +95 -0
  30. package/src/cli/commands/ai-ml/adaptive-commands.js +178 -0
  31. package/src/cli/commands/ai-ml/federated-commands.js +207 -0
  32. package/src/cli/commands/ai-ml/index.js +17 -0
  33. package/src/cli/commands/ai-ml/multimodal-commands.js +187 -0
  34. package/src/cli/commands/ai-ml/shared.js +51 -0
  35. package/src/cli/commands/ai-ml/training-commands.js +228 -0
  36. package/src/cli/commands/ai-ml.js +176 -757
  37. package/src/cli/commands/plugin-hub/certification-commands.js +221 -0
  38. package/src/cli/commands/plugin-hub/event-handlers.js +64 -0
  39. package/src/cli/commands/plugin-hub/hub-commands.js +290 -0
  40. package/src/cli/commands/plugin-hub/review-commands.js +78 -0
  41. package/src/cli/commands/plugin-hub.js +106 -782
  42. package/src/cli/diagnostics/config-checker.js +81 -0
  43. package/src/cli/diagnostics/dependency-checker.js +69 -0
  44. package/src/cli/diagnostics/environment-checker.js +45 -0
  45. package/src/cli/diagnostics/performance-checker.js +51 -0
  46. package/src/cli/diagnostics/plugin-checker.js +106 -0
  47. package/src/cli/diagnostics/security-checker.js +61 -0
  48. package/src/cli/doctor-command.js +70 -369
  49. package/src/cli/enhanced-cli-commands.js +162 -706
  50. package/src/cli/handlers/config-handler.js +126 -0
  51. package/src/cli/handlers/diagnostics-handler.js +113 -0
  52. package/src/cli/handlers/ingest-handler.js +42 -0
  53. package/src/cli/handlers/init-handler.js +51 -0
  54. package/src/cli/handlers/query-handler.js +45 -0
  55. package/src/cli/handlers/run-handler.js +181 -0
  56. package/src/cli/interactive-wizard.js +99 -723
  57. package/src/cli/shared/cli-utils.js +89 -0
  58. package/src/cli/wizard/configuration.js +148 -0
  59. package/src/cli/wizard/observability.js +79 -0
  60. package/src/cli/wizard/performance.js +76 -0
  61. package/src/cli/wizard/plugin-selection.js +297 -0
  62. package/src/cli/wizard/preview-save.js +172 -0
  63. package/src/cli/wizard/project-setup.js +66 -0
  64. package/src/config/memory-optimization.js +3 -3
  65. package/src/connectors/anthropic-connector.js +179 -0
  66. package/src/connectors/base-connector.js +94 -0
  67. package/src/connectors/cohere-connector.js +143 -0
  68. package/src/connectors/local-embedder.js +171 -0
  69. package/src/connectors/memory-retriever.js +150 -0
  70. package/src/connectors/ollama-connector.js +205 -0
  71. package/src/connectors/openai-connector.js +173 -0
  72. package/src/core/create-pipeline.js +21 -1
  73. package/src/core/observability/tracing.js +2 -1
  74. package/src/core/pipeline-factory.js +0 -1
  75. package/src/core/plugin-registry.js +14 -14
  76. package/src/cost/cost-calculator.js +146 -0
  77. package/src/cost/cost-tracker.js +260 -0
  78. package/src/cost/token-budget.js +245 -0
  79. package/src/dag/core/execution-scheduler.js +2 -1
  80. package/src/dag/core/topology-validation.js +0 -3
  81. package/src/dag/dag-engine.js +3 -5
  82. package/src/dag/dag-node.js +0 -1
  83. package/src/dag/enhanced-dag-engine.js +171 -99
  84. package/src/dashboard/dashboard-generator.js +642 -0
  85. package/src/dashboard/metrics-aggregator.js +409 -0
  86. package/src/debug/execution-tracer.js +210 -0
  87. package/src/debug/trace-inspector.js +281 -0
  88. package/src/dev/dev-server.js +5 -5
  89. package/src/dev/hot-reload.js +3 -2
  90. package/src/dx/integration-templates.js +0 -3
  91. package/src/ecosystem/plugin-analytics-dashboard.js +2 -2
  92. package/src/ecosystem/plugin-hub.js +2 -2
  93. package/src/enterprise/audit-logging.js +2 -2
  94. package/src/enterprise/sso-integration.js +52 -32
  95. package/src/evaluate/context-metrics.js +127 -0
  96. package/src/evaluate/evaluator.js +4 -2
  97. package/src/evaluate/faithfulness.js +117 -0
  98. package/src/evaluate/groundedness.js +60 -0
  99. package/src/evaluate/pipeline-evaluator.js +156 -0
  100. package/src/evaluate/relevance.js +129 -0
  101. package/src/evaluate/scoring.js +27 -0
  102. package/src/graph/entity-extractor.js +183 -0
  103. package/src/graph/graph-index.js +113 -0
  104. package/src/graph/graph-retriever.js +244 -0
  105. package/src/graph/knowledge-graph.js +256 -0
  106. package/src/guardrails/guardrails-pipeline.js +136 -0
  107. package/src/guardrails/post-generation-guard.js +170 -0
  108. package/src/guardrails/pre-retrieval-guard.js +161 -0
  109. package/src/guardrails/retrieval-guard.js +126 -0
  110. package/src/index.js +255 -9
  111. package/src/loader/html-loader.js +4 -15
  112. package/src/loader/markdown-loader.js +4 -15
  113. package/src/mcp/mcp-server.js +199 -0
  114. package/src/mcp/mcp-tool-builder.js +121 -0
  115. package/src/observability/audit-logger.js +0 -2
  116. package/src/observability/event-logger.js +2 -1
  117. package/src/observability/security-monitor.js +0 -2
  118. package/src/observability/telemetry.js +0 -2
  119. package/src/reranker/cascade-reranker.js +79 -0
  120. package/src/reranker/embedding-reranker.js +124 -0
  121. package/src/reranker/llm-reranker.js +6 -3
  122. package/src/reranker/scoring-reranker.js +123 -0
  123. package/src/retrieval/bm25-search.js +157 -0
  124. package/src/retrieval/hybrid-retriever.js +111 -0
  125. package/src/retrieval/rank-fusion.js +62 -0
  126. package/src/security/jwt-config.js +4 -3
  127. package/src/security/jwt-validator.js +2 -1
  128. package/src/security/plugin-sandbox.js +0 -3
  129. package/src/security/plugin-signature-verifier.js +4 -6
  130. package/src/security/validator.js +0 -2
  131. package/src/streaming/embedding-stream.js +197 -0
  132. package/src/streaming/sse-adapter.js +168 -0
  133. package/src/streaming/stream-router.js +210 -0
  134. package/src/streaming/streaming-embedder.js +231 -0
  135. package/src/streaming/websocket-adapter.js +171 -0
  136. package/src/templates/scaffold.js +147 -0
  137. package/src/templates/template-registry.js +272 -0
  138. package/src/utils/contract-validator.js +2 -1
  139. package/src/utils/input-sanitizer.js +80 -99
  140. package/src/utils/performance-monitor.js +0 -3
  141. package/src/utils/plugin-scaffolder.js +9 -16
  142. package/src/utils/rate-limiter.js +0 -1
  143. package/src/utils/retry-policy.js +0 -3
  144. package/src/utils/safe-expression-evaluator.js +0 -3
  145. package/src/utils/secure-logger-config.js +2 -4
  146. package/src/utils/secure-logging.js +0 -3
  147. package/src/utils/structured-logger.js +0 -3
  148. package/src/ai/index-fixed.js +0 -509
  149. package/src/ai/module-template.js +0 -37
  150. package/src/ci/workflow-analyzer.js +0 -71
  151. package/src/cli/plugin-marketplace-commands.js +0 -869
  152. package/src/dev/README.md +0 -126
  153. package/src/dev/examples/hot-reload-usage.js +0 -355
  154. package/src/mocks/openai-embedder.js +0 -119
  155. package/src/mocks/openai-llm.js +0 -77
  156. package/src/mocks/pdf-loader.js +0 -21
  157. package/src/mocks/pinecone-retriever.js +0 -106
  158. package/src/scripts/script-utilities.js +0 -36
  159. package/src/utils/ci/diagnostic-reporter.js +0 -57
  160. package/src/utils/examples/error-formatter-usage.js +0 -351
package/src/index.js CHANGED
@@ -7,7 +7,7 @@
7
7
  const { createRagPipeline } = require('./core/create-pipeline');
8
8
 
9
9
  // Configuration utilities
10
- const { loadConfig } = require('./config/load-config');
10
+ const { loadRagConfig } = require('./config/load-config');
11
11
  const { validateRagrc } = require('./config/enhanced-ragrc-schema');
12
12
  const { normalizeConfig } = require('./config/normalize-config');
13
13
 
@@ -17,13 +17,125 @@ const pluginRegistry = require('./core/plugin-registry');
17
17
  // Utilities
18
18
  const logger = require('./utils/logger');
19
19
  const errorFormatter = require('./utils/error-formatter');
20
+ const { BatchProcessor } = require('./utils/batch-processor');
21
+ const RateLimiter = require('./utils/rate-limiter');
22
+ const { retry, withRetry } = require('./utils/retry');
23
+ const { ConnectionPoolManager } = require('./utils/connection-pool');
24
+
25
+ // Security
26
+ const { JWTValidator } = require('./security/jwt-validator');
27
+ const { PluginSandbox } = require('./security/plugin-sandbox');
28
+ const {
29
+ PluginSignatureVerifier,
30
+ } = require('./security/plugin-signature-verifier');
31
+ const { validateInput } = require('./security/validator');
20
32
 
21
33
  // AI/ML capabilities
22
- const MultiModalProcessor = require('./ai/multimodal');
23
- const AdaptiveRetrievalEngine = require('./ai/retrieval-engine');
34
+ const { MultiModalProcessor } = require('./ai/multimodal');
35
+ const { AdaptiveRetrievalEngine } = require('./ai/retrieval-engine');
36
+ const {
37
+ FederatedLearningCoordinator,
38
+ } = require('./ai/federation/federated-learning-coordinator');
39
+ const {
40
+ ModelTrainingOrchestrator,
41
+ } = require('./ai/training/model-training-orchestrator');
24
42
 
25
43
  // DAG engine for complex workflows
26
- const { DAGEngine } = require('./dag/dag-engine');
44
+ const { DAG } = require('./dag/dag-engine');
45
+
46
+ // Evaluation
47
+ const { evaluateRagDataset } = require('./evaluate/evaluator');
48
+ const {
49
+ scoreAnswer,
50
+ computeBLEU,
51
+ computeROUGE,
52
+ } = require('./evaluate/scoring');
53
+ const { computeFaithfulness } = require('./evaluate/faithfulness');
54
+ const { computeAnswerRelevance } = require('./evaluate/relevance');
55
+ const {
56
+ computeContextPrecision,
57
+ computeContextRecall,
58
+ } = require('./evaluate/context-metrics');
59
+ const { computeGroundedness } = require('./evaluate/groundedness');
60
+ const { PipelineEvaluator } = require('./evaluate/pipeline-evaluator');
61
+
62
+ // Chunking
63
+ const { ChunkingEngine } = require('./chunking/chunking-engine');
64
+
65
+ // Citation & Grounding
66
+ const { CitationTracker } = require('./citation/citation-tracker');
67
+ const {
68
+ mapSentenceToSources,
69
+ buildIDFWeights,
70
+ } = require('./citation/source-mapper');
71
+ const { detectHallucinations } = require('./citation/hallucination-detector');
72
+
73
+ // Hybrid Retrieval
74
+ const { BM25Search } = require('./retrieval/bm25-search');
75
+ const { reciprocalRankFusion } = require('./retrieval/rank-fusion');
76
+ const { HybridRetriever } = require('./retrieval/hybrid-retriever');
77
+
78
+ // Guardrails
79
+ const { PreRetrievalGuard } = require('./guardrails/pre-retrieval-guard');
80
+ const { RetrievalGuard } = require('./guardrails/retrieval-guard');
81
+ const { PostGenerationGuard } = require('./guardrails/post-generation-guard');
82
+ const { GuardrailsPipeline } = require('./guardrails/guardrails-pipeline');
83
+
84
+ // Agentic RAG
85
+ const { QueryPlanner } = require('./agentic/query-planner');
86
+ const { IterativeRetriever } = require('./agentic/iterative-retriever');
87
+ const { SelfCritiqueChecker } = require('./agentic/self-critique');
88
+ const { AgenticPipeline } = require('./agentic/agentic-pipeline');
89
+
90
+ // Cost Management
91
+ const { CostCalculator } = require('./cost/cost-calculator');
92
+ const { CostTracker } = require('./cost/cost-tracker');
93
+ const { TokenBudget } = require('./cost/token-budget');
94
+
95
+ // Pipeline Debugger
96
+ const { ExecutionTracer } = require('./debug/execution-tracer');
97
+ const { TraceInspector } = require('./debug/trace-inspector');
98
+
99
+ // MCP Integration
100
+ const { MCPServer } = require('./mcp/mcp-server');
101
+ const { MCPToolBuilder } = require('./mcp/mcp-tool-builder');
102
+
103
+ // Quick Start Templates
104
+ const { ProjectScaffolder } = require('./templates/scaffold');
105
+ const { TemplateRegistry } = require('./templates/template-registry');
106
+
107
+ // Streaming Adapters
108
+ const { SSEAdapter } = require('./streaming/sse-adapter');
109
+ const { WebSocketAdapter } = require('./streaming/websocket-adapter');
110
+ const { StreamRouter } = require('./streaming/stream-router');
111
+
112
+ // Connectors
113
+ const { BaseConnector } = require('./connectors/base-connector');
114
+ const { OllamaConnector } = require('./connectors/ollama-connector');
115
+ const { LocalEmbedder } = require('./connectors/local-embedder');
116
+ const { MemoryRetriever } = require('./connectors/memory-retriever');
117
+ const { OpenAIConnector } = require('./connectors/openai-connector');
118
+ const { AnthropicConnector } = require('./connectors/anthropic-connector');
119
+ const { CohereConnector } = require('./connectors/cohere-connector');
120
+
121
+ // Streaming Embeddings
122
+ const { StreamingEmbedder } = require('./streaming/streaming-embedder');
123
+ const { createEmbeddingStream } = require('./streaming/embedding-stream');
124
+
125
+ // Advanced Reranking
126
+ const { ScoringReranker } = require('./reranker/scoring-reranker');
127
+ const { EmbeddingReranker } = require('./reranker/embedding-reranker');
128
+ const { CascadeReranker } = require('./reranker/cascade-reranker');
129
+
130
+ // GraphRAG
131
+ const { KnowledgeGraph } = require('./graph/knowledge-graph');
132
+ const { EntityExtractor } = require('./graph/entity-extractor');
133
+ const { GraphRetriever } = require('./graph/graph-retriever');
134
+ const { GraphIndex } = require('./graph/graph-index');
135
+
136
+ // Performance Dashboard
137
+ const { DashboardGenerator } = require('./dashboard/dashboard-generator');
138
+ const { MetricsAggregator } = require('./dashboard/metrics-aggregator');
27
139
 
28
140
  // Performance and observability
29
141
  const ParallelProcessor = require('./core/performance/parallel-processor');
@@ -32,7 +144,25 @@ const metrics = require('./core/observability/metrics');
32
144
 
33
145
  // Enterprise features
34
146
  const { AuditLogger } = require('./enterprise/audit-logging');
35
- const { DataGovernance } = require('./enterprise/data-governance');
147
+ const { DataGovernanceManager } = require('./enterprise/data-governance');
148
+ const {
149
+ TenantManager,
150
+ ResourceMonitor,
151
+ } = require('./enterprise/multi-tenancy');
152
+ const {
153
+ SSOManager,
154
+ SAMLProvider,
155
+ OAuth2Provider,
156
+ ActiveDirectoryProvider,
157
+ OIDCProvider,
158
+ } = require('./enterprise/sso-integration');
159
+
160
+ // Ecosystem
161
+ const { PluginHub, PluginAnalytics } = require('./ecosystem/plugin-hub');
162
+ const { PluginCertification } = require('./ecosystem/plugin-certification');
163
+ const {
164
+ PluginAnalyticsDashboard,
165
+ } = require('./ecosystem/plugin-analytics-dashboard');
36
166
 
37
167
  // Development tools
38
168
  const {
@@ -47,7 +177,8 @@ module.exports = {
47
177
  createPipeline: createRagPipeline, // Alias for backward compatibility
48
178
 
49
179
  // Configuration
50
- loadConfig,
180
+ loadConfig: loadRagConfig,
181
+ loadRagConfig,
51
182
  validateRagrc,
52
183
  normalizeConfig,
53
184
 
@@ -57,17 +188,118 @@ module.exports = {
57
188
  // Utilities
58
189
  logger,
59
190
  errorFormatter,
60
- // Error handling utilities
61
191
  createError: errorFormatter.createError,
62
192
  wrapError: errorFormatter.wrapError,
63
193
  ERROR_CODES: errorFormatter.ERROR_CODES,
194
+ BatchProcessor,
195
+ RateLimiter,
196
+ retry,
197
+ withRetry,
198
+ ConnectionPoolManager,
199
+
200
+ // Security
201
+ JWTValidator,
202
+ PluginSandbox,
203
+ PluginSignatureVerifier,
204
+ validateInput,
64
205
 
65
206
  // AI/ML
66
207
  MultiModalProcessor,
67
208
  AdaptiveRetrievalEngine,
209
+ FederatedLearningCoordinator,
210
+ ModelTrainingOrchestrator,
68
211
 
69
212
  // Workflow engine
70
- DAGEngine,
213
+ DAGEngine: DAG,
214
+ DAG,
215
+
216
+ // Evaluation
217
+ evaluateRagDataset,
218
+ scoreAnswer,
219
+ computeBLEU,
220
+ computeROUGE,
221
+ computeFaithfulness,
222
+ computeAnswerRelevance,
223
+ computeContextPrecision,
224
+ computeContextRecall,
225
+ computeGroundedness,
226
+ PipelineEvaluator,
227
+
228
+ // Chunking
229
+ ChunkingEngine,
230
+
231
+ // Citation & Grounding
232
+ CitationTracker,
233
+ mapSentenceToSources,
234
+ buildIDFWeights,
235
+ detectHallucinations,
236
+
237
+ // Hybrid Retrieval
238
+ BM25Search,
239
+ reciprocalRankFusion,
240
+ HybridRetriever,
241
+
242
+ // Guardrails
243
+ PreRetrievalGuard,
244
+ RetrievalGuard,
245
+ PostGenerationGuard,
246
+ GuardrailsPipeline,
247
+
248
+ // Agentic RAG
249
+ QueryPlanner,
250
+ IterativeRetriever,
251
+ SelfCritiqueChecker,
252
+ AgenticPipeline,
253
+
254
+ // Cost Management
255
+ CostCalculator,
256
+ CostTracker,
257
+ TokenBudget,
258
+
259
+ // Pipeline Debugger
260
+ ExecutionTracer,
261
+ TraceInspector,
262
+
263
+ // MCP Integration
264
+ MCPServer,
265
+ MCPToolBuilder,
266
+
267
+ // Quick Start Templates
268
+ ProjectScaffolder,
269
+ TemplateRegistry,
270
+
271
+ // Streaming Adapters
272
+ SSEAdapter,
273
+ WebSocketAdapter,
274
+ StreamRouter,
275
+
276
+ // Connectors
277
+ BaseConnector,
278
+ OllamaConnector,
279
+ LocalEmbedder,
280
+ MemoryRetriever,
281
+ OpenAIConnector,
282
+ AnthropicConnector,
283
+ CohereConnector,
284
+
285
+ // Streaming Embeddings
286
+ StreamingEmbedder,
287
+ createEmbeddingStream,
288
+
289
+ // Advanced Reranking
290
+ ScoringReranker,
291
+ EmbeddingReranker,
292
+ CascadeReranker,
293
+
294
+ // GraphRAG
295
+ KnowledgeGraph,
296
+ EntityExtractor,
297
+ GraphRetriever,
298
+ GraphIndex,
299
+
300
+ // Performance Dashboard
301
+ DashboardGenerator,
302
+ MetricsAggregator,
71
303
 
72
304
  // Performance & Observability
73
305
  ParallelProcessor,
@@ -76,7 +308,21 @@ module.exports = {
76
308
 
77
309
  // Enterprise
78
310
  AuditLogger,
79
- DataGovernance,
311
+ DataGovernance: DataGovernanceManager,
312
+ DataGovernanceManager,
313
+ TenantManager,
314
+ ResourceMonitor,
315
+ SSOManager,
316
+ SAMLProvider,
317
+ OAuth2Provider,
318
+ ActiveDirectoryProvider,
319
+ OIDCProvider,
320
+
321
+ // Ecosystem
322
+ PluginHub,
323
+ PluginAnalytics,
324
+ PluginCertification,
325
+ PluginAnalyticsDashboard,
80
326
 
81
327
  // Development tools
82
328
  HotReloadManager,
@@ -34,26 +34,15 @@ class HTMLLoader {
34
34
  }
35
35
 
36
36
  /**
37
- * Chunk HTML text content by sentence
37
+ * Chunk HTML text content using the ChunkingEngine
38
38
  * @param {string} input
39
39
  * @param {number} maxLen
40
40
  * @returns {string[]}
41
41
  */
42
42
  _chunkText(input, maxLen = 500) {
43
- const sentences = input.split(/(?<=[.!?])\s+/);
44
- const chunks = [];
45
- let buffer = '';
46
-
47
- for (const sentence of sentences) {
48
- if ((buffer + sentence).length <= maxLen) {
49
- buffer += sentence + ' ';
50
- } else {
51
- chunks.push(buffer.trim());
52
- buffer = sentence + ' ';
53
- }
54
- }
55
- if (buffer.trim()) chunks.push(buffer.trim());
56
- return chunks;
43
+ const { ChunkingEngine } = require('../chunking/chunking-engine');
44
+ const engine = new ChunkingEngine({ strategy: 'sentence', maxLen });
45
+ return engine.chunk(input);
57
46
  }
58
47
  }
59
48
 
@@ -37,26 +37,15 @@ class MarkdownLoader {
37
37
  }
38
38
 
39
39
  /**
40
- * Simple sentence-based chunking strategy
40
+ * Chunk text using the ChunkingEngine
41
41
  * @param {string} input
42
42
  * @param {number} maxLen
43
43
  * @returns {string[]}
44
44
  */
45
45
  _chunkText(input, maxLen = 500) {
46
- const sentences = input.split(/(?<=[.!?])\s+/);
47
- const chunks = [];
48
- let buffer = '';
49
-
50
- for (const sentence of sentences) {
51
- if ((buffer + sentence).length <= maxLen) {
52
- buffer += sentence + ' ';
53
- } else {
54
- chunks.push(buffer.trim());
55
- buffer = sentence + ' ';
56
- }
57
- }
58
- if (buffer.trim()) chunks.push(buffer.trim());
59
- return chunks;
46
+ const { ChunkingEngine } = require('../chunking/chunking-engine');
47
+ const engine = new ChunkingEngine({ strategy: 'sentence', maxLen });
48
+ return engine.chunk(input);
60
49
  }
61
50
  }
62
51
 
@@ -0,0 +1,199 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @module mcp/mcp-server
5
+ * @description Wraps a RAG pipeline as an MCP-compatible tool handler.
6
+ */
7
+
8
+ const { EventEmitter } = require('events');
9
+ const { MCPToolBuilder } = require('./mcp-tool-builder');
10
+
11
+ /** @type {Object} Default configuration for the MCP server */
12
+ const DEFAULT_CONFIG = {
13
+ includeMetadata: true,
14
+ maxResponseLength: 50000,
15
+ };
16
+
17
+ /**
18
+ * MCP server that registers RAG pipelines as callable MCP tools.
19
+ *
20
+ * @extends EventEmitter
21
+ * @fires MCPServer#tool_use
22
+ *
23
+ * @example
24
+ * const server = MCPServer.fromPipeline(myPipeline, { name: 'my_tool' });
25
+ * const tools = server.getToolDefinitions();
26
+ * const result = await server.handleToolUse('my_tool', { query: 'What is X?' });
27
+ */
28
+ class MCPServer extends EventEmitter {
29
+ /**
30
+ * @param {Object} [options={}] - Server configuration
31
+ * @param {boolean} [options.includeMetadata] - Include metadata in responses
32
+ * @param {number} [options.maxResponseLength] - Maximum response text length
33
+ * @param {Object} [options.toolOptions] - Options forwarded to MCPToolBuilder
34
+ */
35
+ constructor(options = {}) {
36
+ super();
37
+ this.config = { ...DEFAULT_CONFIG, ...options };
38
+ this.toolBuilder = new MCPToolBuilder(options.toolOptions);
39
+ /** @type {Map<string, {pipeline: Object, config: Object, toolDefinition: Object}>} */
40
+ this.pipelines = new Map();
41
+ }
42
+
43
+ /**
44
+ * Register a pipeline that can be called as an MCP tool.
45
+ *
46
+ * @param {string} name - Tool name used to invoke this pipeline
47
+ * @param {Object} pipeline - Pipeline instance with a `run` method
48
+ * @param {Object} [config={}] - Pipeline-specific configuration
49
+ * @returns {void}
50
+ */
51
+ registerPipeline(name, pipeline, config = {}) {
52
+ if (!name || typeof name !== 'string') {
53
+ throw new TypeError('Pipeline name must be a non-empty string');
54
+ }
55
+ if (!pipeline || typeof pipeline.run !== 'function') {
56
+ throw new TypeError('Pipeline must have a run() method');
57
+ }
58
+
59
+ const builder = new MCPToolBuilder({
60
+ toolName: name,
61
+ toolDescription:
62
+ config.description || this.toolBuilder.config.toolDescription,
63
+ });
64
+
65
+ const toolDefinition = builder.buildToolDefinition(config);
66
+
67
+ this.pipelines.set(name, { pipeline, config, toolDefinition });
68
+ }
69
+
70
+ /**
71
+ * Return array of all registered tool definitions.
72
+ * Each is a valid MCP tool schema.
73
+ *
74
+ * @returns {Array<Object>} Array of MCP tool definition objects
75
+ */
76
+ getToolDefinitions() {
77
+ return Array.from(this.pipelines.values()).map(
78
+ (entry) => entry.toolDefinition,
79
+ );
80
+ }
81
+
82
+ /**
83
+ * Handle an MCP tool_use request by running the matching pipeline.
84
+ *
85
+ * @param {string} toolName - Name of the tool to invoke
86
+ * @param {Object} toolInput - Tool input parameters
87
+ * @param {string} toolInput.query - The search query (required)
88
+ * @param {number} [toolInput.topK] - Number of results to retrieve
89
+ * @param {boolean} [toolInput.stream] - Enable streaming response
90
+ * @param {boolean} [toolInput.citations] - Include source citations
91
+ * @param {boolean} [toolInput.evaluate] - Include quality evaluation metrics
92
+ * @returns {Promise<Object>} MCP-formatted response with type and text fields
93
+ * @throws {Error} If tool name is not registered or query is missing
94
+ */
95
+ async handleToolUse(toolName, toolInput) {
96
+ const entry = this.pipelines.get(toolName);
97
+ if (!entry) {
98
+ throw new Error(`Unknown tool: ${toolName}`);
99
+ }
100
+
101
+ if (
102
+ !toolInput ||
103
+ typeof toolInput.query !== 'string' ||
104
+ !toolInput.query.trim()
105
+ ) {
106
+ throw new Error(
107
+ 'toolInput.query is required and must be a non-empty string',
108
+ );
109
+ }
110
+
111
+ const { pipeline } = entry;
112
+ const options = {};
113
+
114
+ if (typeof toolInput.topK === 'number') {
115
+ options.topK = toolInput.topK;
116
+ }
117
+ if (typeof toolInput.stream === 'boolean') {
118
+ options.stream = toolInput.stream;
119
+ }
120
+ if (typeof toolInput.citations === 'boolean') {
121
+ options.citations = toolInput.citations;
122
+ }
123
+ if (typeof toolInput.evaluate === 'boolean') {
124
+ options.evaluate = toolInput.evaluate;
125
+ }
126
+
127
+ const result = await pipeline.run({
128
+ query: toolInput.query,
129
+ options,
130
+ });
131
+
132
+ const hasExtras = result.citations || result.evaluation;
133
+ let responseText;
134
+
135
+ if (hasExtras && this.config.includeMetadata) {
136
+ const payload = { answer: result.answer || result.results };
137
+ if (result.citations) {
138
+ payload.citations = result.citations;
139
+ }
140
+ if (result.evaluation) {
141
+ payload.evaluation = result.evaluation;
142
+ }
143
+ responseText = JSON.stringify(payload);
144
+ } else {
145
+ responseText =
146
+ typeof result.answer === 'string'
147
+ ? result.answer
148
+ : JSON.stringify(result);
149
+ }
150
+
151
+ if (
152
+ this.config.maxResponseLength &&
153
+ responseText.length > this.config.maxResponseLength
154
+ ) {
155
+ responseText = responseText.slice(0, this.config.maxResponseLength);
156
+ }
157
+
158
+ const response = {
159
+ type: 'text',
160
+ text: responseText,
161
+ };
162
+
163
+ /**
164
+ * @event MCPServer#tool_use
165
+ * @type {Object}
166
+ * @property {string} toolName - Name of the tool that was invoked
167
+ * @property {Object} toolInput - Original input parameters
168
+ * @property {number} responseLength - Length of the response text
169
+ */
170
+ this.emit('tool_use', {
171
+ toolName,
172
+ toolInput,
173
+ responseLength: responseText.length,
174
+ });
175
+
176
+ return response;
177
+ }
178
+
179
+ /**
180
+ * Convenience factory: create an MCPServer with a single pipeline registered.
181
+ *
182
+ * @param {Object} pipeline - Pipeline instance with a `run` method
183
+ * @param {Object} [options={}] - Server and registration options
184
+ * @param {string} [options.name='rag_query'] - Tool name for the pipeline
185
+ * @param {Object} [options.config] - Pipeline-specific configuration
186
+ * @returns {MCPServer} Configured server instance
187
+ */
188
+ static fromPipeline(pipeline, options = {}) {
189
+ const server = new MCPServer(options);
190
+ server.registerPipeline(
191
+ options.name || 'rag_query',
192
+ pipeline,
193
+ options.config || {},
194
+ );
195
+ return server;
196
+ }
197
+ }
198
+
199
+ module.exports = { MCPServer, DEFAULT_CONFIG };
@@ -0,0 +1,121 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @module mcp/mcp-tool-builder
5
+ * @description Builds MCP tool definitions from pipeline configuration.
6
+ */
7
+
8
+ /** @type {Object} Default configuration for the MCP tool builder */
9
+ const DEFAULT_CONFIG = {
10
+ toolName: 'rag_pipeline_query',
11
+ toolDescription: 'Query a RAG pipeline with natural language',
12
+ };
13
+
14
+ /**
15
+ * Builds MCP-compatible tool definitions from RAG pipeline configuration.
16
+ *
17
+ * @example
18
+ * const builder = new MCPToolBuilder({ toolName: 'my_rag_tool' });
19
+ * const definition = builder.buildToolDefinition({ capabilities: { stream: true } });
20
+ */
21
+ class MCPToolBuilder {
22
+ /**
23
+ * @param {Object} [options={}] - Builder configuration
24
+ * @param {string} [options.toolName] - Name for the generated MCP tool
25
+ * @param {string} [options.toolDescription] - Description for the generated MCP tool
26
+ */
27
+ constructor(options = {}) {
28
+ this.config = { ...DEFAULT_CONFIG, ...options };
29
+ }
30
+
31
+ /**
32
+ * Generate an MCP-compatible tool definition from pipeline configuration.
33
+ *
34
+ * @param {Object} [pipelineConfig={}] - Pipeline-specific configuration
35
+ * @param {Object} [pipelineConfig.capabilities] - Pipeline capabilities to reflect in schema
36
+ * @param {boolean} [pipelineConfig.capabilities.stream] - Whether streaming is supported
37
+ * @param {boolean} [pipelineConfig.capabilities.citations] - Whether citations are supported
38
+ * @param {boolean} [pipelineConfig.capabilities.evaluate] - Whether evaluation is supported
39
+ * @param {number} [pipelineConfig.capabilities.maxTopK] - Maximum allowed topK value
40
+ * @returns {Object} MCP tool definition with name, description, and input_schema
41
+ */
42
+ buildToolDefinition(pipelineConfig = {}) {
43
+ const capabilities = pipelineConfig.capabilities || {};
44
+
45
+ const properties = {
46
+ query: {
47
+ type: 'string',
48
+ description: 'The search query or question',
49
+ },
50
+ topK: {
51
+ type: 'number',
52
+ description: 'Number of results to retrieve',
53
+ default: 5,
54
+ },
55
+ };
56
+
57
+ if (typeof capabilities.maxTopK === 'number') {
58
+ properties.topK.maximum = capabilities.maxTopK;
59
+ }
60
+
61
+ if (capabilities.stream !== false) {
62
+ properties.stream = {
63
+ type: 'boolean',
64
+ description: 'Enable streaming response',
65
+ default: false,
66
+ };
67
+ }
68
+
69
+ if (capabilities.citations !== false) {
70
+ properties.citations = {
71
+ type: 'boolean',
72
+ description: 'Include source citations',
73
+ default: false,
74
+ };
75
+ }
76
+
77
+ if (capabilities.evaluate !== false) {
78
+ properties.evaluate = {
79
+ type: 'boolean',
80
+ description: 'Include quality evaluation metrics',
81
+ default: false,
82
+ };
83
+ }
84
+
85
+ return {
86
+ name: this.config.toolName,
87
+ description: this.config.toolDescription,
88
+ input_schema: {
89
+ type: 'object',
90
+ properties,
91
+ required: ['query'],
92
+ },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Build tool definitions for multiple named pipelines.
98
+ *
99
+ * @param {Array<Object>} pipelines - Array of pipeline descriptors
100
+ * @param {string} pipelines[].name - Tool name for this pipeline
101
+ * @param {string} [pipelines[].description] - Tool description
102
+ * @param {Object} [pipelines[].pipeline] - Pipeline instance (unused during definition building)
103
+ * @param {Object} [pipelines[].config] - Pipeline configuration passed to buildToolDefinition
104
+ * @returns {Array<Object>} Array of MCP tool definitions
105
+ */
106
+ buildMultipleTools(pipelines) {
107
+ if (!Array.isArray(pipelines)) {
108
+ throw new TypeError('pipelines must be an array');
109
+ }
110
+
111
+ return pipelines.map((entry) => {
112
+ const builder = new MCPToolBuilder({
113
+ toolName: entry.name,
114
+ toolDescription: entry.description || this.config.toolDescription,
115
+ });
116
+ return builder.buildToolDefinition(entry.config || {});
117
+ });
118
+ }
119
+ }
120
+
121
+ module.exports = { MCPToolBuilder, DEFAULT_CONFIG };
@@ -754,5 +754,3 @@ module.exports = {
754
754
  initializeAuditLogging,
755
755
  logAuditEvent,
756
756
  };
757
-
758
- module.exports.default = module.exports;