Skip to content

feat: Add vector index create and update #252

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 7 commits into from
May 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/tools/mongodb/create/createVectorIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { buildVectorFields, DbOperationArgs, MongoDBToolBase, VectorIndexArgs } from "../mongodbTool.js";
import { OperationType, ToolArgs } from "../../tool.js";

const VECTOR_INDEX_TYPE = "vectorSearch";
export class CreateVectorIndexTool extends MongoDBToolBase {
protected name = "create-vector-index";
protected description = "Create an Atlas Vector Search Index for a collection.";
protected argsShape = {
...DbOperationArgs,
name: VectorIndexArgs.name,
vectorDefinition: VectorIndexArgs.vectorDefinition,
filterFields: VectorIndexArgs.filterFields,
};

protected operationType: OperationType = "create";

protected async execute({
database,
collection,
name,
vectorDefinition,
filterFields,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = await this.ensureConnected();

const indexes = await provider.createSearchIndexes(database, collection, [
{
name,
type: VECTOR_INDEX_TYPE,
definition: { fields: buildVectorFields(vectorDefinition, filterFields) },
},
]);

return {
content: [
{
text: `Created the vector index ${indexes[0]} on collection "${collection}" in database "${database}"`,
type: "text",
},
],
};
}
}
60 changes: 59 additions & 1 deletion src/tools/mongodb/mongodbTool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { z } from "zod";
import { ToolArgs, ToolBase, ToolCategory, TelemetryToolMetadata } from "../tool.js";
import { TelemetryToolMetadata, ToolArgs, ToolBase, ToolCategory } from "../tool.js";
import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { ErrorCodes, MongoDBError } from "../../errors.js";
Expand All @@ -10,6 +10,64 @@ export const DbOperationArgs = {
collection: z.string().describe("Collection name"),
};

export enum VectorFieldType {
VECTOR = "vector",
FILTER = "filter",
}
export const VectorIndexArgs = {
name: z.string().describe("The name of the index"),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: maybe to add .min(1) to strict the validation a bit?

vectorDefinition: z
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: we could use z.strictObject to forbid unexpected fields in the input.

Copy link
Collaborator Author

@edgarw19 edgarw19 May 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering why the existing repo doesn't use strictObject. Maybe it allows some flexibility in including additional fields that perhaps the API now accepts but the MCP server has not been updated to reflect?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can also circumvent that by exposing your schema information to the chatbot (so index json passed is always up to date with what MCP server wants to support)

.object({
path: z
.string()
.min(1)
.describe(
"Name of the field to index. For nested fields, use dot notation to specify path to embedded fields."
),
numDimensions: z
.number()
.int()
.min(1)
.max(8192)
.describe("Number of vector dimensions to enforce at index-time and query-time."),
similarity: z
.enum(["euclidean", "cosine", "dotProduct"])
.describe("Vector similarity function to use to search for top K-nearest neighbors."),
quantization: z
.enum(["none", "scalar", "binary"])
.default("none")
.optional()
.describe(
"Automatic vector quantization. Use this setting only if your embeddings are float or double vectors."
),
})
.describe("The vector index definition."),
filterFields: z
.array(
z.object({
path: z
.string()
.min(1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a type? Not sure what min(1) means for a string field

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This enforces a minimum length of 1 so empty strings do not pass validation

.describe(
"Name of the field to filter by. For nested fields, use dot notation to specify path to embedded fields."
),
})
)
.optional()
.describe("Additional indexed fields that pre-filter data."),
};

type VectorDefinitionType = z.infer<typeof VectorIndexArgs.vectorDefinition>;
type FilterFieldsType = z.infer<typeof VectorIndexArgs.filterFields>;
export function buildVectorFields(vectorDefinition: VectorDefinitionType, filterFields: FilterFieldsType): object[] {
const typedVectorField = { ...vectorDefinition, type: VectorFieldType.VECTOR };
const typedFilterFields = (filterFields ?? []).map((f) => ({
...f,
type: VectorFieldType.FILTER,
}));
return [typedVectorField, ...typedFilterFields];
}

export const SearchIndexOperationArgs = {
database: z.string().describe("Database name"),
collection: z.string().describe("Collection name"),
Expand Down
4 changes: 4 additions & 0 deletions src/tools/mongodb/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { DropCollectionTool } from "./delete/dropCollection.js";
import { ExplainTool } from "./metadata/explain.js";
import { CreateCollectionTool } from "./create/createCollection.js";
import { LogsTool } from "./metadata/logs.js";
import { CreateVectorIndexTool } from "./create/createVectorIndex.js";
import { UpdateVectorIndexTool } from "./update/updateVectorIndex.js";
import { CollectionSearchIndexesTool } from "./read/collectionSearchIndexes.js";
import { DropSearchIndexTool } from "./delete/dropSearchIndex.js";

Expand All @@ -43,5 +45,7 @@ export const MongoDbTools = [
ExplainTool,
CreateCollectionTool,
LogsTool,
CreateVectorIndexTool,
UpdateVectorIndexTool,
DropSearchIndexTool,
];
41 changes: 41 additions & 0 deletions src/tools/mongodb/update/updateVectorIndex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { buildVectorFields, DbOperationArgs, MongoDBToolBase, VectorIndexArgs } from "../mongodbTool.js";
import { OperationType, ToolArgs } from "../../tool.js";

export class UpdateVectorIndexTool extends MongoDBToolBase {
protected name = "update-vector-index";
protected description = "Updates an Atlas Search vector for a collection";
protected argsShape = {
...DbOperationArgs,
name: VectorIndexArgs.name,
vectorDefinition: VectorIndexArgs.vectorDefinition,
filterFields: VectorIndexArgs.filterFields,
};

protected operationType: OperationType = "create";

protected async execute({
database,
collection,
name,
vectorDefinition,
filterFields,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const provider = await this.ensureConnected();

// @ts-expect-error: Interface expects a SearchIndexDefinition {definition: {fields}}. However,
// passing fields at the root level is necessary for the call to succeed.
await provider.updateSearchIndex(database, collection, name, {
fields: buildVectorFields(vectorDefinition, filterFields),
});

return {
content: [
{
text: `Successfully updated vector index "${name}" on collection "${collection}" in database "${database}"`,
type: "text",
},
],
};
}
}
Loading