Skip to content
Draft
Show file tree
Hide file tree
Changes from 9 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
27 changes: 27 additions & 0 deletions .github/workflows/cleanup-atlas-env.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
name: "Cleanup stale Atlas test environments"
on:
workflow_dispatch:
schedule:
- cron: "0 0 * * *"

permissions: {}

jobs:
cleanup-envs:
runs-on: ubuntu-latest
steps:
- uses: GitHubSecurityLab/actions-permissions/monitor@v1
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version-file: package.json
cache: "npm"
- name: Install dependencies
run: npm ci
- name: Run cleanup script
env:
MDB_MCP_API_CLIENT_ID: ${{ secrets.TEST_ATLAS_CLIENT_ID }}
MDB_MCP_API_CLIENT_SECRET: ${{ secrets.TEST_ATLAS_CLIENT_SECRET }}
MDB_MCP_API_BASE_URL: ${{ vars.TEST_ATLAS_BASE_URL }}
run: npm run atlas:cleanup
File renamed without changes.
File renamed without changes.
File renamed without changes.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@
"generate": "./scripts/generate.sh",
"test": "vitest --project eslint-rules --project unit-and-integration --coverage",
"pretest:accuracy": "npm run build",
"test:accuracy": "sh ./scripts/accuracy/runAccuracyTests.sh"
"test:accuracy": "sh ./scripts/accuracy/runAccuracyTests.sh",
"atlas:cleanup": "vitest --project atlas-cleanup"
},
"license": "Apache-2.0",
"devDependencies": {
Expand Down
100 changes: 100 additions & 0 deletions scripts/cleanupAtlasTestLeftovers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import type { Group, AtlasOrganization } from "../src/common/atlas/openapi.js";
import { ApiClient } from "../src/common/atlas/apiClient.js";
import { ConsoleLogger } from "../src/common/logger.js";
import { Keychain } from "../src/lib.js";
import { describe, it } from "vitest";

function isOlderThanADay(date: string): boolean {
const oneDayInMs = 24 * 60 * 60 * 1000;
const projectDate = new Date(date);
const currentDate = new Date();
return currentDate.getTime() - projectDate.getTime() > oneDayInMs;
}

async function findTestOrganization(client: ApiClient): Promise<AtlasOrganization> {
const orgs = await client.listOrganizations();
const testOrg = orgs?.results?.find((org) => org.name === "MongoDB MCP Test");

if (!testOrg) {
throw new Error('Test organization "MongoDB MCP Test" not found.');
}

return testOrg;
}

async function findAllTestProjects(client: ApiClient, orgId: string): Promise<Group[]> {
const projects = await client.listOrganizationProjects({
params: {
path: {
orgId,
},
},
});

const testProjects = projects?.results?.filter((proj) => proj.name.startsWith("testProj-")) || [];
return testProjects.filter((proj) => isOlderThanADay(proj.created));
}

async function deleteAllClustersOnStaleProject(client: ApiClient, projectId: string): Promise<void> {
const allClusters = await client
.listClusters({
params: {
path: {
groupId: projectId || "",
},
},
})
.then((res) => res.results || []);

await Promise.allSettled(
allClusters.map((cluster) =>
client.deleteCluster({ params: { path: { groupId: projectId || "", clusterName: cluster.name || "" } } })
)
);
}

async function main(): Promise<void> {
const apiClient = new ApiClient(
{
baseUrl: process.env.MDB_MCP_API_BASE_URL || "https://cloud-dev.mongodb.com",
credentials: {
clientId: process.env.MDB_MCP_API_CLIENT_ID || "",
clientSecret: process.env.MDB_MCP_API_CLIENT_SECRET || "",
},
},
new ConsoleLogger(Keychain.root)
);

const testOrg = await findTestOrganization(apiClient);
const testProjects = await findAllTestProjects(apiClient, testOrg.id || "");

if (testProjects.length === 0) {
console.log("No stale test projects found for cleanup.");
}

for (const project of testProjects) {
console.log(`Cleaning up project: ${project.name} (${project.id})`);
if (!project.id) {
console.warn(`Skipping project with missing ID: ${project.name}`);
continue;
}

await deleteAllClustersOnStaleProject(apiClient, project.id);
await apiClient.deleteProject({
params: {
path: {
groupId: project.id,
},
},
});
console.log(`Deleted project: ${project.name} (${project.id})`);
}

return;
}

describe("Cleanup Atlas Test Leftovers", () => {
it("should clean up stale test projects", async () => {
await main();
});
});
12 changes: 11 additions & 1 deletion src/tools/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export const ALLOWED_CLUSTER_NAME_CHARACTERS_ERROR =
const ALLOWED_PROJECT_NAME_CHARACTERS_REGEX = /^[a-zA-Z0-9\s()@&+:._',-]+$/;
export const ALLOWED_PROJECT_NAME_CHARACTERS_ERROR =
"Project names can't be longer than 64 characters and can only contain letters, numbers, spaces, and the following symbols: ( ) @ & + : . _ - ' ,";

export const CommonArgs = {
string: (): ZodString => z.string().regex(NO_UNICODE_REGEX, NO_UNICODE_ERROR),

Expand All @@ -30,7 +31,7 @@ export const CommonArgs = {
};

export const AtlasArgs = {
projectId: (): z.ZodString => CommonArgs.objectId("projectId"),
projectId: (): z.ZodString => CommonArgs.objectId("projectId").describe("Atlas project ID"),

organizationId: (): z.ZodString => CommonArgs.objectId("organizationId"),

Expand Down Expand Up @@ -70,6 +71,15 @@ export const AtlasArgs = {
z.string().min(1, "Password is required").max(100, "Password must be 100 characters or less"),
};

export const ProjectArgs = {
projectId: AtlasArgs.projectId(),
};

export const ProjectAndClusterArgs = {
...ProjectArgs,
clusterName: AtlasArgs.clusterName().describe("Atlas cluster name"),
};

function toEJSON<T extends object | undefined>(value: T): T {
if (!value) {
return value;
Expand Down
5 changes: 2 additions & 3 deletions src/tools/atlas/connect/connectCluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { inspectCluster } from "../../../common/atlas/cluster.js";
import { ensureCurrentIpInAccessList } from "../../../common/atlas/accessListUtils.js";
import type { AtlasClusterConnectionInfo } from "../../../common/connectionManager.js";
import { getDefaultRoleFromConfig } from "../../../common/atlas/roles.js";
import { AtlasArgs } from "../../args.js";
import { ProjectAndClusterArgs } from "../../args.js";

const addedIpAccessListMessage =
"Note: Your current IP address has been added to the Atlas project's IP access list to enable secure connection.";
Expand All @@ -20,8 +20,7 @@ function sleep(ms: number): Promise<void> {
}

export const ConnectClusterArgs = {
projectId: AtlasArgs.projectId().describe("Atlas project ID"),
clusterName: AtlasArgs.clusterName().describe("Atlas cluster name"),
...ProjectAndClusterArgs,
};

export class ConnectClusterTool extends AtlasToolBase {
Expand Down
4 changes: 2 additions & 2 deletions src/tools/atlas/create/createAccessList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { type OperationType, type ToolArgs } from "../../tool.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { AtlasToolBase } from "../atlasTool.js";
import { makeCurrentIpAccessListEntry, DEFAULT_ACCESS_LIST_COMMENT } from "../../../common/atlas/accessListUtils.js";
import { AtlasArgs, CommonArgs } from "../../args.js";
import { AtlasArgs, CommonArgs, ProjectArgs } from "../../args.js";

export const CreateAccessListArgs = {
projectId: AtlasArgs.projectId().describe("Atlas project ID"),
...ProjectArgs,
ipAddresses: z.array(AtlasArgs.ipAddress()).describe("IP addresses to allow access from").optional(),
cidrBlocks: z.array(AtlasArgs.cidrBlock()).describe("CIDR blocks to allow access from").optional(),
currentIpAddress: z.boolean().describe("Add the current IP address").default(false),
Expand Down
6 changes: 3 additions & 3 deletions src/tools/atlas/create/createDBUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ensureCurrentIpInAccessList } from "../../../common/atlas/accessListUti
import { AtlasArgs, CommonArgs } from "../../args.js";

export const CreateDBUserArgs = {
projectId: AtlasArgs.projectId().describe("Atlas project ID"),
projectId: AtlasArgs.projectId(),
username: AtlasArgs.username().describe("Username for the new user"),
// Models will generate overly simplistic passwords like SecurePassword123 or
// AtlasPassword123, which are easily guessable and exploitable. We're instructing
Expand All @@ -26,7 +26,7 @@ export const CreateDBUserArgs = {
collectionName: CommonArgs.string().describe("Collection name").optional(),
})
)
.describe("Roles for the new user"),
.describe("Roles for the new database user"),
clusters: z
.array(AtlasArgs.clusterName())
.describe("Clusters to assign the user to, leave empty for access to all clusters")
Expand All @@ -35,7 +35,7 @@ export const CreateDBUserArgs = {

export class CreateDBUserTool extends AtlasToolBase {
public name = "atlas-create-db-user";
protected description = "Create an MongoDB Atlas database user";
protected description = "Create a MongoDB Atlas database user";
public operationType: OperationType = "create";
protected argsShape = {
...CreateDBUserArgs,
Expand Down
15 changes: 9 additions & 6 deletions src/tools/atlas/create/createFreeCluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,25 @@ import { type ToolArgs, type OperationType } from "../../tool.js";
import { AtlasToolBase } from "../atlasTool.js";
import type { ClusterDescription20240805 } from "../../../common/atlas/openapi.js";
import { ensureCurrentIpInAccessList } from "../../../common/atlas/accessListUtils.js";
import { AtlasArgs } from "../../args.js";
import { ProjectAndClusterArgs, AtlasArgs } from "../../args.js";

export class CreateFreeClusterTool extends AtlasToolBase {
public name = "atlas-create-free-cluster";
protected description = "Create a free MongoDB Atlas cluster";
public operationType: OperationType = "create";
protected argsShape = {
projectId: AtlasArgs.projectId().describe("Atlas project ID to create the cluster in"),
name: AtlasArgs.clusterName().describe("Name of the cluster"),
...ProjectAndClusterArgs,
region: AtlasArgs.region().describe("Region of the cluster").default("US_EAST_1"),
};

protected async execute({ projectId, name, region }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
protected async execute({
projectId,
clusterName,
region,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
const input = {
groupId: projectId,
name,
clusterName,
clusterType: "REPLICASET",
replicationSpecs: [
{
Expand Down Expand Up @@ -50,7 +53,7 @@ export class CreateFreeClusterTool extends AtlasToolBase {

return {
content: [
{ type: "text", text: `Cluster "${name}" has been created in region "${region}".` },
{ type: "text", text: `Cluster "${clusterName}" has been created in region "${region}".` },
{ type: "text", text: `Double check your access lists to enable your current IP.` },
],
};
Expand Down
2 changes: 1 addition & 1 deletion src/tools/atlas/read/inspectAccessList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { AtlasToolBase } from "../atlasTool.js";
import { AtlasArgs } from "../../args.js";

export const InspectAccessListArgs = {
projectId: AtlasArgs.projectId().describe("Atlas project ID"),
projectId: AtlasArgs.projectId(),
};

export class InspectAccessListTool extends AtlasToolBase {
Expand Down
9 changes: 2 additions & 7 deletions src/tools/atlas/read/inspectCluster.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,14 @@ import { type OperationType, type ToolArgs, formatUntrustedData } from "../../to
import { AtlasToolBase } from "../atlasTool.js";
import type { Cluster } from "../../../common/atlas/cluster.js";
import { inspectCluster } from "../../../common/atlas/cluster.js";
import { AtlasArgs } from "../../args.js";

export const InspectClusterArgs = {
projectId: AtlasArgs.projectId().describe("Atlas project ID"),
clusterName: AtlasArgs.clusterName().describe("Atlas cluster name"),
};
import { ProjectAndClusterArgs } from "../../args.js";

export class InspectClusterTool extends AtlasToolBase {
public name = "atlas-inspect-cluster";
protected description = "Inspect MongoDB Atlas cluster";
public operationType: OperationType = "read";
protected argsShape = {
...InspectClusterArgs,
...ProjectAndClusterArgs,
};

protected async execute({ projectId, clusterName }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
Expand Down
61 changes: 60 additions & 1 deletion tests/integration/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,10 @@ export function setupIntegrationTest(
keychain: new Keychain(),
});

// Mock hasValidAccessToken for tests
// Mock API Client for tests
if (!userConfig.apiClientId && !userConfig.apiClientSecret) {
userConfig.apiClientId = "test";
userConfig.apiClientSecret = "test";
const mockFn = vi.fn().mockResolvedValue(true);
session.apiClient.validateAccessToken = mockFn;
}
Expand Down Expand Up @@ -242,6 +244,16 @@ export const databaseCollectionParameters: ParameterInfo[] = [
{ name: "collection", type: "string", description: "Collection name", required: true },
];

export const projectIdParameters: ParameterInfo[] = [
{ name: "projectId", type: "string", description: "Atlas project ID", required: true },
];

export const createClusterParameters: ParameterInfo[] = [
{ name: "projectId", type: "string", description: "Atlas project ID", required: true },
{ name: "clusterName", type: "string", description: "Atlas cluster name", required: true },
{ name: "region", type: "string", description: "Region of the cluster", required: false },
];

export const databaseCollectionInvalidArgs = [
{},
{ database: "test" },
Expand All @@ -252,6 +264,53 @@ export const databaseCollectionInvalidArgs = [
{ database: "test", collection: [] },
];

export const projectIdInvalidArgs = [
{},
{ projectId: 123 },
{ projectId: [] },
{ projectId: "!✅invalid" },
{ projectId: "invalid-test-project-id" },
];

export const clusterNameInvalidArgs = [
{ clusterName: 123 },
{ clusterName: [] },
{ clusterName: "!✅invalid" },
{ clusterName: "a".repeat(65) }, // too long
];

export const projectAndClusterInvalidArgs = [
{},
{ projectId: "507f1f77bcf86cd799439011" }, // missing clusterName
{ clusterName: "testCluster" }, // missing projectId
{ projectId: 123, clusterName: "testCluster" },
{ projectId: "507f1f77bcf86cd799439011", clusterName: 123 },
{ projectId: "invalid", clusterName: "testCluster" },
{ projectId: "507f1f77bcf86cd799439011", clusterName: "!✅invalid" },
];

export const organizationIdInvalidArgs = [
{ organizationId: 123 },
{ organizationId: [] },
{ organizationId: "!✅invalid" },
{ organizationId: "invalid-test-org-id" },
];

export const orgIdInvalidArgs = [
{ orgId: 123 },
{ orgId: [] },
{ orgId: "!✅invalid" },
{ orgId: "invalid-test-org-id" },
];

export const usernameInvalidArgs = [
{},
{ username: 123 },
{ username: [] },
{ username: "!✅invalid" },
{ username: "a".repeat(101) }, // too long
];

export const databaseInvalidArgs = [{}, { database: 123 }, { database: [] }];

export function validateToolMetadata(
Expand Down
Loading
Loading