Skip to content

Commit 7b9559c

Browse files
blvafmenezes
andauthored
feat: add readOnly flag (#130)
Co-authored-by: Filipe Constantinov Menezes <[email protected]>
1 parent 435afe1 commit 7b9559c

File tree

7 files changed

+61
-2
lines changed

7 files changed

+61
-2
lines changed

README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ The MongoDB MCP Server can be configured using multiple methods, with the follow
150150
| `connectionString` | MongoDB connection string for direct database connections (optional users may choose to inform it on every tool call) |
151151
| `logPath` | Folder to store logs |
152152
| `disabledTools` | An array of tool names, operation types, and/or categories of tools that will be disabled. |
153+
| `readOnly` | When set to true, only allows read and metadata operation types, disabling create/update/delete operations |
153154

154155
#### `logPath`
155156

@@ -181,6 +182,19 @@ Operation types:
181182
- `read` - Tools that read resources, such as find, aggregate, list clusters, etc.
182183
- `metadata` - Tools that read metadata, such as list databases, list collections, collection schema, etc.
183184

185+
#### Read-Only Mode
186+
187+
The `readOnly` configuration option allows you to restrict the MCP server to only use tools with "read" and "metadata" operation types. When enabled, all tools that have "create", "update" or "delete" operation types will not be registered with the server.
188+
189+
This is useful for scenarios where you want to provide access to MongoDB data for analysis without allowing any modifications to the data or infrastructure.
190+
191+
You can enable read-only mode using:
192+
193+
- **Environment variable**: `export MDB_MCP_READ_ONLY=true`
194+
- **Command-line argument**: `--readOnly`
195+
196+
When read-only mode is active, you'll see a message in the server logs indicating which tools were prevented from registering due to this restriction.
197+
184198
### Atlas API Access
185199

186200
To use the Atlas API tools, you'll need to create a service account in MongoDB Atlas:
@@ -221,6 +235,7 @@ export MDB_MCP_API_CLIENT_SECRET="your-atlas-client-secret"
221235
export MDB_MCP_CONNECTION_STRING="mongodb+srv://username:[email protected]/myDatabase"
222236

223237
export MDB_MCP_LOG_PATH="/path/to/logs"
238+
224239
```
225240

226241
#### Command-Line Arguments

src/config.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export interface UserConfig {
2020
timeoutMS: number;
2121
};
2222
disabledTools: Array<string>;
23+
readOnly?: boolean;
2324
}
2425

2526
const defaults: UserConfig = {
@@ -32,6 +33,7 @@ const defaults: UserConfig = {
3233
},
3334
disabledTools: [],
3435
telemetry: "disabled",
36+
readOnly: false,
3537
};
3638

3739
export const config = {

src/logger.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,11 @@ class McpLogger extends LoggerBase {
124124
}
125125

126126
log(level: LogLevel, _: MongoLogId, context: string, message: string): void {
127+
// Only log if the server is connected
128+
if (!this.server?.isConnected()) {
129+
return;
130+
}
131+
127132
void this.server.server.sendLoggingMessage({
128133
level,
129134
data: `[${context}]: ${message}`,

src/server.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ export class Server {
3535

3636
async connect(transport: Transport) {
3737
this.mcpServer.server.registerCapabilities({ logging: {} });
38+
3839
this.registerTools();
3940
this.registerResources();
4041

@@ -115,6 +116,8 @@ export class Server {
115116

116117
if (command === "start") {
117118
event.properties.startup_time_ms = commandDuration;
119+
event.properties.read_only_mode = this.userConfig.readOnly || false;
120+
event.properties.disallowed_tools = this.userConfig.disabledTools || [];
118121
}
119122
if (command === "stop") {
120123
event.properties.runtime_duration_ms = Date.now() - this.startTime;

src/telemetry/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ export interface ServerEvent extends BaseEvent {
4747
reason?: string;
4848
startup_time_ms?: number;
4949
runtime_duration_ms?: number;
50+
read_only_mode?: boolean;
51+
disabled_tools?: string[];
5052
} & BaseEvent["properties"];
5153
}
5254

src/tools/tool.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { UserConfig } from "../config.js";
99

1010
export type ToolArgs<Args extends ZodRawShape> = z.objectOutputType<Args, ZodNever>;
1111

12-
export type OperationType = "metadata" | "read" | "create" | "delete" | "update" | "cluster";
12+
export type OperationType = "metadata" | "read" | "create" | "delete" | "update";
1313
export type ToolCategory = "mongodb" | "atlas";
1414

1515
export abstract class ToolBase {
@@ -109,7 +109,11 @@ export abstract class ToolBase {
109109
// Checks if a tool is allowed to run based on the config
110110
protected verifyAllowed(): boolean {
111111
let errorClarification: string | undefined;
112-
if (this.config.disabledTools.includes(this.category)) {
112+
113+
// Check read-only mode first
114+
if (this.config.readOnly && !["read", "metadata"].includes(this.operationType)) {
115+
errorClarification = `read-only mode is enabled, its operation type, \`${this.operationType}\`,`;
116+
} else if (this.config.disabledTools.includes(this.category)) {
113117
errorClarification = `its category, \`${this.category}\`,`;
114118
} else if (this.config.disabledTools.includes(this.operationType)) {
115119
errorClarification = `its operation type, \`${this.operationType}\`,`;

tests/integration/server.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,4 +52,32 @@ describe("Server integration test", () => {
5252
});
5353
});
5454
});
55+
56+
describe("with read-only mode", () => {
57+
const integration = setupIntegrationTest(() => ({
58+
...config,
59+
readOnly: true,
60+
apiClientId: "test",
61+
apiClientSecret: "test",
62+
}));
63+
64+
it("should only register read and metadata operation tools when read-only mode is enabled", async () => {
65+
const tools = await integration.mcpClient().listTools();
66+
expectDefined(tools);
67+
expect(tools.tools.length).toBeGreaterThan(0);
68+
69+
// Check that we have some tools available (the read and metadata ones)
70+
expect(tools.tools.some((tool) => tool.name === "find")).toBe(true);
71+
expect(tools.tools.some((tool) => tool.name === "collection-schema")).toBe(true);
72+
expect(tools.tools.some((tool) => tool.name === "list-databases")).toBe(true);
73+
expect(tools.tools.some((tool) => tool.name === "atlas-list-orgs")).toBe(true);
74+
expect(tools.tools.some((tool) => tool.name === "atlas-list-projects")).toBe(true);
75+
76+
// Check that non-read tools are NOT available
77+
expect(tools.tools.some((tool) => tool.name === "insert-one")).toBe(false);
78+
expect(tools.tools.some((tool) => tool.name === "update-many")).toBe(false);
79+
expect(tools.tools.some((tool) => tool.name === "delete-one")).toBe(false);
80+
expect(tools.tools.some((tool) => tool.name === "drop-collection")).toBe(false);
81+
});
82+
});
5583
});

0 commit comments

Comments
 (0)