Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
34 changes: 34 additions & 0 deletions docs/decisions/2026-11-04-mcp-read-only-mode-hides-write-tools.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# MCP read-only mode hides every tool not annotated readOnlyHint, for every caller including admins

- **Status:** Accepted
- **Revisions:** v1 2026-11-04 (initial)
- **Deciders:** Vishnu Jain
- **Guard:** `McpReadOnlyModeTest`
- **Related:** #36577, #33323, #36579

## Context

Some deployments want AI clients kept read-only whatever the signed-in user may do in the UI. A
Deny rule with `impersonatedBy('McpApplicationBot')` covers ordinary users, but admins skip policy
evaluation entirely, and a denied tool is still listed, so the agent keeps calling it.

## Decision

- `readOnly` in `mcpConfiguration` (default `false`). When `true`, only tools whose `readOnlyHint`
annotation is `true` are available. A tool without the annotation counts as a write tool,
matching the MCP spec default. `describe_entity_type` is withheld too: it only reads, but it
exists to prepare a `create_entity` call.
- One rule, applied in two places in `McpServer`, both after a subclass has added its own tools in
`getTools()`: registration at startup leaves the other tools out of `tools/list`, and
`executeTool` refuses them on every call with a 403. Tools are registered once, so the call-time
check is what makes turning the mode on block writes before a restart; each server reads the
setting as it reloads it. Turning it off brings write tools back only after a restart.
- It applies to every caller, admins included. The user's normal authorization still applies to
the tools that remain.

## Consequences

A new write tool must carry `readOnlyHint: false` (or no annotation) to stay hidden; marking a write
tool `readOnlyHint: true` exposes it in read-only mode. A per-tool allowlist was considered and left
out: nobody asked to hide individual read tools, and a name list goes stale on upgrade. Updating
`tools/list` without a restart would mean re-registering tools on a config change on every server.
1 change: 1 addition & 0 deletions openmetadata-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ This module implements a complete OAuth 2.0 Authorization Code Flow with PKCE fo
- **Rate Limiting** - Registration (10/hour per IP) and token (30/minute per IP) endpoint protection
- **Thread-Safe Concurrent Processing** - ThreadLocal storage for request isolation
- **Audit Logging** - OAuth operations logged via SLF4J (oauth_audit_log table available for future use)
- **Read-only Mode** - Turn on Read-only Mode in the MCP Server app settings to expose only tools annotated `readOnlyHint`, for every user including admins. Writes are blocked at once; the tool list changes, and turning it off applies, after a restart. Through the API, send the full configuration: `PUT /api/v1/system/mcp/config` replaces every field.

### Database-Driven Configuration
- **Runtime Configuration** - Update MCP settings without server restart via REST API
Expand Down
47 changes: 45 additions & 2 deletions openmetadata-mcp/src/main/java/org/openmetadata/mcp/McpServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import org.openmetadata.mcp.server.transport.OAuthHttpStatelessServerTransportProvider;
import org.openmetadata.mcp.tools.DefaultToolContext;
import org.openmetadata.mcp.usage.McpUsageRecorder;
import org.openmetadata.schema.api.configuration.MCPConfiguration;
import org.openmetadata.schema.entity.app.mcp.McpToolCallUsage;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.service.Entity;
Expand Down Expand Up @@ -82,7 +83,8 @@ public void initializeMcpServer(
this.limits = limits;
this.environment = environment;
MutableServletContextHandler contextHandler = environment.getApplicationContext();
List<McpSchema.Tool> tools = getTools();
List<McpSchema.Tool> tools =
exposedTools(getTools(), SecurityConfigurationManager.getCurrentMcpConfig());
List<McpSchema.Prompt> prompts = getPrompts();
addStatelessTransport(contextHandler, tools, prompts);
}
Expand All @@ -109,6 +111,8 @@ protected McpSchema.ServerCapabilities buildServerCapabilities() {
private static final Set<String> RDF_DEPENDENT_TOOLS =
Set.of("sparql_query", "entity_neighborhood", "find_by_tag", "shacl_validate");

private static final Set<String> WRITE_HELPER_TOOLS = Set.of("describe_entity_type");

/**
* Advertises the knowledge-graph tools only where they can actually run.
*
Expand Down Expand Up @@ -138,6 +142,41 @@ private static boolean rdfEnabled() {
return repository != null && repository.isEnabled();
}

/**
* Read-only mode, for every caller including admins, whom no policy can deny. It filters here,
* after a subclass has added its own tools in {@link #getTools()}, so those are covered too.
* Tools are registered once at startup, so {@link #executeTool} checks again on every call:
* turning the mode on blocks writes before the restart that drops them from tools/list. See
* ADR:2026-11-04-mcp-read-only-mode-hides-write-tools.
*/
static List<McpSchema.Tool> exposedTools(List<McpSchema.Tool> tools, MCPConfiguration config) {
List<McpSchema.Tool> exposed = tools;
if (isReadOnlyMode(config)) {
exposed = tools.stream().filter(McpServer::isAvailableInReadOnlyMode).toList();
LOG.info(
"[MCP] Read-only mode; withholding {} write tool(s) from tools/list",
tools.size() - exposed.size());
}
return exposed;
}

private static boolean isReadOnlyMode(MCPConfiguration config) {
return config != null && Boolean.TRUE.equals(config.getReadOnly());
}

// The MCP spec defaults readOnlyHint to false, so a tool without it counts as a write tool.
// describe_entity_type only reads, but it exists to prepare a create_entity call.
private static boolean isAvailableInReadOnlyMode(McpSchema.Tool tool) {
boolean readOnlyHint =
tool.annotations() != null && Boolean.TRUE.equals(tool.annotations().readOnlyHint());
return readOnlyHint && !WRITE_HELPER_TOOLS.contains(tool.name());
}

private static boolean isRefusedInReadOnlyMode(McpSchema.Tool tool) {
return isReadOnlyMode(SecurityConfigurationManager.getCurrentMcpConfig())
&& !isAvailableInReadOnlyMode(tool);
}

protected List<McpSchema.Prompt> getPrompts() {
return promptsContext.loadPromptsDefinitionsFromJson("json/data/mcp/prompts.json");
}
Expand Down Expand Up @@ -323,7 +362,11 @@ private McpSchema.CallToolResult executeTool(
try {
ImpersonationContext.setImpersonatedBy(getMcpBotName());
outcome =
toolContext.callToolWithMetadata(authorizer, limits, tool.name(), securityContext, req);
isRefusedInReadOnlyMode(tool)
? DefaultToolContext.forbidden(
"The MCP server is in read-only mode, so " + tool.name() + " is unavailable")
: toolContext.callToolWithMetadata(
authorizer, limits, tool.name(), securityContext, req);
return outcome.result();
} finally {
recordUsage(tool.name(), userName, clientName, outcome);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,14 @@ static McpSchema.CallToolResult buildSuccessResult(Object result, String toolNam
.build();
}

/** A call refused before it reaches any tool, answered in the shape of a tool's own 403. */
public static CallToolOutcome forbidden(String message) {
return new CallToolOutcome(
errorResult(errorPayload(message, STATUS_FORBIDDEN)),
0L,
McpToolCallUsage.ErrorCategory.AUTH);
}

private static McpSchema.CallToolResult errorResult(Map<String, Object> error) {
return McpSchema.CallToolResult.builder()
.content(List.of(new McpSchema.TextContent(JsonUtils.pojoToJson(error))))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/*
* Copyright 2026 Collate
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.openmetadata.mcp;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import io.modelcontextprotocol.common.McpTransportContext;
import io.modelcontextprotocol.spec.McpSchema;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.openmetadata.mcp.prompts.DefaultPromptsContext;
import org.openmetadata.mcp.tools.DefaultToolContext;
import org.openmetadata.mcp.usage.McpUsageRecorder;
import org.openmetadata.schema.api.configuration.MCPConfiguration;
import org.openmetadata.service.security.JwtFilter;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
import org.openmetadata.service.security.auth.SecurityConfigurationManager;

class McpReadOnlyModeTest {

private static final String TOKEN = "token";

private static final Set<String> WITHHELD_TOOLS =
Set.of(
"create_entity",
"patch_entity",
"create_lineage",
"create_test_case",
"describe_entity_type");

private static final MCPConfiguration READ_ONLY = new MCPConfiguration().withReadOnly(true);

private static final McpSchema.CallToolResult SUCCESS =
McpSchema.CallToolResult.builder()
.content(List.of(new McpSchema.TextContent("{}")))
.isError(false)
.build();

@Test
void readOnlyModeWithholdsTheWriteToolsAndKeepsTheReadTools() {
List<McpSchema.Tool> tools = new McpServer().getTools();

List<String> exposed = names(McpServer.exposedTools(tools, READ_ONLY));

WITHHELD_TOOLS.forEach(tool -> assertFalse(exposed.contains(tool), tool + " is a write tool"));
assertEquals(tools.size() - WITHHELD_TOOLS.size(), exposed.size());
assertTrue(exposed.contains("search_metadata"));
}

@Test
void aToolWithoutAReadOnlyHintIsWithheld() {
McpSchema.Tool unannotated = McpSchema.Tool.builder().name("unannotated").build();

assertTrue(McpServer.exposedTools(List.of(unannotated), READ_ONLY).isEmpty());
}

@Test
void everyToolIsExposedWhenReadOnlyIsOffOrUnset() {
List<McpSchema.Tool> tools = new McpServer().getTools();

assertEquals(tools, McpServer.exposedTools(tools, new MCPConfiguration()));
assertEquals(tools, McpServer.exposedTools(tools, null));
}

@Test
void aRegisteredWriteToolIsRefusedOnceReadOnlyIsTurnedOn() {
DefaultToolContext toolContext = succeedingToolContext();

McpSchema.CallToolResult result = callInReadOnlyMode(toolContext, "patch_entity");

assertTrue(result.isError(), "patch_entity must not run in read-only mode");
assertEquals(403, ((Map<?, ?>) result.structuredContent()).get("statusCode"));
verify(toolContext, never()).callToolWithMetadata(any(), any(), any(), any(), any());
}

@Test
void aReadToolStillRunsInReadOnlyMode() {
assertSame(SUCCESS, callInReadOnlyMode(succeedingToolContext(), "search_metadata"));
}

private static DefaultToolContext succeedingToolContext() {
DefaultToolContext toolContext = mock(DefaultToolContext.class);
when(toolContext.callToolWithMetadata(any(), any(), any(), any(), any()))
.thenReturn(new DefaultToolContext.CallToolOutcome(SUCCESS, 0L, null));
return toolContext;
}

private static McpSchema.CallToolResult callInReadOnlyMode(
DefaultToolContext toolContext, String toolName) {
McpServer server = new McpServer(toolContext, new DefaultPromptsContext());
server.jwtFilter = jwtFilterFor("alice");
McpSchema.CallToolRequest request =
McpSchema.CallToolRequest.builder().name(toolName).arguments(Map.of()).build();

try (MockedStatic<SecurityConfigurationManager> config =
mockStatic(SecurityConfigurationManager.class);
MockedStatic<McpUsageRecorder> usage = mockStatic(McpUsageRecorder.class)) {
config.when(SecurityConfigurationManager::getCurrentMcpConfig).thenReturn(READ_ONLY);
return server.getTool(toolNamed(toolName)).callHandler().apply(callerContext(), request);
}
}

private static McpSchema.Tool toolNamed(String name) {
return new McpServer()
.getTools().stream().filter(tool -> tool.name().equals(name)).findFirst().orElseThrow();
}

private static JwtFilter jwtFilterFor(String userName) {
CatalogSecurityContext securityContext = mock(CatalogSecurityContext.class);
when(securityContext.getUserPrincipal()).thenReturn(() -> userName);
JwtFilter jwtFilter = mock(JwtFilter.class);
when(jwtFilter.getCatalogSecurityContext(TOKEN)).thenReturn(securityContext);
return jwtFilter;
}

private static McpTransportContext callerContext() {
return McpTransportContext.create(
Map.of(AuthEnrichedMcpContextExtractor.AUTHORIZATION_HEADER, TOKEN));
}

private static List<String> names(List<McpSchema.Tool> tools) {
return tools.stream().map(McpSchema.Tool::name).toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@
"type": "integer",
"minimum": 25000,
"default": 100000
},
"readOnly": {
"description": "Expose only the MCP tools that do not change metadata (annotated readOnlyHint), for every user including admins. Turning it on blocks write tools right away; they leave tools/list after a restart, and turning it off applies after a restart.",
"type": "boolean",
"default": false
}
},
"additionalProperties": false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,11 @@ $$section

Largest MCP tool response, in characters. Tools return fewer items to stay under it, so it bounds how much of the MCP client's context one call can use. Lower it for clients with a small context window; raise it for ones with a large window. Default: 100,000 (about 25,000 tokens); minimum 25,000. A saved change applies right away on the server that handled the save; other servers in a cluster pick it up on restart.

$$

$$section
### Read-only Mode $(id="readOnly")

Expose only the MCP tools that do not change metadata, such as search, lineage and entity details. Tools that create or edit metadata are blocked for every MCP client and every user, admins included. Each user's own permissions still apply to the remaining tools. Turning it on blocks those tools right away; they leave the tool list after the server restarts, and turning it off takes effect after a restart.

$$
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ describe('McpApplicationConfiguration', () => {
it.each([
[
'every field the form shows',
['/baseUrl', '/allowedOrigins', '/maxResponseChars'],
['/baseUrl', '/allowedOrigins', '/maxResponseChars', '/readOnly'],
],
['the whole setting', ['/']],
])(
Expand Down Expand Up @@ -323,7 +323,12 @@ describe('McpApplicationConfiguration', () => {

describe('McpApplication form schema', () => {
const formSchema = mcpSchema as RJSFSchema;
const editableFields = ['baseUrl', 'allowedOrigins', 'maxResponseChars'];
const editableFields = [
'baseUrl',
'allowedOrigins',
'maxResponseChars',
'readOnly',
];
// Shape of a real stored mcpConfiguration row, including the fields no code reads.
const storedConfig = {
path: '/api/v1/mcp',
Expand All @@ -333,6 +338,7 @@ describe('McpApplication form schema', () => {
mcpServerName: 'openmetadata-mcp-server',
allowedOrigins: ['http://localhost:3000', 'https://app.example.com'],
maxResponseChars: 100000,
readOnly: true,
connectTimeout: 30000,
originHeaderUri: 'http://localhost',
mcpServerVersion: '1.0.0',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const storedConfig = {
baseUrl: 'https://om.example.com',
allowedOrigins: ['http://localhost:3000'],
maxResponseChars: 100000,
readOnly: true,
connectionTimeoutSecs: 30,
};

Expand Down Expand Up @@ -91,6 +92,7 @@ describe('useMcpConfiguration', () => {
baseUrl: 'https://om.example.com',
allowedOrigins: ['http://localhost:3000'],
maxResponseChars: 100000,
readOnly: true,
});
expect(result.current.isEveryFieldManaged).toBe(false);
});
Expand Down Expand Up @@ -180,7 +182,12 @@ describe('useMcpConfiguration', () => {
it('marks the whole form managed when the deployment owns every field', async () => {
mockGetSettingsSource.mockResolvedValue({
settings: [
mcpSource(['/baseUrl', '/allowedOrigins', '/maxResponseChars']),
mcpSource([
'/baseUrl',
'/allowedOrigins',
'/maxResponseChars',
'/readOnly',
]),
],
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,14 @@ import applicationsClassBase from '../AppDetails/ApplicationsClassBase';
* wrong base URL breaks the OAuth metadata behind a load balancer. The response cap depends on
* which MCP clients connect, so it is set here too. Everything else in the stored
* `mcpConfiguration` (timeouts, plus fields no code reads) stays out of the form but is merged
* back on save, because the PUT replaces the whole setting.
* back on save, because the PUT replaces the whole setting. Read-only mode is an admin choice, so
* it is edited here as well.
*/
const EDITABLE_MCP_CONFIG_FIELDS: (keyof MCPConfiguration)[] = [
'baseUrl',
'allowedOrigins',
'maxResponseChars',
'readOnly',
];

const MCP_SETTING_TYPES = [SettingType.MCPConfiguration];
Expand Down
Loading
Loading