mcp-mongo-server 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,6 +13,12 @@ A Model Context Protocol server that provides access to MongoDB databases. This
13
13
 
14
14
  ## Features
15
15
 
16
+ ### Read-Only Mode
17
+ - Connect to MongoDB in read-only mode with `--read-only` or `-r` flag
18
+ - Prevents write operations (update, insert, createIndex)
19
+ - Uses MongoDB's secondary read preference for optimal read performance
20
+ - Provides additional safety for production database connections
21
+
16
22
  ### Resources
17
23
  - List and access collections via `mongodb://` URIs
18
24
  - Each collection has a name, description and schema
@@ -97,6 +103,14 @@ On Windows: `%APPDATA%/Claude/claude_desktop_config.json`
97
103
  "mongodb://muhammed:kilic@mongodb.localhost/namespace"
98
104
  ]
99
105
  },
106
+ "mongodb-readonly": {
107
+ "command": "node",
108
+ "args": [
109
+ "~/mcp-mongo-server/build/index.js",
110
+ "mongodb://muhammed:kilic@mongodb.localhost/namespace",
111
+ "--read-only"
112
+ ]
113
+ }
100
114
  }
101
115
  }
102
116
  ```
@@ -139,6 +153,24 @@ To use this server with the Claude Desktop app, add the following configuration
139
153
  "mcp-mongo-server",
140
154
  "mongodb://muhammed:kilic@mongodb.localhost/sample_namespace"
141
155
  ]
156
+ },
157
+ "mongodb-readonly": {
158
+ "command": "npx",
159
+ "args": [
160
+ "-y",
161
+ "mcp-mongo-server",
162
+ "mongodb://muhammed:kilic@mongodb.localhost/sample_namespace",
163
+ "--read-only"
164
+ ]
165
+ },
166
+ "mongodb-github": {
167
+ "command": "npx",
168
+ "args": [
169
+ "-y",
170
+ "github:kiliczsh/mcp-mongo-server",
171
+ "mongodb://muhammed:kilic@mongodb.localhost/sample_namespace",
172
+ "--read-only"
173
+ ]
142
174
  }
143
175
  }
144
176
  }
@@ -162,6 +194,21 @@ npx @michaellatman/mcp-get@latest install mcp-mongo-server
162
194
 
163
195
  Replace `/sample_namespace` with your database name.
164
196
 
197
+ ## Using Read-Only Mode
198
+
199
+ You can connect to MongoDB in read-only mode by adding the `--read-only` or `-r` flag when starting the server. This is recommended when you need to protect your data from accidental writes or when connecting to production databases.
200
+
201
+ ```bash
202
+ # Connect in read-only mode using the command line
203
+ npx mcp-mongo-server mongodb://user:password@mongodb.example.com/database --read-only
204
+ ```
205
+
206
+ When in read-only mode:
207
+ 1. All write operations (update, insert, createIndex) will be blocked
208
+ 2. The server connects using MongoDB's secondary read preference
209
+ 3. The connection status indicates read-only mode is active
210
+ 4. The `ping` and `serverInfo` responses include read-only status information
211
+
165
212
  ## License
166
213
 
167
214
  This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
package/build/index.js CHANGED
@@ -10,19 +10,23 @@
10
10
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
11
11
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
12
12
  import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, ListResourceTemplatesRequestSchema, PingRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
13
- import { MongoClient } from "mongodb";
13
+ import { MongoClient, ReadPreference } from "mongodb";
14
14
  /**
15
15
  * MongoDB connection client and database reference
16
16
  */
17
17
  let client = null;
18
18
  let db = null;
19
+ /**
20
+ * Flag indicating whether the connection is in read-only mode
21
+ */
22
+ let isReadOnlyMode = false;
19
23
  /**
20
24
  * Create an MCP server with capabilities for resources (to list/read collections),
21
25
  * tools (to query data), and prompts (to analyze collections).
22
26
  */
23
27
  const server = new Server({
24
28
  name: "mongodb",
25
- version: "1.0.0",
29
+ version: "1.1.1",
26
30
  }, {
27
31
  capabilities: {
28
32
  resources: {},
@@ -33,11 +37,13 @@ const server = new Server({
33
37
  /**
34
38
  * Initialize MongoDB connection
35
39
  */
36
- async function connectToMongoDB(url) {
40
+ async function connectToMongoDB(url, readOnly = false) {
37
41
  try {
38
- client = new MongoClient(url);
42
+ const options = readOnly ? { readPreference: ReadPreference.SECONDARY } : {};
43
+ client = new MongoClient(url, options);
39
44
  await client.connect();
40
45
  db = client.db();
46
+ isReadOnlyMode = readOnly;
41
47
  return true;
42
48
  }
43
49
  catch (error) {
@@ -56,7 +62,9 @@ server.setRequestHandler(PingRequestSchema, async () => {
56
62
  }
57
63
  // Ping MongoDB to verify connection
58
64
  await db.command({ ping: 1 });
59
- return {};
65
+ return {
66
+ readOnlyMode: isReadOnlyMode
67
+ };
60
68
  }
61
69
  catch (error) {
62
70
  if (error instanceof Error) {
@@ -378,6 +386,23 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
378
386
  required: ["collection"],
379
387
  },
380
388
  },
389
+ {
390
+ name: "listCollections",
391
+ description: "List all collections in the MongoDB database",
392
+ inputSchema: {
393
+ type: "object",
394
+ properties: {
395
+ nameOnly: {
396
+ type: "boolean",
397
+ description: "Optional: If true, returns only the collection names instead of full collection info"
398
+ },
399
+ filter: {
400
+ type: "object",
401
+ description: "Optional: Filter to apply to the collections"
402
+ }
403
+ }
404
+ }
405
+ },
381
406
  ],
382
407
  };
383
408
  });
@@ -387,6 +412,12 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
387
412
  */
388
413
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
389
414
  const collection = db.collection(request.params.arguments?.collection);
415
+ // Define write operations that should be blocked in read-only mode
416
+ const writeOperations = ['update', 'insert', 'createIndex'];
417
+ // Check if the operation is a write operation and we're in read-only mode
418
+ if (isReadOnlyMode && writeOperations.includes(request.params.name)) {
419
+ throw new Error(`ReadonlyError: Operation '${request.params.name}' is not allowed in read-only mode`);
420
+ }
390
421
  switch (request.params.name) {
391
422
  case "query": {
392
423
  const { filter, projection, limit, explain } = request.params.arguments || {};
@@ -607,6 +638,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
607
638
  bits: buildInfo.bits,
608
639
  ok: buildInfo.ok,
609
640
  status: {},
641
+ connectionInfo: {
642
+ readOnlyMode: isReadOnlyMode,
643
+ readPreference: isReadOnlyMode ? 'secondary' : 'primary'
644
+ }
610
645
  };
611
646
  // Add server status information if requested
612
647
  if (serverStatus) {
@@ -816,8 +851,34 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
816
851
  throw new Error(`Failed to count documents in collection ${collection.collectionName}: Unknown error`);
817
852
  }
818
853
  }
854
+ case "listCollections": {
855
+ const { nameOnly, filter } = request.params.arguments || {};
856
+ try {
857
+ // Get the list of collections
858
+ const options = filter ? { filter } : {};
859
+ const collections = await db.listCollections(options).toArray();
860
+ // If nameOnly is true, return only the collection names
861
+ const result = nameOnly
862
+ ? collections.map((collection) => collection.name)
863
+ : collections;
864
+ return {
865
+ content: [
866
+ {
867
+ type: "text",
868
+ text: JSON.stringify(result, null, 2),
869
+ },
870
+ ],
871
+ };
872
+ }
873
+ catch (error) {
874
+ if (error instanceof Error) {
875
+ throw new Error(`Failed to list collections: ${error.message}`);
876
+ }
877
+ throw new Error("Failed to list collections: Unknown error");
878
+ }
879
+ }
819
880
  default:
820
- throw new Error("Unknown tool");
881
+ throw new Error(`Unknown tool: ${request.params.name}`);
821
882
  }
822
883
  });
823
884
  /**
@@ -952,11 +1013,24 @@ Use these patterns to construct MongoDB queries.`,
952
1013
  */
953
1014
  async function main() {
954
1015
  const args = process.argv.slice(2);
955
- if (args.length === 0) {
1016
+ let connectionUrl = '';
1017
+ let readOnlyMode = false;
1018
+ // Parse command line arguments
1019
+ for (let i = 0; i < args.length; i++) {
1020
+ if (args[i] === '--read-only' || args[i] === '-r') {
1021
+ readOnlyMode = true;
1022
+ }
1023
+ else if (!connectionUrl) {
1024
+ connectionUrl = args[i];
1025
+ }
1026
+ }
1027
+ if (!connectionUrl) {
956
1028
  console.error("Please provide a MongoDB connection URL as a command-line argument");
1029
+ console.error("Usage: command <mongodb-url> [--read-only|-r]");
957
1030
  process.exit(1);
958
1031
  }
959
- const connected = await connectToMongoDB(args[0]);
1032
+ console.log(`Connecting to MongoDB${readOnlyMode ? ' in read-only mode' : ''}...`);
1033
+ const connected = await connectToMongoDB(connectionUrl, readOnlyMode);
960
1034
  if (!connected) {
961
1035
  console.error("Failed to connect to MongoDB");
962
1036
  process.exit(1);
package/build/types.js CHANGED
@@ -4,11 +4,13 @@ import { CallToolRequestSchema, ToolSchema, ResourceSchema, TextResourceContents
4
4
  export const MongoCollectionSchema = ResourceSchema.extend({
5
5
  collectionName: z.string(),
6
6
  databaseName: z.string(),
7
- indexes: z.array(z.object({
7
+ indexes: z
8
+ .array(z.object({
8
9
  name: z.string(),
9
10
  keys: z.record(z.union([z.number(), z.string()])),
10
11
  unique: z.optional(z.boolean()),
11
- })).optional(),
12
+ }))
13
+ .optional(),
12
14
  });
13
15
  // MongoDB Document Schema
14
16
  export const MongoDocumentSchema = TextResourceContentsSchema.extend({
@@ -40,14 +42,16 @@ export const MongoSortSchema = z.record(z.union([z.literal(1), z.literal(-1)]));
40
42
  export const MongoQueryToolSchema = ToolSchema.extend({
41
43
  inputSchema: z.object({
42
44
  type: z.literal("object"),
43
- properties: z.object({
45
+ properties: z
46
+ .object({
44
47
  collection: z.string(),
45
48
  filter: z.record(z.union([z.unknown(), MongoQueryOperatorSchema])),
46
49
  projection: z.record(z.union([z.literal(0), z.literal(1)])).optional(),
47
50
  sort: MongoSortSchema.optional(),
48
51
  limit: z.number().int().positive().optional(),
49
52
  skip: z.number().int().nonnegative().optional(),
50
- }).passthrough(),
53
+ })
54
+ .passthrough(),
51
55
  required: z.array(z.literal("collection")),
52
56
  }),
53
57
  });
@@ -55,10 +59,12 @@ export const MongoQueryToolSchema = ToolSchema.extend({
55
59
  export const MongoAggregateToolSchema = ToolSchema.extend({
56
60
  inputSchema: z.object({
57
61
  type: z.literal("object"),
58
- properties: z.object({
62
+ properties: z
63
+ .object({
59
64
  collection: z.string(),
60
65
  pipeline: z.array(z.record(z.unknown())),
61
- }).passthrough(),
66
+ })
67
+ .passthrough(),
62
68
  required: z.array(z.literal("collection")),
63
69
  }),
64
70
  });
@@ -66,10 +72,14 @@ export const MongoAggregateToolSchema = ToolSchema.extend({
66
72
  export const MongoCountToolSchema = ToolSchema.extend({
67
73
  inputSchema: z.object({
68
74
  type: z.literal("object"),
69
- properties: z.object({
75
+ properties: z
76
+ .object({
70
77
  collection: z.string(),
71
- filter: z.record(z.union([z.unknown(), MongoQueryOperatorSchema])).optional(),
72
- }).passthrough(),
78
+ filter: z
79
+ .record(z.union([z.unknown(), MongoQueryOperatorSchema]))
80
+ .optional(),
81
+ })
82
+ .passthrough(),
73
83
  required: z.array(z.literal("collection")),
74
84
  }),
75
85
  });
@@ -77,18 +87,32 @@ export const MongoCountToolSchema = ToolSchema.extend({
77
87
  export const MongoDistinctToolSchema = ToolSchema.extend({
78
88
  inputSchema: z.object({
79
89
  type: z.literal("object"),
80
- properties: z.object({
90
+ properties: z
91
+ .object({
81
92
  collection: z.string(),
82
93
  field: z.string(),
83
- filter: z.record(z.union([z.unknown(), MongoQueryOperatorSchema])).optional(),
84
- }).passthrough(),
94
+ filter: z
95
+ .record(z.union([z.unknown(), MongoQueryOperatorSchema]))
96
+ .optional(),
97
+ })
98
+ .passthrough(),
85
99
  required: z.array(z.literal("collection")),
86
100
  }),
87
101
  });
88
102
  // MongoDB Call Tool Request Schema
89
103
  export const MongoCallToolRequestSchema = CallToolRequestSchema.extend({
90
104
  params: z.object({
91
- name: z.enum(["query", "aggregate", "count", "distinct"]),
105
+ name: z.enum([
106
+ "query",
107
+ "aggregate",
108
+ "update",
109
+ "serverInfo",
110
+ "insert",
111
+ "createIndex",
112
+ "count",
113
+ "distinct",
114
+ "listCollections",
115
+ ]),
92
116
  arguments: z.union([
93
117
  MongoQueryToolSchema.shape.inputSchema,
94
118
  MongoAggregateToolSchema.shape.inputSchema,
@@ -136,8 +160,10 @@ export const MongoFieldSchemaSchema = z.object({
136
160
  export const MongoCollectionSchemaSchema = z.object({
137
161
  name: z.string(),
138
162
  fields: z.record(MongoFieldSchemaSchema),
139
- options: z.object({
163
+ options: z
164
+ .object({
140
165
  timestamps: z.boolean().optional(),
141
166
  strict: z.boolean().optional(),
142
- }).optional(),
167
+ })
168
+ .optional(),
143
169
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-mongo-server",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "A Model Context Protocol server for MongoDB connections",
5
5
  "private": false,
6
6
  "type": "module",