Skip to content

feat: add DB users tools #41

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 4 commits into from
Apr 10, 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
2 changes: 2 additions & 0 deletions scripts/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ function filterOpenapi(openapi: OpenAPIV3_1.Document): OpenAPIV3_1.Document {
"listClusters",
"createCluster",
"listClustersForAllProjects",
"createDatabaseUser",
"listDatabaseUsers",
"listProjectIpAccessLists",
"createProjectIpAccessList",
];
Expand Down
13 changes: 13 additions & 0 deletions src/common/atlas/client.ts → src/common/atlas/apiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
PaginatedClusterDescription20240805,
PaginatedNetworkAccessView,
NetworkPermissionEntry,
CloudDatabaseUser,
PaginatedApiAtlasDatabaseUserView,
} from "./openapi.js";

export interface OAuthToken {
Expand Down Expand Up @@ -310,4 +312,15 @@ export class ApiClient {
body: JSON.stringify(cluster),
});
}

async createDatabaseUser(groupId: string, user: CloudDatabaseUser): Promise<CloudDatabaseUser> {
return await this.do<CloudDatabaseUser>(`/groups/${groupId}/databaseUsers`, {
method: "POST",
body: JSON.stringify(user),
});
}

async listDatabaseUsers(groupId: string): Promise<PaginatedApiAtlasDatabaseUserView> {
return await this.do<PaginatedApiAtlasDatabaseUserView>(`/groups/${groupId}/databaseUsers`);
}
}
2 changes: 1 addition & 1 deletion src/common/atlas/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApiClient } from "./client";
import { ApiClient } from "./apiClient";
import { State } from "../../state";

export async function ensureAuthenticated(state: State, apiClient: ApiClient): Promise<void> {
Expand Down
229 changes: 229 additions & 0 deletions src/common/atlas/openapi.d.ts

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ export const config = {
apiBaseURL: process.env.API_BASE_URL || "https://cloud.mongodb.com/",
clientID: process.env.CLIENT_ID || "0oabtxactgS3gHIR0297",
stateFile: process.env.STATE_FILE || path.resolve("./state.json"),
projectID: process.env.PROJECT_ID,
userAgent: `AtlasMCP/${packageJson.version} (${process.platform}; ${process.arch}; ${process.env.HOSTNAME || "unknown"})`,
};

Expand Down
2 changes: 1 addition & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { ApiClient } from "./common/atlas/client.js";
import { ApiClient } from "./common/atlas/apiClient.js";
import { State, saveState, loadState } from "./state.js";
import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { registerAtlasTools } from "./tools/atlas/tools.js";
Expand Down
2 changes: 1 addition & 1 deletion src/state.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from "fs";
import config from "./config.js";
import { OauthDeviceCode, OAuthToken } from "./common/atlas/client.js";
import { OauthDeviceCode, OAuthToken } from "./common/atlas/apiClient.js";

export interface State {
auth: {
Expand Down
2 changes: 1 addition & 1 deletion src/tools/atlas/atlasTool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ToolBase } from "../tool.js";
import { ApiClient } from "../../common/atlas/client.js";
import { ApiClient } from "../../common/atlas/apiClient.js";
import { State } from "../../state.js";
import { ensureAuthenticated } from "../../common/atlas/auth.js";

Expand Down
62 changes: 62 additions & 0 deletions src/tools/atlas/createDBUser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { z } from "zod";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { AtlasToolBase } from "./atlasTool.js";
import { ToolArgs } from "../tool.js";
import { CloudDatabaseUser, DatabaseUserRole } from "../../common/atlas/openapi.js";

export class CreateDBUserTool extends AtlasToolBase {
protected name = "atlas-create-db-user";
protected description = "Create an MongoDB Atlas user";
protected argsShape = {
projectId: z.string().describe("Atlas project ID"),
username: z.string().describe("Username for the new user"),
password: z.string().describe("Password for the new user"),
roles: z
.array(
z.object({
roleName: z.string().describe("Role name"),
databaseName: z.string().describe("Database name").default("admin"),
collectionName: z.string().describe("Collection name").optional(),
})
)
.describe("Roles for the new user"),
clusters: z
.array(z.string())
.describe("Clusters to assign the user to, leave empty for access to all clusters")
.optional(),
};

protected async execute({
projectId,
username,
password,
roles,
clusters,
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
await this.ensureAuthenticated();

const input = {
groupId: projectId,
awsIAMType: "NONE",
databaseName: "admin",
ldapAuthType: "NONE",
oidcAuthType: "NONE",
x509Type: "NONE",
username,
password,
roles: roles as unknown as DatabaseUserRole[],
scopes: clusters?.length
? clusters.map((cluster) => ({
type: "CLUSTER",
name: cluster,
}))
: undefined,
} as CloudDatabaseUser;

await this.apiClient!.createDatabaseUser(projectId, input);

return {
content: [{ type: "text", text: `User "${username}" created sucessfully.` }],
};
}
}
8 changes: 3 additions & 5 deletions src/tools/atlas/listClusters.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { z } from "zod";
import { config } from "../../config.js";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { AtlasToolBase } from "./atlasTool.js";
import { ToolArgs } from "../tool.js";
Expand All @@ -15,16 +14,15 @@ export class ListClustersTool extends AtlasToolBase {
protected async execute({ projectId }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
await this.ensureAuthenticated();

const selectedProjectId = projectId || config.projectID;
if (!selectedProjectId) {
if (!projectId) {
const data = await this.apiClient.listClustersForAllProjects();

return this.formatAllClustersTable(data);
} else {
const project = await this.apiClient.getProject(selectedProjectId);
const project = await this.apiClient.getProject(projectId);

if (!project?.id) {
throw new Error(`Project with ID "${selectedProjectId}" not found.`);
throw new Error(`Project with ID "${projectId}" not found.`);
}

const data = await this.apiClient.listClusters(project.id || "");
Expand Down
55 changes: 55 additions & 0 deletions src/tools/atlas/listDBUsers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { z } from "zod";
import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { AtlasToolBase } from "./atlasTool.js";
import { ToolArgs } from "../tool.js";
import { DatabaseUserRole, UserScope } from "../../common/atlas/openapi.js";

export class ListDBUsersTool extends AtlasToolBase {
protected name = "atlas-list-db-users";
protected description = "List MongoDB Atlas users";
protected argsShape = {
projectId: z.string().describe("Atlas project ID to filter DB users"),
};

protected async execute({ projectId }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
await this.ensureAuthenticated();

const data = await this.apiClient!.listDatabaseUsers(projectId);

if (!data.results?.length) {
throw new Error("No database users found.");
}

const output =
`Username | Roles | Scopes
----------------|----------------|----------------
` +
data.results
.map((user) => {
return `${user.username} | ${formatRoles(user.roles)} | ${formatScopes(user.scopes)}`;
})
.join("\n");
return {
content: [{ type: "text", text: output }],
};
}
}

function formatRoles(roles?: DatabaseUserRole[]) {
if (!roles?.length) {
return "N/A";
}
return roles
.map(
(role) =>
`${role.roleName}${role.databaseName ? `@${role.databaseName}${role.collectionName ? `:${role.collectionName}` : ""}` : ""}`
)
.join(", ");
}

function formatScopes(scopes?: UserScope[]) {
if (!scopes?.length) {
return "All";
}
return scopes.map((scope) => `${scope.type}:${scope.name}`).join(", ");
}
6 changes: 5 additions & 1 deletion src/tools/atlas/tools.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ToolBase } from "../tool.js";
import { ApiClient } from "../../common/atlas/client.js";
import { ApiClient } from "../../common/atlas/apiClient.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { State } from "../../state.js";
import { AuthTool } from "./auth.js";
Expand All @@ -9,6 +9,8 @@ import { InspectClusterTool } from "./inspectCluster.js";
import { CreateFreeClusterTool } from "./createFreeCluster.js";
import { CreateAccessListTool } from "./createAccessList.js";
import { InspectAccessListTool } from "./inspectAccessList.js";
import { ListDBUsersTool } from "./listDBUsers.js";
import { CreateDBUserTool } from "./createDBUser.js";

export function registerAtlasTools(server: McpServer, state: State, apiClient: ApiClient) {
const tools: ToolBase[] = [
Expand All @@ -19,6 +21,8 @@ export function registerAtlasTools(server: McpServer, state: State, apiClient: A
new CreateFreeClusterTool(state, apiClient),
new CreateAccessListTool(state, apiClient),
new InspectAccessListTool(state, apiClient),
new ListDBUsersTool(state, apiClient),
new CreateDBUserTool(state, apiClient),
];

for (const tool of tools) {
Expand Down