Skip to content
13 changes: 8 additions & 5 deletions docs/decisions/2026-11-12-mcp-turns-off-at-request-time.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# MCP turns off at request time, when its app is disabled or its setting is off

- **Status:** Accepted
- **Revisions:** v1 2026-11-12 (initial)
- **Revisions:** v1 2026-11-12 (initial); v2 2026-11-18 (app state read in the background, not per request)
- **Deciders:** Vishnu Jain
- **Guard:** `McpAvailabilityIT`
- **Related:** #37687, #29201, #30041
Expand Down Expand Up @@ -29,14 +29,17 @@ kept answering, and an uninstalled app is re-seeded at the next start. Setting
follows at once, other servers when the settings watcher picks the change up
(`watchIntervalSeconds`, 10 by default). `SettingsCache` was not used because it does not cache
a missing value, so an install that never saved the setting would query on every request.
- The app is read through the entity cache: the server that took the click follows at once,
other servers when their entry expires (30 seconds by default).
- The app's state is kept in memory and re-read through the entity cache every 2 seconds in the
background, starting when MCP is mounted. A request never reads the database for it: v1 read it
per request, so once the cached entry expired, a database outage made every `/mcp` request hang
on that read instead of reaching the auth check that answers 503 with `Retry-After`. A failed
re-read keeps the last state. The server that took the click follows within about 2 seconds,
other servers when their entity cache entry expires (30 seconds by default) plus up to 2 seconds.

## Consequences

Disable stops MCP and Enable brings it back, with no restart. Uninstall stops MCP until the next
start re-seeds the app; until then each refused request runs one indexed lookup, because a
missing app is not cached for `Include.ALL`. A refusal is a bare 404 status, not `sendError`, because the server maps
start re-seeds the app. A refusal is a bare 404 status, not `sendError`, because the server maps
404 errors to the UI page. A deployment that disabled the app but kept using MCP, which worked
while the app state was ignored, loses MCP on upgrade until the app is enabled. A new MCP route
must sit under `/mcp/` or check `McpAvailabilityFilter.isMcpAvailable()` itself, or it keeps
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public final class MockResponseGate {

private final CountDownLatch arrived = new CountDownLatch(1);
private final CountDownLatch released = new CountDownLatch(1);
private final CountDownLatch completed = new CountDownLatch(1);

/** Blocks the mock's handler thread until {@link #release()}, or {@link #MAX_HOLD} passes. */
public void holdResponse() {
Expand All @@ -30,6 +31,19 @@ public void release() {
released.countDown();
}

/** Called by the mock once the held request has been answered. */
public void complete() {
completed.countDown();
}

/**
* Waits until the held request has been answered, so a test that releases it cannot have that
* late answer land in the next test.
*/
public boolean awaitCompletion(Duration timeout) {
return awaitQuietly(completed, timeout);
}

private static boolean awaitQuietly(CountDownLatch latch, Duration timeout) {
try {
return latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,16 @@ MockResponseGate holdNextResponse() {
public void handle(HttpExchange exchange) throws IOException {
Map<String, String> form = MockHttp.formParameters(exchange);
journal.record(exchange, form);
Optional.ofNullable(pendingGates.poll()).ifPresent(MockResponseGate::holdResponse);
if (isRegisteredClient(exchange, form)) {
respondToGrant(exchange, form);
} else {
respondError(exchange, UNAUTHORIZED, INVALID_CLIENT);
Optional<MockResponseGate> gate = Optional.ofNullable(pendingGates.poll());
gate.ifPresent(MockResponseGate::holdResponse);
try {
if (isRegisteredClient(exchange, form)) {
respondToGrant(exchange, form);
} else {
respondError(exchange, UNAUTHORIZED, INVALID_CLIENT);
}
} finally {
gate.ifPresent(MockResponseGate::complete);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,16 @@ class DataProductDeleteRaceIT {

private static final Duration BLOCKED_WITHIN = Duration.ofSeconds(60);
private static final String CASCADE_PAUSE_EXTENSION = "dataProduct.cascadePause";
// MySQL reports the table each blocked transaction waits on; its statement text in
// innodb_trx missed the waiters on CI, where the requests then ran into the 50s lock timeout.
private static final String MYSQL_LOCK_WAITS =
"""
SELECT trx_query FROM information_schema.innodb_trx WHERE trx_state = 'LOCK WAIT'""";
SELECT DISTINCT w.REQUESTING_ENGINE_TRANSACTION_ID, l.OBJECT_NAME AS waiting
FROM performance_schema.data_lock_waits w
JOIN performance_schema.data_locks l ON l.ENGINE_LOCK_ID = w.REQUESTING_ENGINE_LOCK_ID""";
private static final String POSTGRES_LOCK_WAITS =
"""
SELECT query FROM pg_stat_activity
SELECT query AS waiting FROM pg_stat_activity
WHERE wait_event_type = 'Lock' AND datname = current_database()""";
private static final String DATA_PRODUCT_ROWS =
"""
Expand Down Expand Up @@ -277,10 +281,8 @@ private static CompletableFuture<?> async(Runnable request) {
}

/**
* Waits until {@code request} has returned or {@code waiters} statements on {@code tables} are
* waiting on a row lock. Statements are matched on the table, not the row id: the blocked
* statement need not name the held row (a MySQL run once waited the full minute on a statement
* without the data product's id), and Postgres shows placeholders instead of bound values.
* Waits until {@code request} has returned or {@code waiters} transactions wait on a row lock in
* {@code tables}: the locked table on MySQL, the waiting statement's text on Postgres.
*/
private static void awaitBlocked(CompletableFuture<?> request, int waiters, List<String> tables) {
Awaitility.await("request done or %d statements waiting on a row lock".formatted(waiters))
Expand All @@ -293,7 +295,8 @@ private static long lockWaiters(List<String> tables) {
boolean mysql = TestSuiteBootstrap.getConnectionType() == ConnectionType.MYSQL;
String waiting = mysql ? MYSQL_LOCK_WAITS : POSTGRES_LOCK_WAITS;
List<String> statements =
lockProbe.withHandle(h -> h.createQuery(waiting).mapTo(String.class).list());
lockProbe.withHandle(
h -> h.createQuery(waiting).map((row, ctx) -> row.getString("waiting")).list());
return statements.stream()
.filter(sql -> sql != null && tables.stream().anyMatch(table -> mentionsTable(sql, table)))
.count();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2819,6 +2819,9 @@ void put_reingestingANewExpressionChangesOnlyTheExpression(TestNamespace ns) {
curated.setExperts(List.of(shared.USER2_REF));
patchEntity(curated.getId().toString(), curated);
patchMetricReviewers(metric.getId(), List.of(shared.USER1_REF));
// The reviewer change starts an approval run that writes In Review asynchronously; let it land
// first so the baseline status is the one the bot's re-ingest must leave unchanged.
awaitApprovalTask(metric);
Metric beforeRerun = getEntityWithFields(metric.getId().toString(), curatedFields);
assertEquals(List.of(shared.USER1_REF.getId()), ids(beforeRerun.getReviewers()));
assertEquals(List.of(shared.USER2_REF.getId()), ids(beforeRerun.getExperts()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ void libraryPreviewCannotReadDeniedWorkingDefinitions(TestNamespace ns) {
Map.entry("dcat", 48),
Map.entry("dpv", 3688),
Map.entry("epcis", 199),
Map.entry("fhir", 16404),
Map.entry("fhir", 15673),
Map.entry("fibo", 9901),
Map.entry("foaf", 100),
Map.entry("gs1", 1071),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,9 @@ void failingTokenEndpointEndsOnTheSignInPage(TestNamespace ns) {
assertLoginEndsOnSignIn(timedOut, login(timedOut), TOKEN_EXCHANGE_FAILED);
} finally {
unanswered.release();
// The released exchange still mints an ID token; let it land before the next test reads the
// provider's last issued token.
unanswered.awaitCompletion(Duration.ofSeconds(10));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Completion timeouts go unnoticed. awaitCompletion() returns false on timeout or interruption, but this call ignores the result. The test can pass while the released exchange is still running, leaving the late ID token free to affect the next test—the race this change aims to remove. Assert that the wait succeeds so a failed cleanup is reported here.

}
assertNoAccountFor(identity);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
package org.openmetadata.mcp;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.openmetadata.schema.api.configuration.MCPConfiguration;
import org.openmetadata.schema.entity.app.App;
import org.openmetadata.schema.type.Include;
Expand All @@ -21,6 +27,23 @@
*/
public class McpAvailabilityFilter implements Filter {

private static final long APP_STATE_REFRESH_SECONDS = 2;
private static final ScheduledExecutorService APP_STATE_REFRESHER =
Executors.newSingleThreadScheduledExecutor(
Thread.ofPlatform().daemon().name("mcp-availability").factory());

/**
* The app's state is served from memory and re-read in the background, so a request never waits
* on the database: during an outage MCP keeps the last state it read, and its auth answers 503
* instead of the request hanging on this read. A failed re-read keeps the previous state.
*/
private static final LoadingCache<String, Boolean> APP_ACTIVE =
CacheBuilder.newBuilder()
.maximumSize(1)
.build(
CacheLoader.asyncReloading(
CacheLoader.from(McpAvailabilityFilter::readAppActive), APP_STATE_REFRESHER));

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Expand Down Expand Up @@ -50,14 +73,25 @@ private static boolean isEnabledInSettings() {
return config == null || Boolean.TRUE.equals(config.getEnabled());
}

/** Starts re-reading the app's state in the background, beginning while the database is up. */
public static void startAppStateRefresh() {
APP_STATE_REFRESHER.scheduleWithFixedDelay(
() -> APP_ACTIVE.refresh(McpAppConstants.MCP_APP_NAME),
0,
APP_STATE_REFRESH_SECONDS,
TimeUnit.SECONDS);
Comment on lines +77 to +82

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Refresh task outlives the server. startAppStateRefresh() starts a repeating task but keeps no handle to cancel it. The server's stop hook only stops OAuthTokenCleanupScheduler. Stopping an embedded server therefore leaves this task reading shared repositories, and starting another server in the same JVM adds another task. Tie the task to the server's start and stop hooks, and prevent duplicate scheduling.

}

private static boolean isAppActive() {
return APP_ACTIVE.getUnchecked(McpAppConstants.MCP_APP_NAME);
}

/**
* Through the entity cache. Disabling the app soft-deletes it; uninstalling removes it until a
* restart re-seeds it.
*/
private static boolean isAppActive() {
App app =
Entity.findEntityByNameOrNull(
Entity.APPLICATION, McpAppConstants.MCP_APP_NAME, Include.ALL);
private static boolean readAppActive(String appName) {
App app = Entity.findEntityByNameOrNull(Entity.APPLICATION, appName, Include.ALL);
return app != null && !Boolean.TRUE.equals(app.getDeleted());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ public void stop() {

/** FORWARD covers the SSO callback, which /callback forwards to /mcp/callback. */
private static void registerAvailabilityFilter(Environment environment) {
McpAvailabilityFilter.startAppStateRefresh();
environment
.servlets()
.addFilter("mcp-availability", new McpAvailabilityFilter())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.openmetadata.schema.type.TagLabel;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.service.Entity;
import org.openmetadata.service.cache.CacheBundle;
import org.openmetadata.service.jdbi3.CollectionDAO;
import org.openmetadata.service.jdbi3.EntityRepository;
import org.openmetadata.service.jdbi3.locator.ConnectionType;
Expand Down Expand Up @@ -242,6 +243,9 @@ private static Outcome repair(
}
EntityRepository.invalidateCacheForEntity(CONTEXT_FILE, misnamed.id(), misnamed.storedFqn());
EntityRepository.invalidateCacheForEntity(CONTEXT_FILE, misnamed.id(), misnamed.derivedFqn());
// A lookup of the derived FQN before the repair left a not-found marker that the entity
// cache helper above does not clear.
CacheBundle.invalidateEntity(CONTEXT_FILE, misnamed.id(), misnamed.derivedFqn());
reindex(repaired.get());
if (!sharing.isEmpty()) {
LOG.warn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -879,7 +879,12 @@ username, new CreateUser().withName(username).withEmail(email).withIsBot(false))

return UserUtil.createOrAdoptConcurrentlyCreatedUser(
() -> UserUtil.addOrUpdateUser(newUser),
() -> Entity.getEntityByName(Entity.USER, username, USER_FIELDS, Include.NON_DELETED),
// From the database: the losing login's own miss can leave a not-found marker that
// would
// hide the account the winning login just committed.
() ->
Entity.getEntityByName(
Entity.USER, username, USER_FIELDS, Include.NON_DELETED, false),
email);
}
throw new AuthenticationException("User not found and self-signup is disabled");
Expand Down
Loading