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
15 changes: 15 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. |
| `readOnly` | 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 `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.

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=true`
- **Command-line argument**: `--readOnly`

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 Expand Up @@ -221,6 +235,7 @@ export MDB_MCP_API_CLIENT_SECRET="your-atlas-client-secret"
export MDB_MCP_CONNECTION_STRING="mongodb+srv://username:password@cluster.mongodb.net/myDatabase"

export MDB_MCP_LOG_PATH="/path/to/logs"

```

#### Command-Line Arguments
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>;
readOnly?: boolean;
}

const defaults: UserConfig = {
Expand All @@ -32,6 +33,7 @@ const defaults: UserConfig = {
},
disabledTools: [],
telemetry: "disabled",
readOnly: 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 @@ -124,6 +124,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()) {
return;
}

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

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

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

Expand Down Expand Up @@ -115,6 +116,8 @@ export class Server {

if (command === "start") {
event.properties.startup_time_ms = commandDuration;
event.properties.read_only_mode = this.userConfig.readOnly || false;
event.properties.disallowed_tools = this.userConfig.disabledTools || [];
}
if (command === "stop") {
event.properties.runtime_duration_ms = Date.now() - this.startTime;
Expand Down
2 changes: 2 additions & 0 deletions src/telemetry/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ export interface ServerEvent extends BaseEvent {
reason?: string;
startup_time_ms?: number;
runtime_duration_ms?: number;
read_only_mode?: boolean;
disabled_tools?: string[];
} & BaseEvent["properties"];
}

Expand Down
8 changes: 6 additions & 2 deletions src/tools/tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { UserConfig } from "../config.js";

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

export type OperationType = "metadata" | "read" | "create" | "delete" | "update" | "cluster";
export type OperationType = "metadata" | "read" | "create" | "delete" | "update";
export type ToolCategory = "mongodb" | "atlas";

export abstract class ToolBase {
Expand Down Expand Up @@ -109,7 +109,11 @@ export abstract class ToolBase {
// Checks if a tool is allowed to run based on the config
protected verifyAllowed(): boolean {
let errorClarification: string | undefined;
if (this.config.disabledTools.includes(this.category)) {

// Check read-only mode first
if (this.config.readOnly && !["read", "metadata"].includes(this.operationType)) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

keeping it like this so we don't alter the configured disallowed tools. i also think adding the virtual "write" would be an extra layer of complexity for users that id' like to avoid.

the other thing we could do is remove this check and set the disallowed operation types during initalization, I can do that if you prefer, but I don't have a strong opinion!

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

(cc @nirinchev )

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this is totally fine!

One thing I noticed is that the SDK recently added the ability to enable/disable tools - modelcontextprotocol/typescript-sdk#247. We should probably look into it post-public-preview and see if it makes sense to use that mechanism instead. Might also be interesting to see if there'd be a way to allow users to dynamically update the server config without restarting it.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

nice, yep, that'd be awesome, I think in VSCode it gives you a checklist so I think it's possible depending on the tool already

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

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

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);
expect(tools.tools.some((tool) => tool.name === "atlas-list-orgs")).toBe(true);
expect(tools.tools.some((tool) => tool.name === "atlas-list-projects")).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