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
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class PersonaAIContextIT extends McpTestBase {
private static final String ACTIVE_PERSONA_HEADER = "X-OpenMetadata-Persona";
private static Persona persona;
private static Table table;
private static String directMemberToken;
Expand Down Expand Up @@ -323,6 +324,104 @@ void twoScopedRulesSelectTheUnionOfBothWhenTheFilterIsActuallySearched() throws
}
}

@Test
void mcpSearchAppliesPersonaScopeByDefaultAndCanExplicitlyBypassIt() throws Exception {
String suffix = shortId();
Table selected = createServiceDatabaseSchemaTable("persona_mcp_selected_" + suffix);
Table excluded = createServiceDatabaseSchemaTable("persona_mcp_excluded_" + suffix);
User member = createUser("persona_mcp_member_" + suffix);
Persona owned =
post(
"personas",
new CreatePersona()
.withName("persona_mcp_" + suffix)
.withDescription("MCP persona search scope integration test")
.withUsers(List.of(member.getId())),
Persona.class);
String contextPath = "personas/" + owned.getId() + "/aiContext";
String token = tokenFor(member);

try {
put(
contextPath,
new PersonaContextDefinition().withEnabled(true),
PersonaContextDefinition.class);
post(
contextPath + "/rules",
scopedFqnRule("MCP scope", selected.getFullyQualifiedName()),
PersonaContextDefinition.class);

Awaitility.await("MCP search consumes the active persona scope")
.atMost(Duration.ofSeconds(60))
.pollDelay(Duration.ofSeconds(1))
.pollInterval(Duration.ofSeconds(2))
.untilAsserted(
() -> {
JsonNode scoped =
searchMetadataWithPersona(owned, token, selected, excluded, false);
assertThat(resultFqns(scoped)).containsExactly(selected.getFullyQualifiedName());
assertThat(scoped.path("personaScopeApplied").asBoolean()).isTrue();

JsonNode unscoped =
searchMetadataWithPersona(owned, token, selected, excluded, true);
assertThat(resultFqns(unscoped))
.containsExactlyInAnyOrder(
selected.getFullyQualifiedName(), excluded.getFullyQualifiedName());
assertThat(unscoped.has("personaScopeApplied")).isFalse();
});
} finally {
deleteResponse("personas/" + owned.getId() + "?hardDelete=true", authToken);
}
}

private JsonNode searchMetadataWithPersona(
Persona activePersona, String token, Table first, Table second, boolean ignoreScope)
throws Exception {
String queryFilter =
OBJECT_MAPPER.writeValueAsString(
Map.of(
"bool",
Map.of(
"filter",
List.of(
Map.of("term", Map.of("entityType", Entity.TABLE)),
Map.of(
"terms",
Map.of(
"fullyQualifiedName",
List.of(
first.getFullyQualifiedName(),
second.getFullyQualifiedName())))))));
Map<String, Object> arguments =
Map.of(
"query",
"*",
"entityType",
Entity.TABLE,
"queryFilter",
queryFilter,
"size",
10,
"ignorePersonaScope",
ignoreScope);
JsonNode response =
executeMcp(
McpTestUtils.createToolCallRequest("search_metadata", arguments),
token,
activePersona.getFullyQualifiedName());
JsonNode toolResult = response.path("result");
assertThat(toolResult.path("isError").asBoolean(false)).isFalse();
return OBJECT_MAPPER.readTree(toolResult.path("content").get(0).path("text").asText());
}

private static Set<String> resultFqns(JsonNode response) {
Set<String> fqns = new HashSet<>();
response
.path("results")
.forEach(result -> fqns.add(result.path("fullyQualifiedName").asText()));
return fqns;
}

/** Polls until the served scope includes selected assets and excludes unscoped assets. */
private static void awaitScopeIncludes(
Persona owner, Set<String> selectedAssets, Set<String> excludedAssets) {
Expand Down Expand Up @@ -462,17 +561,25 @@ void aiContextRulesAreReadableByAnyUserButEditableOnlyByAdmins() throws Exceptio
}

private JsonNode executeMcp(Map<String, Object> requestBody, String token) throws Exception {
HttpRequest request =
return executeMcp(requestBody, token, null);
}

private JsonNode executeMcp(Map<String, Object> requestBody, String token, String activePersona)
throws Exception {
HttpRequest.Builder request =
HttpRequest.newBuilder()
.uri(URI.create(getMcpUrl("/mcp")))
.header("Content-Type", "application/json")
.header("Accept", "application/json, text/event-stream")
.header("Authorization", token)
.POST(
HttpRequest.BodyPublishers.ofString(OBJECT_MAPPER.writeValueAsString(requestBody)))
.timeout(Duration.ofSeconds(30))
.build();
HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
.timeout(Duration.ofSeconds(30));
if (activePersona != null) {
request.header(ACTIVE_PERSONA_HEADER, activePersona);
}
HttpResponse<String> response =
HTTP_CLIENT.send(request.build(), HttpResponse.BodyHandlers.ofString());
assertThat(response.statusCode()).isEqualTo(200);
return OBJECT_MAPPER.readTree(extractJsonFromResponse(response.body()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
public class AuthEnrichedMcpContextExtractor
implements McpTransportContextExtractor<HttpServletRequest> {
public static final String AUTHORIZATION_HEADER = "Authorization";
public static final String ACTIVE_PERSONA_HEADER = JwtFilter.ACTIVE_PERSONA_HEADER;

/**
* Context key carrying the resolved client name (Claude Desktop / Cursor / VS Code / etc.)
Expand Down Expand Up @@ -64,9 +65,13 @@ private record UaMatcher(Predicate<String> matches, String label) {}
@Override
public McpTransportContext extract(HttpServletRequest request) {
String token = JwtFilter.extractToken(request.getHeader(AUTHORIZATION_HEADER));
String activePersona = request.getHeader(ACTIVE_PERSONA_HEADER);
String clientName = resolveClientName(request.getHeader(USER_AGENT_HEADER));
Map<String, Object> values = new HashMap<>();
values.put(AUTHORIZATION_HEADER, token != null ? token : "");
if (activePersona != null && !activePersona.isBlank()) {
values.put(ACTIVE_PERSONA_HEADER, activePersona);
}
if (clientName != null) {
values.put(CLIENT_NAME, clientName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,13 @@ protected McpStatelessServerFeatures.SyncToolSpecification getTool(McpSchema.Too
return new McpStatelessServerFeatures.SyncToolSpecification(
tool,
(context, req) -> {
String token = (String) context.get(AuthEnrichedMcpContextExtractor.AUTHORIZATION_HEADER);
String activePersona =
(String) context.get(AuthEnrichedMcpContextExtractor.ACTIVE_PERSONA_HEADER);
CatalogSecurityContext securityContext =
jwtFilter.getCatalogSecurityContext((String) context.get("Authorization"));
activePersona == null
? jwtFilter.getCatalogSecurityContext(token)
: jwtFilter.getCatalogSecurityContext(token, activePersona);
String userName = securityContext.getUserPrincipal().getName();
String clientName =
(String)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public class OAuthHttpStatelessServerTransportProvider extends HttpServletStatel
// Mcp-Method, Mcp-Name - required since protocol 2026-07-28, so gateways can route and meter
// requests without reading the JSON body
// Mcp-Client-Name - our own header, read by AuthEnrichedMcpContextExtractor
// X-OpenMetadata-Persona - selects an assigned persona for scoped searches
static final String CORS_ALLOWED_HEADERS =
String.join(
", ",
Expand All @@ -92,7 +93,8 @@ public class OAuthHttpStatelessServerTransportProvider extends HttpServletStatel
"MCP-Protocol-Version",
"Mcp-Method",
"Mcp-Name",
AuthEnrichedMcpContextExtractor.CLIENT_NAME));
AuthEnrichedMcpContextExtractor.CLIENT_NAME,
AuthEnrichedMcpContextExtractor.ACTIVE_PERSONA_HEADER));

// After a 401 the client reads WWW-Authenticate to find this authorization server. Browsers hide
// response headers unless we expose them, so without this the client cannot start the OAuth flow.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
* 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.tools;

import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.openmetadata.schema.entity.teams.Persona;
import org.openmetadata.schema.type.PersonaContextDefinition;
import org.openmetadata.schema.type.personaContext.SearchScope;
import org.openmetadata.schema.utils.JsonUtils;
import org.openmetadata.service.aicontext.PersonaContextAccess;
import org.openmetadata.service.aicontext.PersonaContextBuilder;
import org.openmetadata.service.exception.EntityNotFoundException;
import org.openmetadata.service.security.auth.CatalogSecurityContext;

@Slf4j
record PersonaSearchScope(String queryFilter, List<String> entityTypes) {

PersonaSearchScope {
entityTypes = List.copyOf(entityTypes);
}

static Optional<PersonaSearchScope> resolve(CatalogSecurityContext securityContext) {
try {
Persona persona = PersonaContextAccess.activePersona(securityContext);
PersonaContextDefinition definition = persona.getContextDefinition();
SearchScope compiled =
PersonaContextBuilder.searchScope(
definition == null ? new PersonaContextDefinition() : definition);
return from(compiled);
} catch (EntityNotFoundException exception) {
LOG.debug("No active persona search scope is configured");
return Optional.empty();
} catch (RuntimeException exception) {
LOG.warn("Unable to apply the active persona's search scope", exception);
return Optional.empty();
}
}

static Optional<PersonaSearchScope> from(SearchScope scope) {
if (scope == null
|| nullOrEmpty(scope.getQueryFilter())
|| nullOrEmpty(scope.getEntityTypes())) {
return Optional.empty();
}
try {
queryNode(scope.getQueryFilter());
return Optional.of(
new PersonaSearchScope(scope.getQueryFilter(), new ArrayList<>(scope.getEntityTypes())));
} catch (RuntimeException exception) {
LOG.warn("Ignoring an invalid persona search scope: {}", exception.getMessage());
return Optional.empty();
}
}

String applyTo(String callerFilter) {
if (nullOrEmpty(callerFilter)) {
return queryFilter;
}
ObjectNode root = JsonUtils.getObjectMapper().createObjectNode();
ArrayNode filters = root.putObject("query").putObject("bool").putArray("filter");
filters.add(queryNode(callerFilter));
filters.add(queryNode(queryFilter));
return JsonUtils.pojoToJson(root);
}

void annotate(Map<String, Object> response) {
response.put("personaScopeApplied", true);
response.put("personaScopeEntityTypes", entityTypes);
if (response.get("returnedCount") instanceof Number count && count.longValue() == 0) {
response.put(
"message",
"No results matched the active persona scope. If the user wants to search beyond it, "
+ "retry with ignorePersonaScope=true.");
}
}

private static JsonNode queryNode(String filter) {
JsonNode root = JsonUtils.readTree(filter);
JsonNode query = root != null && root.has("query") ? root.get("query") : root;
if (query == null || !query.isObject() || query.isEmpty()) {
throw new IllegalArgumentException("Persona queryFilter must contain a query object");
}
return query;
}

@FunctionalInterface
interface Provider {
Optional<PersonaSearchScope> resolve(CatalogSecurityContext securityContext);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ public class SearchMetadataTool implements McpTool {
private static final String DESCRIPTION_TRUNCATED_KEY = "descriptionTruncated";
private static final String TEST_CASE_ENTITY = "testCase";
private static final String NEVER_RUN_KEY = "neverRun";
private final PersonaSearchScope.Provider personaSearchScopeProvider;

public SearchMetadataTool() {
this(PersonaSearchScope::resolve);
}

@VisibleForTesting
SearchMetadataTool(PersonaSearchScope.Provider personaSearchScopeProvider) {
this.personaSearchScopeProvider = personaSearchScopeProvider;
}

private static final List<String> ESSENTIAL_FIELDS_ONLY =
List.of(
Expand Down Expand Up @@ -258,11 +268,16 @@ public Map<String, Object> execute(
// the text query (OpenSearchSearchManager#applyQueryFilter) and additionally applies the
// deleted
// filter, ranked scoring, and the search preference.
String effectiveQueryFilter = nullOrEmpty(queryFilter) ? exclusionFilter : queryFilter;
Optional<PersonaSearchScope> personaScope = personaSearchScope(securityContext, params);
if (personaScope.isPresent()) {
effectiveQueryFilter = personaScope.orElseThrow().applyTo(effectiveQueryFilter);
}
SearchRequest searchRequest =
new SearchRequest()
.withQuery(nullOrEmpty(query) ? MATCH_ANY_QUERY : query)
.withIndex(Entity.getSearchRepository().getIndexOrAliasName(index))
.withQueryFilter(nullOrEmpty(queryFilter) ? exclusionFilter : queryFilter)
.withQueryFilter(effectiveQueryFilter)
.withSize(size)
.withFrom(from)
.withFetchSource(true)
Expand Down Expand Up @@ -290,7 +305,16 @@ public Map<String, Object> execute(
requestedFields,
includeAggregations,
maxAggregationBuckets);
return dropExcludedTypes(enhanced, excludedTypes);
Map<String, Object> result = dropExcludedTypes(enhanced, excludedTypes);
personaScope.ifPresent(scope -> scope.annotate(result));
return result;
}

private Optional<PersonaSearchScope> personaSearchScope(
CatalogSecurityContext securityContext, Map<String, Object> params) {
return McpParams.getBoolean(params, "ignorePersonaScope", false)
? Optional.empty()
: personaSearchScopeProvider.resolve(securityContext);
}

/**
Expand Down
Loading
Loading