@hashgraphonline/conversational-agent 0.1.206 → 0.1.208

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.
@@ -1,236 +1,161 @@
1
- import { MemoryWindow } from "./index21.js";
2
- import { ContentStorage } from "./index19.js";
3
- import { TokenCounter } from "./index22.js";
4
- const _SmartMemoryManager = class _SmartMemoryManager {
5
- constructor(config = {}) {
6
- this.config = { ..._SmartMemoryManager.DEFAULT_CONFIG, ...config };
7
- this.tokenCounter = new TokenCounter(this.config.modelName);
8
- this.contentStorage = new ContentStorage(this.config.storageLimit);
9
- this.memoryWindow = new MemoryWindow(
10
- this.config.maxTokens,
11
- this.config.reserveTokens,
12
- this.tokenCounter
13
- );
14
- }
15
- /**
16
- * Add a message to the active memory window
17
- * Automatically handles pruning and storage of displaced messages
18
- * @param message - Message to add
19
- */
20
- addMessage(message) {
21
- const result = this.memoryWindow.addMessage(message);
22
- if (result.prunedMessages.length > 0) {
23
- this.contentStorage.storeMessages(result.prunedMessages);
24
- }
25
- }
26
- /**
27
- * Get all active messages from the memory window
28
- * @returns Array of active messages in chronological order
29
- */
30
- getMessages() {
31
- return this.memoryWindow.getMessages();
32
- }
33
- /**
34
- * Clear active memory window
35
- * @param clearStorage - Whether to also clear the content storage (default: false)
36
- */
37
- clear(clearStorage = false) {
38
- this.memoryWindow.clear();
39
- if (clearStorage) {
40
- this.contentStorage.clear();
41
- }
42
- }
43
- /**
44
- * Set the system prompt for the memory window
45
- * @param systemPrompt - System prompt text
46
- */
47
- setSystemPrompt(systemPrompt) {
48
- this.memoryWindow.setSystemPrompt(systemPrompt);
49
- }
50
- /**
51
- * Get the current system prompt
52
- * @returns Current system prompt text
53
- */
54
- getSystemPrompt() {
55
- return this.memoryWindow.getSystemPrompt();
56
- }
57
- /**
58
- * Search through stored message history
59
- * @param query - Search term or pattern
60
- * @param options - Search configuration
61
- * @returns Array of matching messages from history
62
- */
63
- searchHistory(query, options = {}) {
64
- return this.contentStorage.searchMessages(query, options);
65
- }
66
- /**
67
- * Get recent messages from storage history
68
- * @param count - Number of recent messages to retrieve
69
- * @returns Array of recent messages from storage
70
- */
71
- getRecentHistory(count) {
72
- return this.contentStorage.getRecentMessages(count);
73
- }
74
- /**
75
- * Check if a message can be added without exceeding limits
76
- * @param message - Message to test
77
- * @returns True if message can be added
78
- */
79
- canAddMessage(message) {
80
- return this.memoryWindow.canAddMessage(message);
81
- }
82
- /**
83
- * Get statistics about the active memory window
84
- * @returns Memory usage statistics
85
- */
86
- getMemoryStats() {
87
- const windowStats = this.memoryWindow.getStats();
88
- return {
89
- totalActiveMessages: windowStats.totalMessages,
90
- currentTokenCount: windowStats.currentTokens,
91
- maxTokens: windowStats.maxTokens,
92
- remainingCapacity: windowStats.remainingCapacity,
93
- systemPromptTokens: windowStats.systemPromptTokens,
94
- usagePercentage: windowStats.usagePercentage
95
- };
96
- }
97
- /**
98
- * Get statistics about the content storage
99
- * @returns Storage usage statistics
100
- */
101
- getStorageStats() {
102
- return this.contentStorage.getStorageStats();
103
- }
104
- /**
105
- * Get combined statistics for both active memory and storage
106
- * @returns Combined memory and storage statistics
107
- */
108
- getOverallStats() {
109
- const memoryStats = this.getMemoryStats();
110
- const storageStats = this.getStorageStats();
111
- return {
112
- activeMemory: memoryStats,
113
- storage: storageStats,
114
- totalMessagesManaged: memoryStats.totalActiveMessages + storageStats.totalMessages,
115
- activeMemoryUtilization: memoryStats.usagePercentage,
116
- storageUtilization: storageStats.usagePercentage
117
- };
118
- }
119
- /**
120
- * Update the configuration and apply changes
121
- * @param newConfig - New configuration options
122
- */
123
- updateConfig(newConfig) {
124
- this.config = { ...this.config, ...newConfig };
125
- if (newConfig.maxTokens !== void 0 || newConfig.reserveTokens !== void 0) {
126
- this.memoryWindow.updateLimits(
127
- this.config.maxTokens,
128
- this.config.reserveTokens
129
- );
1
+ import { DynamicStructuredTool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+ import { shouldUseReference, ContentStoreService } from "@hashgraphonline/standards-sdk";
4
+ function convertMCPToolToLangChain(tool, mcpManager, serverConfig) {
5
+ const zodSchema = jsonSchemaToZod(tool.inputSchema);
6
+ const sanitizedName = `${tool.serverName}_${tool.name}`.replace(
7
+ /[^a-zA-Z0-9_]/g,
8
+ "_"
9
+ );
10
+ let description = tool.description || `MCP tool ${tool.name} from ${tool.serverName}`;
11
+ if (serverConfig?.toolDescriptions?.[tool.name]) {
12
+ description = `${description}
13
+
14
+ ${serverConfig.toolDescriptions[tool.name]}`;
15
+ }
16
+ if (serverConfig?.additionalContext) {
17
+ description = `${description}
18
+
19
+ Context: ${serverConfig.additionalContext}`;
20
+ }
21
+ return new DynamicStructuredTool({
22
+ name: sanitizedName,
23
+ description,
24
+ schema: zodSchema,
25
+ func: async (input) => {
26
+ try {
27
+ const result = await mcpManager.executeTool(
28
+ tool.serverName,
29
+ tool.name,
30
+ input
31
+ );
32
+ let responseText = "";
33
+ if (typeof result === "string") {
34
+ responseText = result;
35
+ } else if (result && typeof result === "object" && "content" in result) {
36
+ const content = result.content;
37
+ if (Array.isArray(content)) {
38
+ const textParts = content.filter(
39
+ (item) => typeof item === "object" && item !== null && "type" in item && item.type === "text" && "text" in item
40
+ ).map((item) => item.text);
41
+ responseText = textParts.join("\n");
42
+ } else {
43
+ responseText = JSON.stringify(content);
44
+ }
45
+ } else {
46
+ responseText = JSON.stringify(result);
47
+ }
48
+ const responseBuffer = Buffer.from(responseText, "utf8");
49
+ console.log(`[MCP Adapter] Response size: ${responseBuffer.length} bytes, tool: ${tool.serverName}_${tool.name}`);
50
+ const MCP_REFERENCE_THRESHOLD = 10 * 1024;
51
+ const shouldStoreMCPContent = responseBuffer.length > MCP_REFERENCE_THRESHOLD;
52
+ if (shouldStoreMCPContent || shouldUseReference(responseBuffer)) {
53
+ console.log(`[MCP Adapter] Content exceeds threshold (${responseBuffer.length} > ${MCP_REFERENCE_THRESHOLD}), storing as reference`);
54
+ const contentStore = ContentStoreService.getInstance();
55
+ if (contentStore) {
56
+ try {
57
+ const referenceId = await contentStore.storeContent(responseBuffer, {
58
+ contentType: "text",
59
+ source: "mcp",
60
+ mcpToolName: `${tool.serverName}_${tool.name}`,
61
+ originalSize: responseBuffer.length
62
+ });
63
+ console.log(`[MCP Adapter] Stored content as reference: content-ref:${referenceId}`);
64
+ return `content-ref:${referenceId}`;
65
+ } catch (storeError) {
66
+ console.warn("Failed to store large MCP content as reference:", storeError);
67
+ }
68
+ } else {
69
+ console.warn("[MCP Adapter] ContentStoreService not available");
70
+ }
71
+ }
72
+ return responseText;
73
+ } catch (error) {
74
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
75
+ return `Error executing MCP tool ${tool.name}: ${errorMessage}`;
76
+ }
130
77
  }
131
- if (newConfig.storageLimit !== void 0) {
132
- this.contentStorage.updateStorageLimit(this.config.storageLimit);
78
+ });
79
+ }
80
+ function jsonSchemaToZod(schema) {
81
+ if (!schema || typeof schema !== "object") {
82
+ return z.object({});
83
+ }
84
+ const schemaObj = schema;
85
+ if (schemaObj.type && schemaObj.type !== "object") {
86
+ return convertType(schemaObj);
87
+ }
88
+ if (!schemaObj.properties || typeof schemaObj.properties !== "object") {
89
+ return z.object({});
90
+ }
91
+ const shape = {};
92
+ for (const [key, value] of Object.entries(schemaObj.properties)) {
93
+ let zodType = convertType(value);
94
+ const isRequired = Array.isArray(schemaObj.required) && schemaObj.required.includes(key);
95
+ if (!isRequired) {
96
+ zodType = zodType.optional();
133
97
  }
134
- }
135
- /**
136
- * Get current configuration
137
- * @returns Current configuration settings
138
- */
139
- getConfig() {
140
- return { ...this.config };
141
- }
142
- /**
143
- * Get messages from storage within a time range
144
- * @param startTime - Start of time range
145
- * @param endTime - End of time range
146
- * @returns Messages within the specified time range
147
- */
148
- getHistoryFromTimeRange(startTime, endTime) {
149
- return this.contentStorage.getMessagesFromTimeRange(startTime, endTime);
150
- }
151
- /**
152
- * Get messages from storage by message type
153
- * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)
154
- * @param limit - Maximum number of messages to return
155
- * @returns Messages of the specified type
156
- */
157
- getHistoryByType(messageType, limit) {
158
- return this.contentStorage.getMessagesByType(messageType, limit);
159
- }
160
- /**
161
- * Get recent messages from storage within the last N minutes
162
- * @param minutes - Number of minutes to look back
163
- * @returns Messages from the last N minutes
164
- */
165
- getRecentHistoryByTime(minutes) {
166
- return this.contentStorage.getRecentMessagesByTime(minutes);
167
- }
168
- /**
169
- * Export the current state for persistence or analysis
170
- * @returns Serializable representation of memory state
171
- */
172
- exportState() {
173
- return {
174
- config: this.config,
175
- activeMessages: this.memoryWindow.getMessages().map((msg) => ({
176
- content: msg.content,
177
- type: msg._getType()
178
- })),
179
- systemPrompt: this.memoryWindow.getSystemPrompt(),
180
- memoryStats: this.getMemoryStats(),
181
- storageStats: this.getStorageStats(),
182
- storedMessages: this.contentStorage.exportMessages()
183
- };
184
- }
185
- /**
186
- * Get a summary of conversation context for external use
187
- * Useful for providing context to other systems or for logging
188
- * @param includeStoredContext - Whether to include recent stored messages
189
- * @returns Context summary object
190
- */
191
- getContextSummary(includeStoredContext = false) {
192
- const activeMessages = this.getMessages();
193
- const summary = {
194
- activeMessageCount: activeMessages.length,
195
- systemPrompt: this.getSystemPrompt(),
196
- recentMessages: activeMessages.slice(-5),
197
- // Last 5 active messages
198
- memoryUtilization: this.getMemoryStats().usagePercentage,
199
- hasStoredHistory: this.getStorageStats().totalMessages > 0
200
- };
201
- if (includeStoredContext) {
202
- return {
203
- ...summary,
204
- recentStoredMessages: this.getRecentHistory(10),
205
- // Last 10 stored messages
206
- storageStats: this.getStorageStats()
207
- };
208
- }
209
- return summary;
210
- }
211
- /**
212
- * Perform maintenance operations
213
- * Optimizes storage and cleans up resources
214
- */
215
- performMaintenance() {
216
- }
217
- /**
218
- * Clean up resources and dispose of components
219
- */
220
- dispose() {
221
- this.memoryWindow.dispose();
222
- this.contentStorage.dispose();
223
- this.tokenCounter.dispose();
224
- }
225
- };
226
- _SmartMemoryManager.DEFAULT_CONFIG = {
227
- maxTokens: 8e3,
228
- reserveTokens: 1e3,
229
- modelName: "gpt-4o",
230
- storageLimit: 1e3
231
- };
232
- let SmartMemoryManager = _SmartMemoryManager;
98
+ shape[key] = zodType;
99
+ }
100
+ return z.object(shape);
101
+ }
102
+ function convertType(schema) {
103
+ if (!schema || typeof schema !== "object" || !("type" in schema)) {
104
+ return z.unknown();
105
+ }
106
+ const schemaObj = schema;
107
+ let zodType;
108
+ switch (schemaObj.type) {
109
+ case "string":
110
+ zodType = z.string();
111
+ if (schemaObj.enum && Array.isArray(schemaObj.enum)) {
112
+ zodType = z.enum(schemaObj.enum);
113
+ }
114
+ break;
115
+ case "number":
116
+ zodType = z.number();
117
+ if ("minimum" in schemaObj && typeof schemaObj.minimum === "number") {
118
+ zodType = zodType.min(schemaObj.minimum);
119
+ }
120
+ if ("maximum" in schemaObj && typeof schemaObj.maximum === "number") {
121
+ zodType = zodType.max(schemaObj.maximum);
122
+ }
123
+ break;
124
+ case "integer":
125
+ zodType = z.number().int();
126
+ if ("minimum" in schemaObj && typeof schemaObj.minimum === "number") {
127
+ zodType = zodType.min(schemaObj.minimum);
128
+ }
129
+ if ("maximum" in schemaObj && typeof schemaObj.maximum === "number") {
130
+ zodType = zodType.max(schemaObj.maximum);
131
+ }
132
+ break;
133
+ case "boolean":
134
+ zodType = z.boolean();
135
+ break;
136
+ case "array":
137
+ if (schemaObj.items) {
138
+ zodType = z.array(convertType(schemaObj.items));
139
+ } else {
140
+ zodType = z.array(z.unknown());
141
+ }
142
+ break;
143
+ case "object":
144
+ if ("properties" in schemaObj) {
145
+ zodType = jsonSchemaToZod(schemaObj);
146
+ } else {
147
+ zodType = z.object({}).passthrough();
148
+ }
149
+ break;
150
+ default:
151
+ zodType = z.unknown();
152
+ }
153
+ if ("description" in schemaObj && typeof schemaObj.description === "string") {
154
+ zodType = zodType.describe(schemaObj.description);
155
+ }
156
+ return zodType;
157
+ }
233
158
  export {
234
- SmartMemoryManager
159
+ convertMCPToolToLangChain
235
160
  };
236
161
  //# sourceMappingURL=index17.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index17.js","sources":["../../src/memory/SmartMemoryManager.ts"],"sourcesContent":["import type { BaseMessage } from '@langchain/core/messages';\nimport { MemoryWindow } from './MemoryWindow';\nimport { ContentStorage } from './ContentStorage';\nimport { TokenCounter } from './TokenCounter';\n\n/**\n * Configuration for SmartMemoryManager\n */\nexport interface SmartMemoryConfig {\n /** Maximum tokens for active memory window */\n maxTokens?: number;\n /** Reserve tokens for response generation */\n reserveTokens?: number;\n /** Model name for token counting */\n modelName?: string;\n /** Maximum messages to store in content storage */\n storageLimit?: number;\n}\n\n/**\n * Search options for history search\n */\nexport interface SearchOptions {\n /** Whether to perform case-sensitive search */\n caseSensitive?: boolean;\n /** Maximum number of results to return */\n limit?: number;\n /** Whether to use regex pattern matching */\n useRegex?: boolean;\n}\n\n/**\n * Memory statistics for active memory window\n */\nexport interface MemoryStats {\n /** Total active messages in memory window */\n totalActiveMessages: number;\n /** Current token count including system prompt */\n currentTokenCount: number;\n /** Maximum token capacity */\n maxTokens: number;\n /** Remaining token capacity */\n remainingCapacity: number;\n /** System prompt token count */\n systemPromptTokens: number;\n /** Memory usage percentage */\n usagePercentage: number;\n}\n\n/**\n * Smart memory manager that combines active memory window with long-term storage\n * Provides context-aware memory management with automatic pruning and searchable history\n */\nexport class SmartMemoryManager {\n private memoryWindow: MemoryWindow;\n private contentStorage: ContentStorage;\n private tokenCounter: TokenCounter;\n private config: Required<SmartMemoryConfig>;\n\n // Default configuration values\n private static readonly DEFAULT_CONFIG: Required<SmartMemoryConfig> = {\n maxTokens: 8000,\n reserveTokens: 1000,\n modelName: 'gpt-4o',\n storageLimit: 1000\n };\n\n constructor(config: SmartMemoryConfig = {}) {\n this.config = { ...SmartMemoryManager.DEFAULT_CONFIG, ...config };\n \n // Initialize components\n this.tokenCounter = new TokenCounter(this.config.modelName as any);\n this.contentStorage = new ContentStorage(this.config.storageLimit);\n this.memoryWindow = new MemoryWindow(\n this.config.maxTokens,\n this.config.reserveTokens,\n this.tokenCounter\n );\n }\n\n /**\n * Add a message to the active memory window\n * Automatically handles pruning and storage of displaced messages\n * @param message - Message to add\n */\n addMessage(message: BaseMessage): void {\n const result = this.memoryWindow.addMessage(message);\n \n // Store any pruned messages in content storage\n if (result.prunedMessages.length > 0) {\n this.contentStorage.storeMessages(result.prunedMessages);\n }\n }\n\n /**\n * Get all active messages from the memory window\n * @returns Array of active messages in chronological order\n */\n getMessages(): BaseMessage[] {\n return this.memoryWindow.getMessages();\n }\n\n /**\n * Clear active memory window\n * @param clearStorage - Whether to also clear the content storage (default: false)\n */\n clear(clearStorage: boolean = false): void {\n this.memoryWindow.clear();\n \n if (clearStorage) {\n this.contentStorage.clear();\n }\n }\n\n /**\n * Set the system prompt for the memory window\n * @param systemPrompt - System prompt text\n */\n setSystemPrompt(systemPrompt: string): void {\n this.memoryWindow.setSystemPrompt(systemPrompt);\n }\n\n /**\n * Get the current system prompt\n * @returns Current system prompt text\n */\n getSystemPrompt(): string {\n return this.memoryWindow.getSystemPrompt();\n }\n\n /**\n * Search through stored message history\n * @param query - Search term or pattern\n * @param options - Search configuration\n * @returns Array of matching messages from history\n */\n searchHistory(query: string, options: SearchOptions = {}): BaseMessage[] {\n return this.contentStorage.searchMessages(query, options);\n }\n\n /**\n * Get recent messages from storage history\n * @param count - Number of recent messages to retrieve\n * @returns Array of recent messages from storage\n */\n getRecentHistory(count: number): BaseMessage[] {\n return this.contentStorage.getRecentMessages(count);\n }\n\n /**\n * Check if a message can be added without exceeding limits\n * @param message - Message to test\n * @returns True if message can be added\n */\n canAddMessage(message: BaseMessage): boolean {\n return this.memoryWindow.canAddMessage(message);\n }\n\n /**\n * Get statistics about the active memory window\n * @returns Memory usage statistics\n */\n getMemoryStats(): MemoryStats {\n const windowStats = this.memoryWindow.getStats();\n \n return {\n totalActiveMessages: windowStats.totalMessages,\n currentTokenCount: windowStats.currentTokens,\n maxTokens: windowStats.maxTokens,\n remainingCapacity: windowStats.remainingCapacity,\n systemPromptTokens: windowStats.systemPromptTokens,\n usagePercentage: windowStats.usagePercentage\n };\n }\n\n /**\n * Get statistics about the content storage\n * @returns Storage usage statistics\n */\n getStorageStats() {\n return this.contentStorage.getStorageStats();\n }\n\n /**\n * Get combined statistics for both active memory and storage\n * @returns Combined memory and storage statistics\n */\n getOverallStats() {\n const memoryStats = this.getMemoryStats();\n const storageStats = this.getStorageStats();\n \n return {\n activeMemory: memoryStats,\n storage: storageStats,\n totalMessagesManaged: memoryStats.totalActiveMessages + storageStats.totalMessages,\n activeMemoryUtilization: memoryStats.usagePercentage,\n storageUtilization: storageStats.usagePercentage\n };\n }\n\n /**\n * Update the configuration and apply changes\n * @param newConfig - New configuration options\n */\n updateConfig(newConfig: Partial<SmartMemoryConfig>): void {\n this.config = { ...this.config, ...newConfig };\n \n // Update components with new configuration\n if (newConfig.maxTokens !== undefined || newConfig.reserveTokens !== undefined) {\n this.memoryWindow.updateLimits(\n this.config.maxTokens,\n this.config.reserveTokens\n );\n }\n \n if (newConfig.storageLimit !== undefined) {\n this.contentStorage.updateStorageLimit(this.config.storageLimit);\n }\n \n // Note: Model name changes would require recreating the token counter\n // This is not implemented to avoid disrupting ongoing operations\n }\n\n /**\n * Get current configuration\n * @returns Current configuration settings\n */\n getConfig(): Required<SmartMemoryConfig> {\n return { ...this.config };\n }\n\n /**\n * Get messages from storage within a time range\n * @param startTime - Start of time range\n * @param endTime - End of time range\n * @returns Messages within the specified time range\n */\n getHistoryFromTimeRange(startTime: Date, endTime: Date): BaseMessage[] {\n return this.contentStorage.getMessagesFromTimeRange(startTime, endTime);\n }\n\n /**\n * Get messages from storage by message type\n * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.)\n * @param limit - Maximum number of messages to return\n * @returns Messages of the specified type\n */\n getHistoryByType(messageType: string, limit?: number): BaseMessage[] {\n return this.contentStorage.getMessagesByType(messageType, limit);\n }\n\n /**\n * Get recent messages from storage within the last N minutes\n * @param minutes - Number of minutes to look back\n * @returns Messages from the last N minutes\n */\n getRecentHistoryByTime(minutes: number): BaseMessage[] {\n return this.contentStorage.getRecentMessagesByTime(minutes);\n }\n\n /**\n * Export the current state for persistence or analysis\n * @returns Serializable representation of memory state\n */\n exportState() {\n return {\n config: this.config,\n activeMessages: this.memoryWindow.getMessages().map(msg => ({\n content: msg.content,\n type: msg._getType()\n })),\n systemPrompt: this.memoryWindow.getSystemPrompt(),\n memoryStats: this.getMemoryStats(),\n storageStats: this.getStorageStats(),\n storedMessages: this.contentStorage.exportMessages()\n };\n }\n\n /**\n * Get a summary of conversation context for external use\n * Useful for providing context to other systems or for logging\n * @param includeStoredContext - Whether to include recent stored messages\n * @returns Context summary object\n */\n getContextSummary(includeStoredContext: boolean = false) {\n const activeMessages = this.getMessages();\n const summary = {\n activeMessageCount: activeMessages.length,\n systemPrompt: this.getSystemPrompt(),\n recentMessages: activeMessages.slice(-5), // Last 5 active messages\n memoryUtilization: this.getMemoryStats().usagePercentage,\n hasStoredHistory: this.getStorageStats().totalMessages > 0\n };\n\n if (includeStoredContext) {\n return {\n ...summary,\n recentStoredMessages: this.getRecentHistory(10), // Last 10 stored messages\n storageStats: this.getStorageStats()\n };\n }\n\n return summary;\n }\n\n /**\n * Perform maintenance operations\n * Optimizes storage and cleans up resources\n */\n performMaintenance(): void {\n // No specific maintenance needed currently\n // This method is reserved for future optimizations\n }\n\n /**\n * Clean up resources and dispose of components\n */\n dispose(): void {\n this.memoryWindow.dispose();\n this.contentStorage.dispose();\n this.tokenCounter.dispose();\n }\n}"],"names":[],"mappings":";;;AAqDO,MAAM,sBAAN,MAAM,oBAAmB;AAAA,EAc9B,YAAY,SAA4B,IAAI;AAC1C,SAAK,SAAS,EAAE,GAAG,oBAAmB,gBAAgB,GAAG,OAAA;AAGzD,SAAK,eAAe,IAAI,aAAa,KAAK,OAAO,SAAgB;AACjE,SAAK,iBAAiB,IAAI,eAAe,KAAK,OAAO,YAAY;AACjE,SAAK,e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"index17.js","sources":["../../src/mcp/adapters/langchain.ts"],"sourcesContent":["import { DynamicStructuredTool } from '@langchain/core/tools';\nimport { z } from 'zod';\nimport type { MCPToolInfo, MCPServerConfig } from '../types';\nimport type { MCPClientManager } from '../MCPClientManager';\nimport { ContentStoreService, shouldUseReference } from '@hashgraphonline/standards-sdk';\nimport type { ContentSource } from '../../types/content-reference';\n\n/**\n * Convert an MCP tool to a LangChain DynamicStructuredTool\n */\nexport function convertMCPToolToLangChain(\n tool: MCPToolInfo,\n mcpManager: MCPClientManager,\n serverConfig?: MCPServerConfig\n): DynamicStructuredTool {\n const zodSchema = jsonSchemaToZod(tool.inputSchema);\n\n const sanitizedName = `${tool.serverName}_${tool.name}`.replace(\n /[^a-zA-Z0-9_]/g,\n '_'\n );\n\n let description = tool.description || `MCP tool ${tool.name} from ${tool.serverName}`;\n \n if (serverConfig?.toolDescriptions?.[tool.name]) {\n description = `${description}\\n\\n${serverConfig.toolDescriptions[tool.name]}`;\n }\n \n if (serverConfig?.additionalContext) {\n description = `${description}\\n\\nContext: ${serverConfig.additionalContext}`;\n }\n\n return new DynamicStructuredTool({\n name: sanitizedName,\n description,\n schema: zodSchema,\n func: async (input) => {\n try {\n const result = await mcpManager.executeTool(\n tool.serverName,\n tool.name,\n input\n );\n\n let responseText = '';\n \n if (typeof result === 'string') {\n responseText = result;\n } else if (\n result &&\n typeof result === 'object' &&\n 'content' in result\n ) {\n const content = (result as { content: unknown }).content;\n if (Array.isArray(content)) {\n const textParts = content\n .filter(\n (item): item is { type: string; text: string } =>\n typeof item === 'object' &&\n item !== null &&\n 'type' in item &&\n item.type === 'text' &&\n 'text' in item\n )\n .map((item) => item.text);\n responseText = textParts.join('\\n');\n } else {\n responseText = JSON.stringify(content);\n }\n } else {\n responseText = JSON.stringify(result);\n }\n\n // Check if content should be stored as reference\n const responseBuffer = Buffer.from(responseText, 'utf8');\n console.log(`[MCP Adapter] Response size: ${responseBuffer.length} bytes, tool: ${tool.serverName}_${tool.name}`);\n \n // Use a lower threshold for MCP tools (10KB) to avoid token limit issues\n const MCP_REFERENCE_THRESHOLD = 10 * 1024; // 10KB\n const shouldStoreMCPContent = responseBuffer.length > MCP_REFERENCE_THRESHOLD;\n \n if (shouldStoreMCPContent || shouldUseReference(responseBuffer)) {\n console.log(`[MCP Adapter] Content exceeds threshold (${responseBuffer.length} > ${MCP_REFERENCE_THRESHOLD}), storing as reference`);\n const contentStore = ContentStoreService.getInstance();\n if (contentStore) {\n try {\n const referenceId = await contentStore.storeContent(responseBuffer, {\n contentType: 'text' as ContentSource,\n source: 'mcp',\n mcpToolName: `${tool.serverName}_${tool.name}`,\n originalSize: responseBuffer.length\n });\n console.log(`[MCP Adapter] Stored content as reference: content-ref:${referenceId}`);\n return `content-ref:${referenceId}`;\n } catch (storeError) {\n // If storage fails, fall back to returning the content\n console.warn('Failed to store large MCP content as reference:', storeError);\n }\n } else {\n console.warn('[MCP Adapter] ContentStoreService not available');\n }\n }\n\n return responseText;\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n return `Error executing MCP tool ${tool.name}: ${errorMessage}`;\n }\n },\n });\n}\n\n/**\n * Convert JSON Schema to Zod schema\n * This is a simplified converter that handles common cases\n */\nfunction jsonSchemaToZod(schema: unknown): z.ZodTypeAny {\n if (!schema || typeof schema !== 'object') {\n return z.object({});\n }\n\n const schemaObj = schema as Record<string, unknown>;\n\n if (schemaObj.type && schemaObj.type !== 'object') {\n return convertType(schemaObj);\n }\n\n if (!schemaObj.properties || typeof schemaObj.properties !== 'object') {\n return z.object({});\n }\n\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const [key, value] of Object.entries(schemaObj.properties)) {\n let zodType = convertType(value);\n\n const isRequired =\n Array.isArray(schemaObj.required) && schemaObj.required.includes(key);\n if (!isRequired) {\n zodType = zodType.optional();\n }\n\n shape[key] = zodType;\n }\n\n return z.object(shape);\n}\n\n/**\n * Convert a single JSON Schema type to Zod\n */\nfunction convertType(schema: unknown): z.ZodTypeAny {\n if (!schema || typeof schema !== 'object' || !('type' in schema)) {\n return z.unknown();\n }\n\n const schemaObj = schema as {\n type: string;\n enum?: unknown[];\n items?: unknown;\n };\n let zodType: z.ZodTypeAny;\n\n switch (schemaObj.type) {\n case 'string':\n zodType = z.string();\n if (schemaObj.enum && Array.isArray(schemaObj.enum)) {\n zodType = z.enum(schemaObj.enum as [string, ...string[]]);\n }\n break;\n\n case 'number':\n zodType = z.number();\n if ('minimum' in schemaObj && typeof schemaObj.minimum === 'number') {\n zodType = (zodType as z.ZodNumber).min(schemaObj.minimum);\n }\n if ('maximum' in schemaObj && typeof schemaObj.maximum === 'number') {\n zodType = (zodType as z.ZodNumber).max(schemaObj.maximum);\n }\n break;\n\n case 'integer':\n zodType = z.number().int();\n if ('minimum' in schemaObj && typeof schemaObj.minimum === 'number') {\n zodType = (zodType as z.ZodNumber).min(schemaObj.minimum);\n }\n if ('maximum' in schemaObj && typeof schemaObj.maximum === 'number') {\n zodType = (zodType as z.ZodNumber).max(schemaObj.maximum);\n }\n break;\n\n case 'boolean':\n zodType = z.boolean();\n break;\n\n case 'array':\n if (schemaObj.items) {\n zodType = z.array(convertType(schemaObj.items));\n } else {\n zodType = z.array(z.unknown());\n }\n break;\n\n case 'object':\n if ('properties' in schemaObj) {\n zodType = jsonSchemaToZod(schemaObj);\n } else {\n zodType = z.object({}).passthrough();\n }\n break;\n\n default:\n zodType = z.unknown();\n }\n\n if ('description' in schemaObj && typeof schemaObj.description === 'string') {\n zodType = zodType.describe(schemaObj.description);\n }\n\n return zodType;\n}\n"],"names":[],"mappings":";;;AAUO,SAAS,0BACd,MACA,YACA,cACuB;AACvB,QAAM,YAAY,gBAAgB,KAAK,WAAW;AAElD,QAAM,gBAAgB,GAAG,KAAK,UAAU,IAAI,KAAK,IAAI,GAAG;AAAA,IACtD;AAAA,IACA;AAAA,EAAA;AAGF,MAAI,cAAc,KAAK,eAAe,YAAY,KAAK,IAAI,SAAS,KAAK,UAAU;AAEnF,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