-
Notifications
You must be signed in to change notification settings - Fork 155
chore: adds validation for vector search stage's pre-filter expression MCP-242 #696
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 all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
e77cf2e
chore: add validation for vector stage pre-filter
himanshusinghs 66f69ab
Copy fixes
himanshusinghs 697a729
Update tests/integration/tools/mongodb/read/aggregate.test.ts
himanshusinghs 998e6aa
Update tests/integration/tools/mongodb/read/aggregate.test.ts
himanshusinghs 92d5840
chore: another test case
himanshusinghs caf691a
Merge branch 'main' of github.com:mongodb-js/mongodb-mcp-server into …
gagik e266c58
chore: move helper into its own independent method
gagik a1eccb9
chore: rename file
gagik 15780fa
chore: rename test
gagik ac095d4
chore: fix build
gagik 69c7fb7
chore: fix style
gagik dfbb803
chore: add more tests to assert
gagik 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,90 @@ | ||
| // Based on - | ||
|
|
||
| import type z from "zod"; | ||
| import { ErrorCodes, MongoDBError } from "../common/errors.js"; | ||
| import type { VectorSearchStage } from "../tools/mongodb/mongodbSchemas.js"; | ||
| import { type CompositeLogger, LogId } from "../common/logger.js"; | ||
|
|
||
| // https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/#mongodb-vector-search-pre-filter | ||
| const ALLOWED_LOGICAL_OPERATORS = ["$not", "$nor", "$and", "$or"]; | ||
|
|
||
| export type VectorSearchIndex = { | ||
| name: string; | ||
| latestDefinition: { | ||
| fields: Array< | ||
| | { | ||
| type: "vector"; | ||
| } | ||
| | { | ||
| type: "filter"; | ||
| path: string; | ||
| } | ||
| >; | ||
| }; | ||
| }; | ||
|
|
||
| export function assertVectorSearchFilterFieldsAreIndexed({ | ||
| searchIndexes, | ||
| pipeline, | ||
| logger, | ||
| }: { | ||
| searchIndexes: VectorSearchIndex[]; | ||
| pipeline: Record<string, unknown>[]; | ||
| logger: CompositeLogger; | ||
| }): void { | ||
| const searchIndexesWithFilterFields = searchIndexes.reduce<Record<string, string[]>>( | ||
| (indexFieldMap, searchIndex) => { | ||
| const filterFields = searchIndex.latestDefinition.fields | ||
| .map<string | undefined>((field) => { | ||
| return field.type === "filter" ? field.path : undefined; | ||
| }) | ||
| .filter((filterField) => filterField !== undefined); | ||
|
|
||
| indexFieldMap[searchIndex.name] = filterFields; | ||
| return indexFieldMap; | ||
| }, | ||
| {} | ||
| ); | ||
| for (const stage of pipeline) { | ||
| if ("$vectorSearch" in stage) { | ||
| const { $vectorSearch: vectorSearchStage } = stage as z.infer<typeof VectorSearchStage>; | ||
| const allowedFilterFields = searchIndexesWithFilterFields[vectorSearchStage.index]; | ||
| if (!allowedFilterFields) { | ||
| logger.warning({ | ||
| id: LogId.toolValidationError, | ||
| context: "aggregate tool", | ||
| message: `Could not assert if filter fields are indexed - No filter fields found for index ${vectorSearchStage.index}`, | ||
| }); | ||
| return; | ||
| } | ||
|
|
||
| const filterFieldsInStage = collectFieldsFromVectorSearchFilter(vectorSearchStage.filter); | ||
| const filterFieldsNotIndexed = filterFieldsInStage.filter((field) => !allowedFilterFields.includes(field)); | ||
| if (filterFieldsNotIndexed.length) { | ||
| throw new MongoDBError( | ||
| ErrorCodes.AtlasVectorSearchInvalidQuery, | ||
| `Vector search stage contains filter on fields that are not indexed by index ${vectorSearchStage.index} - ${filterFieldsNotIndexed.join(", ")}` | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export function collectFieldsFromVectorSearchFilter(filter: unknown): string[] { | ||
| if (!filter || typeof filter !== "object" || !Object.keys(filter).length) { | ||
| return []; | ||
| } | ||
|
|
||
| const collectedFields = Object.entries(filter).reduce<string[]>((collectedFields, [maybeField, fieldMQL]) => { | ||
| if (ALLOWED_LOGICAL_OPERATORS.includes(maybeField) && Array.isArray(fieldMQL)) { | ||
| return fieldMQL.flatMap((mql) => collectFieldsFromVectorSearchFilter(mql)); | ||
| } | ||
|
|
||
| if (!ALLOWED_LOGICAL_OPERATORS.includes(maybeField)) { | ||
| collectedFields.push(maybeField); | ||
| } | ||
| return collectedFields; | ||
| }, []); | ||
|
|
||
| return Array.from(new Set(collectedFields)); | ||
| } | ||
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,86 @@ | ||
| import z from "zod"; | ||
| import { zEJSON } from "../args.js"; | ||
|
|
||
| export const zVoyageModels = z | ||
| .enum(["voyage-3-large", "voyage-3.5", "voyage-3.5-lite", "voyage-code-3"]) | ||
| .default("voyage-3-large"); | ||
|
|
||
| // Zod does not undestand JS boxed numbers (like Int32) as integer literals, | ||
| // so we preprocess them to unwrap them so Zod understands them. | ||
| function unboxNumber(v: unknown): number { | ||
| if (v && typeof v === "object" && typeof v.valueOf === "function") { | ||
| const n = Number(v.valueOf()); | ||
| if (!Number.isNaN(n)) return n; | ||
| } | ||
| return v as number; | ||
| } | ||
|
|
||
| export const zVoyageEmbeddingParameters = z.object({ | ||
| outputDimension: z | ||
| .preprocess( | ||
| unboxNumber, | ||
| z.union([z.literal(256), z.literal(512), z.literal(1024), z.literal(2048), z.literal(4096)]) | ||
| ) | ||
| .optional() | ||
| .default(1024), | ||
| outputDtype: z.enum(["float", "int8", "uint8", "binary", "ubinary"]).optional().default("float"), | ||
| }); | ||
|
|
||
| export const zVoyageAPIParameters = zVoyageEmbeddingParameters | ||
| .extend({ | ||
| inputType: z.enum(["query", "document"]), | ||
| }) | ||
| .strip(); | ||
|
|
||
| export type VoyageModels = z.infer<typeof zVoyageModels>; | ||
| export type VoyageEmbeddingParameters = z.infer<typeof zVoyageEmbeddingParameters> & EmbeddingParameters; | ||
|
|
||
| export type EmbeddingParameters = { | ||
| inputType: "query" | "document"; | ||
| }; | ||
|
|
||
| export const zSupportedEmbeddingParameters = zVoyageEmbeddingParameters.extend({ model: zVoyageModels }); | ||
| export type SupportedEmbeddingParameters = z.infer<typeof zSupportedEmbeddingParameters>; | ||
|
|
||
| export const AnyVectorSearchStage = zEJSON(); | ||
| export const VectorSearchStage = z.object({ | ||
| $vectorSearch: z | ||
| .object({ | ||
| exact: z | ||
| .boolean() | ||
| .optional() | ||
| .default(false) | ||
| .describe( | ||
| "When true, uses an ENN algorithm, otherwise uses ANN. Using ENN is not compatible with numCandidates, in that case, numCandidates must be left empty." | ||
| ), | ||
| index: z.string().describe("Name of the index, as retrieved from the `collection-indexes` tool."), | ||
| path: z | ||
| .string() | ||
| .describe( | ||
| "Field, in dot notation, where to search. There must be a vector search index for that field. Note to LLM: When unsure, use the 'collection-indexes' tool to validate that the field is indexed with a vector search index." | ||
| ), | ||
| queryVector: z | ||
| .union([z.string(), z.array(z.number())]) | ||
| .describe( | ||
| "The content to search for. The embeddingParameters field is mandatory if the queryVector is a string, in that case, the tool generates the embedding automatically using the provided configuration." | ||
| ), | ||
| numCandidates: z | ||
| .number() | ||
| .int() | ||
| .positive() | ||
| .optional() | ||
| .describe("Number of candidates for the ANN algorithm. Mandatory when exact is false."), | ||
| limit: z.number().int().positive().optional().default(10), | ||
| filter: zEJSON() | ||
| .optional() | ||
| .describe( | ||
| "MQL filter that can only use filter fields from the index definition. Note to LLM: If unsure, use the `collection-indexes` tool to learn which fields can be used for filtering." | ||
| ), | ||
| embeddingParameters: zSupportedEmbeddingParameters | ||
| .optional() | ||
| .describe( | ||
| "The embedding model and its parameters to use to generate embeddings before searching. It is mandatory if queryVector is a string value. Note to LLM: If unsure, ask the user before providing one." | ||
| ), | ||
| }) | ||
| .passthrough(), | ||
| }); |
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
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.