- 
                Notifications
    You must be signed in to change notification settings 
- Fork 153
chore: Add new session-level service for getting embeddings of a specific collection MCP-246 #626
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 19 commits
      Commits
    
    
            Show all changes
          
          
            25 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      8ac71ba
              
                chore: Add new session-level service for getting embeddings of a spec…
              
              
                kmruiz cb52116
              
                chore: add unit tests to embedding validation
              
              
                kmruiz 082fce9
              
                chore: add the ability to disable embedding validation
              
              
                kmruiz ed7a16e
              
                chore: Make sure that cache works
              
              
                kmruiz d68deee
              
                chore: Do not query for the embedding information if the validation i…
              
              
                kmruiz 32fe96d
              
                chore: it can't be undefined anymore, so this check is useless
              
              
                kmruiz 2e013f8
              
                chore: Embedding validation on insert and minor refactor of formatUnt…
              
              
                kmruiz 998cf1b
              
                Merge remote-tracking branch 'origin/main' into chore/mcp-246
              
              
                kmruiz 81f9ddd
              
                Update src/tools/mongodb/create/insertMany.ts
              
              
                kmruiz 0a1c789
              
                chore: Add integration test for insert many
              
              
                kmruiz c68e4ad
              
                chore: Make eslint happy
              
              
                kmruiz 539c4a5
              
                chore: test slightly older image of atlas-local in case it's broken i…
              
              
                kmruiz 44a3ce8
              
                chore: increase timeout time for CI
              
              
                kmruiz a5842ef
              
                chore: minor fixes from the PR comments
              
              
                kmruiz 13c1c35
              
                Merge remote-tracking branch 'origin/main' into chore/mcp-246
              
              
                kmruiz a04c2f3
              
                chore: Merge reliably search permission detection
              
              
                kmruiz 94fdcda
              
                Merge branch 'main' into chore/mcp-246
              
              
                kmruiz 3264796
              
                chore: cleanup embeddings cache when the connection is closed
              
              
                kmruiz 3b104b5
              
                chore: clean up embeddings cache after creating an index
              
              
                kmruiz 19a333c
              
                chore: simplify, assume search indexes are available just by listing …
              
              
                kmruiz 7eed735
              
                chore: add the Manager suffix
              
              
                kmruiz 519a0c4
              
                Merge branch 'main' into chore/mcp-246
              
              
                kmruiz 3d69362
              
                Update src/common/search/vectorSearchEmbeddingsManager.ts
              
              
                kmruiz debc6f9
              
                chore: Remove unused error code and messages
              
              
                kmruiz c0d9dee
              
                chore: use ts private fields for now
              
              
                kmruiz File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| import type { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver"; | ||
| import { BSON, type Document } from "bson"; | ||
| import type { UserConfig } from "../config.js"; | ||
| import type { ConnectionManager } from "../connectionManager.js"; | ||
|  | ||
| export type VectorFieldIndexDefinition = { | ||
| type: "vector"; | ||
| path: string; | ||
| numDimensions: number; | ||
| quantization: "none" | "scalar" | "binary"; | ||
| similarity: "euclidean" | "cosine" | "dotProduct"; | ||
| }; | ||
|  | ||
| export type EmbeddingNamespace = `${string}.${string}`; | ||
| export class VectorSearchEmbeddings { | ||
|         
                  kmruiz marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| constructor( | ||
| private readonly config: UserConfig, | ||
| private readonly connectionManager: ConnectionManager, | ||
| private readonly embeddings: Map<EmbeddingNamespace, VectorFieldIndexDefinition[]> = new Map() | ||
| ) { | ||
| connectionManager.events.on("connection-close", () => { | ||
| this.embeddings.clear(); | ||
| }); | ||
| } | ||
|  | ||
| cleanupEmbeddingsForNamespace({ database, collection }: { database: string; collection: string }): void { | ||
| const embeddingDefKey: EmbeddingNamespace = `${database}.${collection}`; | ||
| this.embeddings.delete(embeddingDefKey); | ||
| } | ||
|  | ||
| async embeddingsForNamespace({ | ||
| database, | ||
| collection, | ||
| }: { | ||
| database: string; | ||
| collection: string; | ||
| }): Promise<VectorFieldIndexDefinition[]> { | ||
| const provider = await this.assertAtlasSearchIsAvailable(); | ||
| if (!provider) { | ||
| return []; | ||
| } | ||
|  | ||
| // We only need the embeddings for validation now, so don't query them if | ||
| // validation is disabled. | ||
| if (this.config.disableEmbeddingsValidation) { | ||
| return []; | ||
| } | ||
|  | ||
| const embeddingDefKey: EmbeddingNamespace = `${database}.${collection}`; | ||
| const definition = this.embeddings.get(embeddingDefKey); | ||
|  | ||
| if (!definition) { | ||
| const allSearchIndexes = await provider.getSearchIndexes(database, collection); | ||
| const vectorSearchIndexes = allSearchIndexes.filter((index) => index.type === "vectorSearch"); | ||
| const vectorFields = vectorSearchIndexes | ||
| // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access | ||
| .flatMap<Document>((index) => (index.latestDefinition?.fields as Document) ?? []) | ||
| .filter((field) => this.isVectorFieldIndexDefinition(field)); | ||
|  | ||
| this.embeddings.set(embeddingDefKey, vectorFields); | ||
| return vectorFields; | ||
| } | ||
|  | ||
| return definition; | ||
| } | ||
|  | ||
| async findFieldsWithWrongEmbeddings( | ||
| { | ||
| database, | ||
| collection, | ||
| }: { | ||
| database: string; | ||
| collection: string; | ||
| }, | ||
| document: Document | ||
| ): Promise<VectorFieldIndexDefinition[]> { | ||
| const provider = await this.assertAtlasSearchIsAvailable(); | ||
| if (!provider) { | ||
| return []; | ||
| } | ||
|  | ||
| // While we can do our best effort to ensure that the embedding validation is correct | ||
| // based on https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-quantization/ | ||
| // it's a complex process so we will also give the user the ability to disable this validation | ||
| if (this.config.disableEmbeddingsValidation) { | ||
| return []; | ||
| } | ||
|  | ||
| const embeddings = await this.embeddingsForNamespace({ database, collection }); | ||
| return embeddings.filter((emb) => !this.documentPassesEmbeddingValidation(emb, document)); | ||
| } | ||
|  | ||
| private async assertAtlasSearchIsAvailable(): Promise<NodeDriverServiceProvider | null> { | ||
| const connectionState = this.connectionManager.currentConnectionState; | ||
| if (connectionState.tag === "connected") { | ||
| if ((await connectionState.getSearchAvailability()) === "available") { | ||
| return connectionState.serviceProvider; | ||
| } | ||
| } | ||
|  | ||
| return null; | ||
| } | ||
|  | ||
| private isVectorFieldIndexDefinition(doc: Document): doc is VectorFieldIndexDefinition { | ||
| return doc["type"] === "vector"; | ||
| } | ||
|  | ||
| private documentPassesEmbeddingValidation(definition: VectorFieldIndexDefinition, document: Document): boolean { | ||
| const fieldPath = definition.path.split("."); | ||
| let fieldRef: unknown = document; | ||
|  | ||
| for (const field of fieldPath) { | ||
| if (fieldRef && typeof fieldRef === "object" && field in fieldRef) { | ||
| fieldRef = (fieldRef as Record<string, unknown>)[field]; | ||
| } else { | ||
| return true; | ||
| } | ||
| } | ||
|  | ||
| switch (definition.quantization) { | ||
| // Because quantization is not defined by the use | ||
| // we have to trust them in the format they use. | ||
| case "none": | ||
| return true; | ||
| case "scalar": | ||
| case "binary": | ||
| if (fieldRef instanceof BSON.Binary) { | ||
| try { | ||
| const elements = fieldRef.toFloat32Array(); | ||
| return elements.length === definition.numDimensions; | ||
| } catch { | ||
| // bits are also supported | ||
| try { | ||
| const bits = fieldRef.toBits(); | ||
| return bits.length === definition.numDimensions; | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
| } else { | ||
| if (!Array.isArray(fieldRef)) { | ||
| return false; | ||
| } | ||
|  | ||
| if (fieldRef.length !== definition.numDimensions) { | ||
| return false; | ||
| } | ||
|  | ||
| if (!fieldRef.every((e) => this.isANumber(e))) { | ||
| return false; | ||
| } | ||
| } | ||
|  | ||
| break; | ||
| } | ||
|  | ||
| return true; | ||
| } | ||
|  | ||
| private isANumber(value: unknown): boolean { | ||
| if (typeof value === "number") { | ||
| return true; | ||
| } | ||
|  | ||
| if ( | ||
| value instanceof BSON.Int32 || | ||
| value instanceof BSON.Decimal128 || | ||
| value instanceof BSON.Double || | ||
| value instanceof BSON.Long | ||
| ) { | ||
| return true; | ||
| } | ||
|  | ||
| return false; | ||
| } | ||
| } | ||
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.