Skip to content

feat: add readOnly flag #130

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 12 commits into from
Apr 25, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ The MongoDB MCP Server can be configured using multiple methods, with the follow
| `connectionString` | MongoDB connection string for direct database connections (optional users may choose to inform it on every tool call) |
| `logPath` | Folder to store logs |
| `disabledTools` | An array of tool names, operation types, and/or categories of tools that will be disabled. |
| `readOnlyMode` | When set to true, only allows read and metadata operation types, disabling create/update/delete operations |

#### `logPath`

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

#### Read-Only Mode

The `readOnlyMode` 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", "delete", or "cluster" operation types will not be registered with the server.

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.

You can enable read-only mode using:

- **Environment variable**: `export MDB_MCP_READ_ONLY_MODE=true`
- **Command-line argument**: `--readOnlyMode=true`

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.

### Atlas API Access

To use the Atlas API tools, you'll need to create a service account in MongoDB Atlas:
Expand Down
2 changes: 2 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface UserConfig {
timeoutMS: number;
};
disabledTools: Array<string>;
readOnlyMode?: boolean;
}

const defaults: UserConfig = {
Expand All @@ -32,6 +33,7 @@ const defaults: UserConfig = {
},
disabledTools: [],
telemetry: "disabled",
readOnlyMode: false,
};

export const config = {
Expand Down
5 changes: 5 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ class McpLogger extends LoggerBase {
}

log(level: LogLevel, _: MongoLogId, context: string, message: string): void {
// Only log if the server is connected
if (this.server?.isConnected() === false) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fly-by - when server is not connect, this can crash, so I've added this check.

return;
}

void this.server.server.sendLoggingMessage({
level,
data: `[${context}]: ${message}`,
Expand Down
11 changes: 11 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,16 @@ export class Server {

async connect(transport: Transport) {
this.mcpServer.server.registerCapabilities({ logging: {} });

// Log read-only mode status if enabled
if (this.userConfig.readOnlyMode) {
logger.info(
mongoLogId(1_000_005),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move this to a constant under logger/LogId and update the value to be consistent with the other constants there.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually decided to remove since we're not doing anything other than logging here, but will do from now on

"server",
"Server starting in READ-ONLY mode. Only read and metadata operations will be available."
);
}

this.registerTools();
this.registerResources();

Expand Down Expand Up @@ -116,6 +126,7 @@ export class Server {

if (command === "start") {
event.properties.startup_time_ms = commandDuration;
event.properties.read_only_mode = this.userConfig.readOnlyMode || false;
}
if (command === "stop") {
event.properties.runtime_duration_ms = Date.now() - this.startTime;
Expand Down
11 changes: 11 additions & 0 deletions src/tools/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,17 @@ export abstract class ToolBase {
// Checks if a tool is allowed to run based on the config
protected verifyAllowed(): boolean {
let errorClarification: string | undefined;

// Check read-only mode first
if (this.config.readOnlyMode && !["read", "metadata"].includes(this.operationType)) {
logger.debug(
mongoLogId(1_000_010),
"tool",
`Prevented registration of ${this.name} because it has operation type \`${this.operationType}\` and read-only mode is enabled`
);
return false;
}

if (this.config.disabledTools.includes(this.category)) {
errorClarification = `its category, \`${this.category}\`,`;
} else if (this.config.disabledTools.includes(this.operationType)) {
Expand Down
24 changes: 24 additions & 0 deletions tests/integration/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,28 @@ describe("Server integration test", () => {
});
});
});

describe("with read-only mode", () => {
const integration = setupIntegrationTest({
...config,
readOnlyMode: true,
});

it("should only register read and metadata operation tools when read-only mode is enabled", async () => {
const tools = await integration.mcpClient().listTools();
expectDefined(tools);
expect(tools.tools.length).toBeGreaterThan(0);

// Check that we have some tools available (the read and metadata ones)
expect(tools.tools.some((tool) => tool.name === "find")).toBe(true);
expect(tools.tools.some((tool) => tool.name === "collection-schema")).toBe(true);
expect(tools.tools.some((tool) => tool.name === "list-databases")).toBe(true);

// Check that non-read tools are NOT available
expect(tools.tools.some((tool) => tool.name === "insert-one")).toBe(false);
expect(tools.tools.some((tool) => tool.name === "update-many")).toBe(false);
expect(tools.tools.some((tool) => tool.name === "delete-one")).toBe(false);
expect(tools.tools.some((tool) => tool.name === "drop-collection")).toBe(false);
});
});
});
Loading