UNPKG

@utaba/ucm-mcp-server

Version:

Universal Context Manager MCP Server - AI-native artifact management

79 lines 2.72 kB
export class ResponseChunker { static MAX_CHUNK_SIZE = 20000; // ~20k characters to stay under token limit static chunks = new Map(); static CHUNK_TTL = 5 * 60 * 1000; // 5 minutes static chunkTimestamps = new Map(); static chunk(data, chunkId) { const serialized = typeof data === 'string' ? data : JSON.stringify(data, null, 2); // If small enough, return as-is if (serialized.length < this.MAX_CHUNK_SIZE) { return data; } // Generate chunk ID if not provided const id = chunkId || `ucm_chunk_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`; // Split into chunks const chunks = []; for (let i = 0; i < serialized.length; i += this.MAX_CHUNK_SIZE) { chunks.push(serialized.slice(i, i + this.MAX_CHUNK_SIZE)); } // Store chunks for retrieval with timestamp this.chunks.set(id, chunks); this.chunkTimestamps.set(id, Date.now()); // Schedule cleanup after TTL setTimeout(() => { this.cleanup(id); }, this.CHUNK_TTL); // Return first chunk with metadata return { chunk: { id, sequence: 0, total: chunks.length, data: chunks[0] }, hasMore: chunks.length > 1 }; } static getNextChunk(chunkId, sequence) { const chunks = this.chunks.get(chunkId); if (!chunks || sequence >= chunks.length || sequence < 0) { return null; } // Update timestamp to extend TTL this.chunkTimestamps.set(chunkId, Date.now()); return { chunk: { id: chunkId, sequence, total: chunks.length, data: chunks[sequence] }, hasMore: sequence < chunks.length - 1 }; } static cleanup(chunkId) { this.chunks.delete(chunkId); this.chunkTimestamps.delete(chunkId); } static cleanupExpired() { const now = Date.now(); for (const [id, timestamp] of this.chunkTimestamps.entries()) { if (now - timestamp > this.CHUNK_TTL) { this.cleanup(id); } } } static getChunkInfo(chunkId) { const chunks = this.chunks.get(chunkId); const timestamp = this.chunkTimestamps.get(chunkId); if (!chunks || !timestamp) { return { exists: false }; } return { exists: true, total: chunks.length, expires: timestamp + this.CHUNK_TTL }; } } //# sourceMappingURL=ResponseChunker.js.map