Skip to content

Commit c611836

Browse files
authored
Merge branch 'main' into gagik/use-machine-id
2 parents 8816bef + 333c36a commit c611836

File tree

11 files changed

+263
-112
lines changed

11 files changed

+263
-112
lines changed

README.md

Lines changed: 129 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,96 +1,96 @@
11
# MongoDB MCP Server
22

3-
A Model Context Protocol server for interacting with MongoDB Atlas. This project implements a Model Context Protocol (MCP) server enabling AI assistants to interact with MongoDB Atlas resources through natural language.
4-
5-
> [!CAUTION]
6-
> Do not use this in production. This is a work in progress and is not intended for production use. It is meant for demonstration purposes only.
3+
A Model Context Protocol server for interacting with MongoDB Databases and MongoDB Atlas.
74

85
## 📚 Table of Contents
96

107
- [🚀 Getting Started](#getting-started)
118
- [Prerequisites](#prerequisites)
12-
- [Installation](#installation)
13-
- [VSCode](#vscode)
14-
- [Claude Desktop](#claude)
9+
- [Setup](#setup)
10+
- [Quick Start](#quick-start)
1511
- [🛠️ Supported Tools](#supported-tools)
16-
- [Tool List](#tool-list)
12+
- [MongoDB Atlas Tools](#mongodb-atlas-tools)
13+
- [MongoDB Database Tools](#mongodb-database-tools)
1714
- [⚙️ Configuration](#configuration)
1815
- [Configuration Options](#configuration-options)
1916
- [Atlas API Access](#atlas-api-access)
2017
- [Configuration Methods](#configuration-methods)
21-
- [👩‍💻 Client Integration](#client-integration)
22-
- [VSCode](#vscode)
23-
- [Claude](#claude)
18+
- [Environment Variables](#environment-variables)
19+
- [Command-Line Arguments](#command-line-arguments)
20+
- [MCP Client Configuration](#mcp-configuration-file-examples)
2421
- [🤝 Contributing](#contributing)
2522

2623
## Prerequisites
2724

2825
- Node.js (v20 or later)
29-
- MongoDB Atlas account
3026

31-
## Installation
27+
```shell
28+
node -v
29+
```
3230

33-
### VSCode
31+
- A MongoDB connection string or Atlas API credentials, **_the Server will not start unless configured_**.
32+
- **_Atlas API credentials_** are required to use the Atlas tools. You can create a service account in MongoDB Atlas and use its credentials for authentication. See [Atlas API Access](#atlas-api-access) for more details.
33+
- If you have a MongoDB connection string, you can use it directly to connect to your MongoDB instance.
3434

35-
Prerequisites:
35+
## Setup
3636

37-
- Node.js v20.x
37+
### Quick Start
3838

39-
Step 1: Add the mcp server to VSCode configuration
39+
Most MCP clients require a configuration file to be created or modified to add the MCP server.
4040

41-
- Press `Cmd + Shift + P` and type `MCP: Add MCP Server` and select it.
42-
- Select command (Stdio).
43-
- Input command `npx -y mongodb-mcp-server`.
44-
- Choose between user / workspace
45-
- Add arguments to the file
41+
- **Windsurf**:https://docs.windsurf.com/windsurf/mcp
42+
- **VSCode**: https://docs.codeium.com/docs/mcp
43+
- **Claude Desktop**: https://modelcontextprotocol.io/quickstart/user
44+
- **Cursor**: https://docs.cursor.com/context/model-context-protocol
4645

47-
Note: the file should look like:
46+
#### Option 1: Connection String args
4847

49-
```
48+
You can pass your connection string via args, make sure to use a valid username and password.
49+
50+
```json
5051
{
51-
"servers": {
52-
"MongoDB": {
53-
"type": "stdio",
54-
"command": "npx",
55-
"args": [
56-
"-y",
57-
"mongodb-mcp-server"
58-
]
59-
}
52+
"servers": {
53+
"MongoDB": {
54+
"command": "npx",
55+
"args": [
56+
"-y",
57+
"mongodb-mcp-server",
58+
"--connectionString",
59+
"mongodb+srv://username:[email protected]/myDatabase"
60+
]
6061
}
62+
}
6163
}
6264
```
6365

64-
Notes: You can configure the server with atlas access, make sure to follow configuration section for more details.
65-
66-
Step 2: Try talking to github copilot
67-
68-
- Can you connect to my mongodb instance?
69-
70-
### Claude Desktop
71-
72-
Step 1: Install claude and login
73-
74-
Note: follow instructions at https://claude.ai/download
75-
76-
Step 2: Launch Claude Settings -> Developer -> Edit Config
66+
#### Option 2: Atlas API credentials args
7767

78-
Paste the mcp server configuration into the file
68+
Use your Atlas API Service Account credentials. More details in the [Atlas API Access](#atlas-api-access) section.
7969

8070
```json
8171
{
82-
"mcpServers": {
72+
"servers": {
8373
"MongoDB": {
8474
"command": "npx",
85-
"args": ["-y", "mongodb-mcp-server"]
75+
"args": [
76+
"-y",
77+
"mongodb-mcp-server",
78+
"--apiClientId",
79+
"your-atlas-client-id",
80+
"--apiClientSecret",
81+
"your-atlas-client-secret"
82+
]
8683
}
8784
}
8885
}
8986
```
9087

91-
Step 3: Close and Relaunch Claude Desktop and click on the hammer icon, the MongoDB MCP server should be detected.
88+
#### Other options
9289

93-
You may experiment asking `Can you connect to my mongodb instance?`.
90+
Alternatively you can use environment variables in the config file or set them and run the server via npx.
91+
92+
- Connection String via environment variables in the MCP file [example](#connection-string-with-environment-variables)
93+
- Atlas API credentials via environment variables in the MCP file [example](#atlas-api-credentials-with-environment-variables)
9494

9595
## 🛠️ Supported Tools
9696

@@ -154,7 +154,7 @@ The MongoDB MCP Server can be configured using multiple methods, with the follow
154154
| `readOnly` | When set to true, only allows read and metadata operation types, disabling create/update/delete operations |
155155
| `telemetry` | When set to disabled, disables telemetry collection |
156156

157-
#### `logPath`
157+
#### Log Path
158158

159159
Default log location is as follows:
160160

@@ -220,6 +220,8 @@ To use the Atlas API tools, you'll need to create a service account in MongoDB A
220220
- Select appropriate permissions (for full access, use Organization Owner)
221221
- Click "Create"
222222

223+
To learn more about Service Accounts, check the [MongoDB Atlas documentation](https://www.mongodb.com/docs/atlas/api/service-accounts-overview/).
224+
223225
2. **Save Client Credentials:**
224226

225227
- After creation, you'll be shown the Client ID and Client Secret
@@ -250,6 +252,41 @@ export MDB_MCP_LOG_PATH="/path/to/logs"
250252

251253
```
252254

255+
#### MCP configuration file examples
256+
257+
##### Connection String with environment variables
258+
259+
```json
260+
{
261+
"servers": {
262+
"MongoDB": {
263+
"command": "npx",
264+
"args": ["-y", "mongodb-mcp-server"],
265+
"env": {
266+
"MDB_MCP_CONNECTION_STRING": "mongodb+srv://username:[email protected]/myDatabase"
267+
}
268+
}
269+
}
270+
}
271+
```
272+
273+
##### Atlas API credentials with environment variables
274+
275+
```json
276+
{
277+
"servers": {
278+
"MongoDB": {
279+
"command": "npx",
280+
"args": ["-y", "mongodb-mcp-server"],
281+
"env": {
282+
"MDB_MCP_API_CLIENT_ID": "your-atlas-client-id",
283+
"MDB_MCP_API_CLIENT_SECRET": "your-atlas-client-secret"
284+
}
285+
}
286+
}
287+
}
288+
```
289+
253290
#### Command-Line Arguments
254291

255292
Pass configuration options as command-line arguments when starting the server:
@@ -258,6 +295,46 @@ Pass configuration options as command-line arguments when starting the server:
258295
npx -y mongodb-mcp-server --apiClientId="your-atlas-client-id" --apiClientSecret="your-atlas-client-secret" --connectionString="mongodb+srv://username:[email protected]/myDatabase" --logPath=/path/to/logs
259296
```
260297

298+
#### MCP configuration file examples
299+
300+
##### Connection String with command-line arguments
301+
302+
```json
303+
{
304+
"servers": {
305+
"MongoDB": {
306+
"command": "npx",
307+
"args": [
308+
"-y",
309+
"mongodb-mcp-server",
310+
"--connectionString",
311+
"mongodb+srv://username:[email protected]/myDatabase"
312+
]
313+
}
314+
}
315+
}
316+
```
317+
318+
##### Atlas API credentials with command-line arguments
319+
320+
```json
321+
{
322+
"servers": {
323+
"MongoDB": {
324+
"command": "npx",
325+
"args": [
326+
"-y",
327+
"mongodb-mcp-server",
328+
"--apiClientId",
329+
"your-atlas-client-id",
330+
"--apiClientSecret",
331+
"your-atlas-client-secret"
332+
]
333+
}
334+
}
335+
}
336+
```
337+
261338
## 🤝 Contributing
262339

263340
Interested in contributing? Great! Please check our [Contributing Guide](CONTRIBUTING.md) for guidelines on code contributions, standards, adding new tools, and troubleshooting information.

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "mongodb-mcp-server",
33
"description": "MongoDB Model Context Protocol Server",
4-
"version": "0.0.7",
4+
"version": "0.1.0",
55
"main": "dist/index.js",
66
"author": "MongoDB <[email protected]>",
77
"homepage": "https://github.com/mongodb-js/mongodb-mcp-server",

src/common/atlas/generatePassword.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { randomBytes } from "crypto";
2+
import { promisify } from "util";
3+
4+
const randomBytesAsync = promisify(randomBytes);
5+
6+
export async function generateSecurePassword(): Promise<string> {
7+
const buf = await randomBytesAsync(16);
8+
const pass = buf.toString("base64url");
9+
return pass;
10+
}

src/logger.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export const LogId = {
1212

1313
atlasCheckCredentials: mongoLogId(1_001_001),
1414
atlasDeleteDatabaseUserFailure: mongoLogId(1_001_002),
15+
atlasConnectFailure: mongoLogId(1_001_003),
1516

1617
telemetryDisabled: mongoLogId(1_002_001),
1718
telemetryEmitFailure: mongoLogId(1_002_002),

src/session.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -69,25 +69,24 @@ export class Session extends EventEmitter<{
6969
this.emit("disconnect");
7070
return;
7171
}
72-
try {
73-
await this.apiClient.deleteDatabaseUser({
72+
void this.apiClient
73+
.deleteDatabaseUser({
7474
params: {
7575
path: {
7676
groupId: this.connectedAtlasCluster.projectId,
7777
username: this.connectedAtlasCluster.username,
7878
databaseName: "admin",
7979
},
8080
},
81+
})
82+
.catch((err: unknown) => {
83+
const error = err instanceof Error ? err : new Error(String(err));
84+
logger.error(
85+
LogId.atlasDeleteDatabaseUserFailure,
86+
"atlas-connect-cluster",
87+
`Error deleting previous database user: ${error.message}`
88+
);
8189
});
82-
} catch (err: unknown) {
83-
const error = err instanceof Error ? err : new Error(String(err));
84-
85-
logger.error(
86-
LogId.atlasDeleteDatabaseUserFailure,
87-
"atlas-connect-cluster",
88-
`Error deleting previous database user: ${error.message}`
89-
);
90-
}
9190
this.connectedAtlasCluster = undefined;
9291

9392
this.emit("disconnect");

src/tools/atlas/create/createDBUser.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
33
import { AtlasToolBase } from "../atlasTool.js";
44
import { ToolArgs, OperationType } from "../../tool.js";
55
import { CloudDatabaseUser, DatabaseUserRole } from "../../../common/atlas/openapi.js";
6+
import { generateSecurePassword } from "../../../common/atlas/generatePassword.js";
67

78
export class CreateDBUserTool extends AtlasToolBase {
89
protected name = "atlas-create-db-user";
@@ -11,7 +12,16 @@ export class CreateDBUserTool extends AtlasToolBase {
1112
protected argsShape = {
1213
projectId: z.string().describe("Atlas project ID"),
1314
username: z.string().describe("Username for the new user"),
14-
password: z.string().describe("Password for the new user"),
15+
// Models will generate overly simplistic passwords like SecurePassword123 or
16+
// AtlasPassword123, which are easily guessable and exploitable. We're instructing
17+
// the model not to try and generate anything and instead leave the field unset.
18+
password: z
19+
.string()
20+
.optional()
21+
.nullable()
22+
.describe(
23+
"Password for the new user. If the user hasn't supplied an explicit password, leave it unset and under no circumstances try to generate a random one. A secure password will be generated by the MCP server if necessary."
24+
),
1525
roles: z
1626
.array(
1727
z.object({
@@ -34,6 +44,11 @@ export class CreateDBUserTool extends AtlasToolBase {
3444
roles,
3545
clusters,
3646
}: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
47+
const shouldGeneratePassword = !password;
48+
if (shouldGeneratePassword) {
49+
password = await generateSecurePassword();
50+
}
51+
3752
const input = {
3853
groupId: projectId,
3954
awsIAMType: "NONE",
@@ -62,7 +77,12 @@ export class CreateDBUserTool extends AtlasToolBase {
6277
});
6378

6479
return {
65-
content: [{ type: "text", text: `User "${username}" created sucessfully.` }],
80+
content: [
81+
{
82+
type: "text",
83+
text: `User "${username}" created successfully${shouldGeneratePassword ? ` with password: \`${password}\`` : ""}.`,
84+
},
85+
],
6686
};
6787
}
6888
}

0 commit comments

Comments
 (0)