vibe-coder-mcp
Version:
Production-ready MCP server with complete agent integration, multi-transport support, and comprehensive development automation tools for AI-assisted workflows.
76 lines (75 loc) • 3.02 kB
JavaScript
import { pipeline } from '@xenova/transformers';
import logger from '../logger.js';
class EmbeddingPipeline {
static task = 'feature-extraction';
static model = 'Xenova/all-MiniLM-L6-v2';
static instance = null;
static async getInstance(progress_callback = null) {
if (this.instance === null) {
logger.info(`Loading embedding model: ${this.model}`);
try {
const options = {};
if (progress_callback) {
options.progress_callback = progress_callback;
}
this.instance = await pipeline(this.task, this.model, options);
logger.info(`Embedding model ${this.model} loaded successfully.`);
}
catch (error) {
logger.error({ err: error }, `Failed to load embedding model ${this.model}`);
throw error;
}
}
if (!this.instance) {
logger.error('Embedding pipeline instance is unexpectedly null after initialization attempt.');
throw new Error('Failed to initialize embedding pipeline instance.');
}
return this.instance;
}
}
export async function generateEmbedding(text) {
logger.debug(`Generating embedding for text: "${text.substring(0, 50)}..."`);
try {
const extractor = await EmbeddingPipeline.getInstance();
const output = await extractor(text, { pooling: 'mean', normalize: true });
if (output.data instanceof Float32Array) {
const vector = Array.from(output.data);
logger.debug(`Successfully generated embedding vector of length ${vector.length}.`);
return vector;
}
else {
logger.error({ dataType: typeof output.data }, 'Unexpected data type received from embedding pipeline');
return [];
}
}
catch (error) {
logger.error({ err: error, textSnippet: text.substring(0, 100) }, 'Failed to generate embedding');
return [];
}
}
export function cosineSimilarity(vecA, vecB) {
if (!vecA || !vecB || vecA.length === 0 || vecB.length === 0) {
logger.warn('Cosine similarity called with invalid vectors (empty or null).');
return 0;
}
if (vecA.length !== vecB.length) {
logger.warn(`Cosine similarity called with vectors of different lengths (${vecA.length} vs ${vecB.length}).`);
return 0;
}
let dotProduct = 0;
let magnitudeA = 0;
let magnitudeB = 0;
for (let i = 0; i < vecA.length; i++) {
dotProduct += vecA[i] * vecB[i];
magnitudeA += vecA[i] * vecA[i];
magnitudeB += vecB[i] * vecB[i];
}
magnitudeA = Math.sqrt(magnitudeA);
magnitudeB = Math.sqrt(magnitudeB);
if (magnitudeA === 0 || magnitudeB === 0) {
logger.debug('Cosine similarity involved a zero vector.');
return 0;
}
const similarity = dotProduct / (magnitudeA * magnitudeB);
return Math.max(-1, Math.min(1, similarity));
}