offered = new HashSet<>();
+ list.path("result").path("tools").forEach(tool -> offered.add(tool.path("name").asText()));
+
+ assertThat(offered).doesNotContainAnyElementsOf(WITHHELD).contains("ontology_describe");
+ }
+
+ @Test
+ void aDirectCallToAWithheldToolDoesNotSucceed() throws Exception {
+ final JsonNode response =
+ executeMcpRequest(
+ McpTestUtils.createToolCallRequest(
+ "sparql_query", Map.of("query", "SELECT ?s WHERE { ?s ?p ?o } LIMIT 1")),
+ grantedToken);
+
+ final boolean refused =
+ response.has("error") || response.path("result").path("isError").asBoolean(false);
+ assertThat(refused).as(response.toString()).isTrue();
+ }
+
+ @Test
+ void anAdministratorDescribingAResourceIsToldTheGraphIsNotEnabled() throws Exception {
+ assertNotEnabled(authToken);
+ }
+
+ @Test
+ void aGrantedUserDescribingAResourceIsToldTheGraphIsNotEnabled() throws Exception {
+ assertNotEnabled(grantedToken);
+ }
+
+ private void assertNotEnabled(final String token) throws Exception {
+ final JsonNode result =
+ executeMcpRequest(
+ McpTestUtils.createToolCallRequest(
+ "ontology_describe", Map.of("resource", RESOURCE, "maxBytes", 2048)),
+ token)
+ .path("result");
+
+ assertThat(result.path("isError").asBoolean()).as(result.toString()).isTrue();
+ final JsonNode error =
+ OBJECT_MAPPER.readTree(result.path("content").path(0).path("text").asText());
+ assertThat(error.path("statusCode").asInt()).isEqualTo(400);
+ assertThat(error.path("error").asText()).contains("RDF knowledge graph is not enabled");
+ }
+}
diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/RdfMcpKnowledgeGraphIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/RdfMcpKnowledgeGraphIT.java
new file mode 100644
index 000000000000..ee1aa5138960
--- /dev/null
+++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/RdfMcpKnowledgeGraphIT.java
@@ -0,0 +1,785 @@
+/*
+ * Copyright 2021 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.it.tests.mcp;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+import com.fasterxml.jackson.databind.JsonNode;
+import java.io.StringWriter;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.jena.riot.Lang;
+import org.apache.jena.riot.RDFDataMgr;
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.parallel.Isolated;
+import org.openmetadata.it.bootstrap.TestSuiteBootstrap;
+import org.openmetadata.it.factories.DatabaseSchemaTestFactory;
+import org.openmetadata.it.factories.DatabaseServiceTestFactory;
+import org.openmetadata.it.util.RdfAccessFixtures;
+import org.openmetadata.it.util.RdfTestUtils;
+import org.openmetadata.it.util.SdkClients;
+import org.openmetadata.it.util.TestNamespace;
+import org.openmetadata.it.util.TestNamespaceExtension;
+import org.openmetadata.schema.api.data.CreateTable;
+import org.openmetadata.schema.api.lineage.AddLineage;
+import org.openmetadata.schema.entity.app.AppRunRecord;
+import org.openmetadata.schema.entity.data.DatabaseSchema;
+import org.openmetadata.schema.entity.data.Table;
+import org.openmetadata.schema.entity.services.DatabaseService;
+import org.openmetadata.schema.type.Column;
+import org.openmetadata.schema.type.ColumnDataType;
+import org.openmetadata.schema.type.ColumnLineage;
+import org.openmetadata.schema.type.EntitiesEdge;
+import org.openmetadata.schema.type.LineageDetails;
+import org.openmetadata.schema.type.MetadataOperation;
+import org.openmetadata.sdk.client.OpenMetadataClient;
+import org.openmetadata.sdk.fluent.Tables;
+import org.openmetadata.sdk.fluent.builders.ColumnBuilder;
+import org.openmetadata.sdk.network.HttpClient;
+import org.openmetadata.sdk.network.HttpMethod;
+import org.openmetadata.service.Entity;
+import org.openmetadata.service.apps.AbstractNativeApplication;
+import org.openmetadata.service.apps.ApplicationContext;
+import org.openmetadata.service.apps.bundles.mcp.McpAppConstants;
+import org.openmetadata.service.rdf.ColumnLineageFixture;
+import org.openmetadata.service.rdf.SparqlQueryLimits;
+import org.openmetadata.service.rdf.agent.AgentSparqlAudit;
+import org.slf4j.LoggerFactory;
+
+/**
+ * The RDF knowledge-graph MCP tools for callers who are not administrators.
+ *
+ * Covers who may call which tool, and the use case behind the change: fetching every downstream
+ * (or upstream) column of one column on a graph of thousands of column-lineage mappings by paging
+ * {@code sparql_query}. The paged query is the template published in the tool description, read
+ * back from {@code tools/list}, so the description and the behavior cannot drift apart.
+ *
+ *
The scale data is written in exactly the shape {@code RdfIndexApp} projects (see {@link
+ * ColumnLineageFixture}) into a dedicated named graph, which reads see through the union default
+ * graph, as production entity writes do. A final test builds the same shape through the real
+ * lineage API and a real reindex to show the synthetic data matches real output; it runs last
+ * because a reindex clears the shared dataset.
+ */
+@Isolated
+@ExtendWith(TestNamespaceExtension.class)
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+public class RdfMcpKnowledgeGraphIT extends McpTestBase {
+ private static final String BASE_URI = "https://open-metadata.org/";
+ private static final int INSERT_BATCH_CHARS = 60_000;
+ private static final int PAGE_SIZE = 250;
+ private static final String FORBIDDEN_STATUS = "403";
+ private static final int TOO_MANY_REQUESTS_STATUS = 429;
+ private static final int BAD_REQUEST_STATUS = 400;
+ private static final String FIXTURE_PREFIX = "rdfmcp";
+ private static final String GRANTED_USER = "granted";
+ private static final Set FAILED_RUN_STATUSES =
+ EnumSet.of(AppRunRecord.Status.FAILED, AppRunRecord.Status.ACTIVE_ERROR);
+ private static final Set FINISHED_RUN_STATUSES =
+ EnumSet.of(AppRunRecord.Status.COMPLETED, AppRunRecord.Status.SUCCESS);
+ private static final String APP_NAME = RdfAccessFixtures.RDF_INDEX_APP;
+ private static final String LATEST_RUN_PATH = "/v1/apps/name/" + APP_NAME + "/runs/latest";
+ private static final Pattern COLUMN_LINEAGE_TEMPLATE =
+ Pattern.compile("SELECT DISTINCT \\?column.*?LIMIT 250 OFFSET 0");
+ private static final String TEMPLATE_START_COLUMN = "svc.db.schema.table.col";
+ private static final String DOWNSTREAM_PATH = "^om:fromColumn/om:toColumn";
+ private static final String UPSTREAM_PATH = "^om:toColumn/om:fromColumn";
+
+ /** {@code executeMcpRequest} is an instance method of the base class; helpers here are static. */
+ private static final McpTestBase MCP_CLIENT = new McpTestBase() {};
+
+ private static RdfAccessFixtures access;
+ private static ColumnLineageFixture fixture;
+ private static String fixtureGraph;
+ private static String queryTemplate;
+ private static String adminToken;
+ private static String grantedToken;
+ private static String ungrantedToken;
+ private static String wildcardToken;
+ private static String grantedAndDeniedToken;
+ private static String grantedBotToken;
+ private static String ungrantedBotToken;
+
+ @BeforeAll
+ static void setUp() throws Exception {
+ assumeTrue(RdfTestUtils.isRdfEnabled(), "Requires the RDF integration-test profile");
+ initAuth();
+ access = new RdfAccessFixtures(FIXTURE_PREFIX);
+ access.markProjectionReady();
+ createCallers();
+ fixtureGraph = "urn:rdf-mcp-it:" + access.suffix() + ":graph";
+ fixture =
+ ColumnLineageFixture.build(
+ BASE_URI, "kgit" + access.suffix() + "_snowflake_prod.analytics.public.");
+ loadFixture();
+ queryTemplate = readPublishedTemplate();
+ }
+
+ @AfterAll
+ static void tearDown() throws Exception {
+ if (fixtureGraph != null) {
+ adminUpdate("DELETE WHERE { GRAPH <" + fixtureGraph + "> { ?s ?p ?o } }");
+ }
+ if (access != null) {
+ access.close();
+ }
+ }
+
+ @Test
+ void anAdministratorMayCallEveryKnowledgeGraphTool() throws Exception {
+ assertSparqlToolsAllowed(adminToken);
+ assertThat(call(adminToken, "shacl_validate", shaclScope()).error()).isFalse();
+ }
+
+ @Test
+ void aUserWithTheExplicitGrantMayCallTheGraphReadingTools() throws Exception {
+ assertSparqlToolsAllowed(grantedToken);
+ }
+
+ @Test
+ void aUserWithoutTheGrantIsForbiddenFromGraphReadingTools() throws Exception {
+ access.withoutDefaultSparqlGrant(() -> assertSparqlToolsForbidden(ungrantedToken));
+ }
+
+ @Test
+ void aWildcardAllPolicyDoesNotGrantTheTools() throws Exception {
+ access.withoutDefaultSparqlGrant(() -> assertSparqlToolsForbidden(wildcardToken));
+ }
+
+ @Test
+ void aGrantPlusADenyIsForbidden() throws Exception {
+ assertSparqlToolsForbidden(grantedAndDeniedToken);
+ }
+
+ @Test
+ void aBotWithTheGrantOnItsOwnPoliciesIsAllowed() throws Exception {
+ assertSparqlToolsAllowed(grantedBotToken);
+ }
+
+ @Test
+ void aBotWithoutTheGrantIsForbidden() throws Exception {
+ access.withoutDefaultSparqlGrant(() -> assertSparqlToolsForbidden(ungrantedBotToken));
+ }
+
+ @Test
+ void validationStaysAdminOnlyEvenForAGrantedUser() throws Exception {
+ final ToolOutcome outcome = call(grantedToken, "shacl_validate", shaclScope());
+
+ assertThat(outcome.error()).isTrue();
+ assertThat(outcome.statusCode()).isEqualTo(403);
+ }
+
+ @Test
+ void theWholeOntologyNeedsNoGrant() throws Exception {
+ access.withoutDefaultSparqlGrant(
+ () -> {
+ final ToolOutcome outcome =
+ call(ungrantedToken, "ontology_describe", Map.of("maxBytes", 2048));
+
+ assertThat(outcome.error()).isFalse();
+ assertThat(outcome.payload().path("scope").asText()).isEqualTo("full-ontology");
+ });
+ }
+
+ @Test
+ void aGrantedUserPagesThroughEveryDownstreamColumnOfOneColumn() throws Exception {
+ final Set expected = fixture.downstreamOf(fixture.sourceColumn());
+
+ final Paged paged = page(grantedToken, fixture.sourceColumn(), DOWNSTREAM_PATH, "", PAGE_SIZE);
+
+ assertThat(expected.size()).as("fixture must need several pages").isGreaterThan(2 * PAGE_SIZE);
+ assertThat(paged.columns()).hasSize(expected.size());
+ assertThat(new HashSet<>(paged.columns())).isEqualTo(expected);
+ paged.logTimings("downstream", fixture.columnLineageNodes());
+ }
+
+ @Test
+ void aGrantedUserPagesThroughEveryUpstreamColumn() throws Exception {
+ final String start = fixture.columnFqn("h5", "g001");
+
+ final Paged paged = page(grantedToken, start, UPSTREAM_PATH, "", 2);
+
+ assertThat(new HashSet<>(paged.columns())).isEqualTo(fixture.upstreamOf(start));
+ assertThat(paged.columns()).doesNotHaveDuplicates();
+ }
+
+ @Test
+ void theAssetTypeFilterDropsTheDashboardDataModelHop() throws Exception {
+ final Set tableColumns =
+ fixture.onlyTableColumns(fixture.downstreamOf(fixture.sourceColumn()));
+
+ final Paged paged =
+ page(grantedToken, fixture.sourceColumn(), DOWNSTREAM_PATH, "?asset a om:Table", PAGE_SIZE);
+
+ assertThat(new HashSet<>(paged.columns())).isEqualTo(tableColumns);
+ assertThat(paged.columns()).doesNotContain(fixture.columnFqn("dm", "metric"));
+ assertThat(paged.columns()).contains(fixture.nestedColumn());
+ }
+
+ @Test
+ void anOversizedPageIsFlaggedTruncatedAndALowerLimitRecovers() throws Exception {
+ final ToolOutcome oversized =
+ call(
+ grantedToken,
+ "sparql_query",
+ Map.of("query", pageQuery(fixture.sourceColumn(), DOWNSTREAM_PATH, "", 3_000, 0)));
+
+ assertThat(oversized.error()).isFalse();
+ assertThat(oversized.payload().path("truncated").asBoolean()).isTrue();
+ assertThat(oversized.payload().path("completeness").path("status").asText())
+ .isEqualTo("COMPLETE");
+
+ final ToolOutcome smaller =
+ call(
+ grantedToken,
+ "sparql_query",
+ Map.of("query", pageQuery(fixture.sourceColumn(), DOWNSTREAM_PATH, "", 100, 0)));
+ assertThat(smaller.payload().path("truncated").asBoolean()).isFalse();
+ }
+
+ @Test
+ void aServerCappedSelectReportsTruncatedCompleteness() throws Exception {
+ final ToolOutcome outcome =
+ call(
+ grantedToken,
+ "sparql_query",
+ Map.of(
+ "query",
+ "SELECT ?c WHERE { ?c <" + BASE_URI + "ontology/fullyQualifiedName> ?fqn }"));
+
+ assertThat(outcome.error()).isFalse();
+ assertThat(outcome.payload().path("completeness").path("status").asText())
+ .isEqualTo("TRUNCATED");
+ assertThat(outcome.payload().path("completeness").path("reason").asText())
+ .isEqualTo("SERVER_ROW_LIMIT");
+ }
+
+ @Test
+ void queryFormsOutsideTheNonAdminProfileAreRejectedWithTheirCode() throws Exception {
+ final Map expectedFragmentByQuery =
+ Map.of(
+ "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o } LIMIT 1", "QUERY_FORM_NOT_ALLOWED",
+ "SELECT * WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 1", "GRAPH_SELECTION_NOT_ALLOWED",
+ "SELECT * WHERE { SERVICE { ?s ?p ?o } }",
+ "FEDERATION_NOT_ALLOWED");
+
+ for (final Map.Entry rejected : expectedFragmentByQuery.entrySet()) {
+ final ToolOutcome outcome =
+ call(grantedToken, "sparql_query", Map.of("query", rejected.getKey()));
+
+ assertThat(outcome.error()).as(rejected.getKey()).isTrue();
+ assertThat(outcome.payload().path("error").asText()).contains(rejected.getValue());
+ }
+ }
+
+ @Test
+ void inferenceIsRefusedForANonAdministrator() throws Exception {
+ final ToolOutcome outcome =
+ call(
+ grantedToken,
+ "sparql_query",
+ Map.of("query", "SELECT ?s WHERE { ?s ?p ?o } LIMIT 1", "inferenceLevel", "rdfs"));
+
+ assertThat(outcome.error()).isTrue();
+ assertThat(outcome.statusCode()).isEqualTo(400);
+ assertThat(outcome.payload().path("error").asText())
+ .contains("'inferenceLevel' must be 'none'");
+ }
+
+ @Test
+ void aNonAdministratorIsToldToRetryWhileTheProjectionRebuilds() throws Exception {
+ access.recordProjectionRun(AppRunRecord.Status.RUNNING);
+ try {
+ for (final ToolCall gated : sparqlToolCalls()) {
+ final ToolOutcome outcome = call(grantedToken, gated.tool(), gated.arguments());
+
+ assertThat(outcome.statusCode()).as(gated.tool()).isEqualTo(TOO_MANY_REQUESTS_STATUS);
+ assertThat(outcome.payload().path("error").asText())
+ .as(gated.tool())
+ .contains("rebuilding; retry later")
+ .contains("RdfIndexApp");
+ }
+ assertAdministratorAndTheOntologyStillAnswer();
+ } finally {
+ access.markProjectionReady();
+ }
+ }
+
+ @Test
+ void aNonAdministratorIsNotToldToRetryWhenTheProjectionIsDegraded() throws Exception {
+ access.recordProjectionRun(AppRunRecord.Status.FAILED);
+ try {
+ for (final ToolCall gated : sparqlToolCalls()) {
+ final ToolOutcome outcome = call(grantedToken, gated.tool(), gated.arguments());
+
+ assertThat(outcome.statusCode()).as(gated.tool()).isEqualTo(BAD_REQUEST_STATUS);
+ assertThat(outcome.payload().path("error").asText())
+ .as(gated.tool())
+ .contains("degraded")
+ .contains("full RdfIndexApp rebuild")
+ .doesNotContainIgnoringCase("retry");
+ }
+ assertAdministratorAndTheOntologyStillAnswer();
+ } finally {
+ access.markProjectionReady();
+ }
+ }
+
+ @Test
+ void aQueryOverMcpIsAuditedWithTheMcpBotAsServiceActorAndTheUserAsEffectiveUser()
+ throws Exception {
+ final Logger auditLogger = (Logger) LoggerFactory.getLogger(AgentSparqlAudit.class);
+ final ListAppender events = new ListAppender<>();
+ events.start();
+ auditLogger.setLevel(Level.INFO);
+ auditLogger.addAppender(events);
+ try {
+ final ToolOutcome outcome =
+ call(
+ grantedToken,
+ "sparql_query",
+ Map.of("query", "SELECT ?s WHERE { ?s ?p ?o } LIMIT 1"));
+
+ assertThat(outcome.error()).isFalse();
+ final String user =
+ (FIXTURE_PREFIX + GRANTED_USER + access.suffix()).toLowerCase(Locale.ROOT);
+ assertThat(
+ events.list.stream()
+ .map(ILoggingEvent::getFormattedMessage)
+ .filter(message -> message.contains("effectiveUser=" + user)))
+ .singleElement()
+ .asString()
+ .contains("serviceActor=" + mcpBotName())
+ .contains("outcome=SUCCESS");
+ } finally {
+ auditLogger.detachAppender(events);
+ auditLogger.setLevel(null);
+ events.stop();
+ }
+ }
+
+ private static void assertAdministratorAndTheOntologyStillAnswer() throws Exception {
+ assertThat(
+ call(
+ adminToken,
+ "sparql_query",
+ Map.of("query", "SELECT ?s WHERE { ?s ?p ?o } LIMIT 1"))
+ .error())
+ .isFalse();
+ assertThat(call(adminToken, "find_by_tag", Map.of("tagFqn", "Tier.Tier1", "limit", 1)).error())
+ .isFalse();
+ assertThat(call(grantedToken, "ontology_describe", Map.of("maxBytes", 2048)).error()).isFalse();
+ }
+
+ /** Resolved the way {@code McpServer} does it, so the test names the bot the server really uses. */
+ private static String mcpBotName() {
+ final AbstractNativeApplication app =
+ ApplicationContext.getInstance().getAppIfExists(McpAppConstants.MCP_APP_NAME);
+ return app != null && app.getApp().getBot() != null
+ ? app.getApp().getBot().getName()
+ : McpAppConstants.MCP_APP_NAME + "Bot";
+ }
+
+ @Test
+ void anAdministratorKeepsConstructAndGraphQueries() throws Exception {
+ final ToolOutcome construct =
+ call(
+ adminToken,
+ "sparql_query",
+ Map.of(
+ "query", "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o } LIMIT 1", "format", "turtle"));
+ final ToolOutcome graph =
+ call(
+ adminToken,
+ "sparql_query",
+ Map.of(
+ "query", "SELECT * WHERE { GRAPH <" + fixtureGraph + "> { ?s ?p ?o } } LIMIT 1"));
+
+ assertThat(construct.error()).isFalse();
+ assertThat(construct.payload().path("queryType").asText()).isEqualTo("CONSTRUCT");
+ assertThat(graph.error()).isFalse();
+ assertThat(graph.payload().path("completeness").isMissingNode()).isTrue();
+ }
+
+ /**
+ * A real lineage edge with column mappings, projected by a real reindex, is found by the same
+ * published query. Last, because the reindex clears the shared dataset and the synthetic scale
+ * graph with it.
+ */
+ @Test
+ @Order(Integer.MAX_VALUE)
+ void columnLineageProjectedByARealReindexIsFoundByThePublishedQuery(TestNamespace namespace)
+ throws Exception {
+ assumeFalse(
+ TestSuiteBootstrap.isK8sEnabled(), "App trigger is not compatible with K8s pipelines");
+ final OpenMetadataClient client = SdkClients.adminClient();
+ final DatabaseService service = DatabaseServiceTestFactory.createPostgres(namespace);
+ final DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(namespace, service);
+ final Table source = createTable(namespace, schema, "kgSource");
+ final Table target = createTable(namespace, schema, "kgTarget", nestedColumn());
+ final String sourceColumn = source.getColumns().getFirst().getFullyQualifiedName();
+ final String targetColumn = target.getColumns().getFirst().getFullyQualifiedName();
+ addColumnLineage(client, source, target, sourceColumn, targetColumn);
+
+ triggerReindexAndWait(client.getHttpClient());
+ access.markProjectionReady();
+
+ final Paged paged = page(grantedToken, sourceColumn, DOWNSTREAM_PATH, "", PAGE_SIZE);
+ assertThat(paged.columns()).containsExactly(targetColumn);
+ assertThat(paged.assets()).containsExactly(BASE_URI + "entity/table/" + target.getId());
+ assertThat(childColumnsProjectedFor(target.getFullyQualifiedName() + ".payload"))
+ .containsExactly(target.getFullyQualifiedName() + ".payload.kind");
+ }
+
+ /** Reads the child columns the live projection holds for one parent column, through MCP. */
+ private static List childColumnsProjectedFor(final String parentColumnFqn)
+ throws Exception {
+ final String query =
+ "PREFIX om: <"
+ + BASE_URI
+ + "ontology/> SELECT ?childFqn WHERE { "
+ + "?parent om:fullyQualifiedName \""
+ + parentColumnFqn
+ + "\" . "
+ + "?parent om:hasChildColumn ?child . ?child om:fullyQualifiedName ?childFqn } ORDER BY ?childFqn";
+ final ToolOutcome outcome = call(grantedToken, "sparql_query", Map.of("query", query));
+ assertThat(outcome.error()).as(outcome.payload().toString()).isFalse();
+ final List children = new ArrayList<>();
+ OBJECT_MAPPER
+ .readTree(outcome.payload().path("body").asText())
+ .path("results")
+ .path("bindings")
+ .forEach(row -> children.add(row.path("childFqn").path("value").asText()));
+ return children;
+ }
+
+ private static void assertSparqlToolsAllowed(final String token) throws Exception {
+ for (final ToolCall toolCall : sparqlToolCalls()) {
+ final ToolOutcome outcome = call(token, toolCall.tool(), toolCall.arguments());
+
+ assertThat(outcome.error()).as("%s: %s", toolCall.tool(), outcome.payload()).isFalse();
+ }
+ }
+
+ private static void assertSparqlToolsForbidden(final String token) throws Exception {
+ for (final ToolCall toolCall : sparqlToolCalls()) {
+ final ToolOutcome outcome = call(token, toolCall.tool(), toolCall.arguments());
+
+ assertThat(outcome.error()).as("%s: %s", toolCall.tool(), outcome.payload()).isTrue();
+ assertThat(outcome.statusCode())
+ .as("%s: %s", toolCall.tool(), outcome.payload())
+ .isEqualTo(Integer.parseInt(FORBIDDEN_STATUS));
+ }
+ }
+
+ private static List sparqlToolCalls() {
+ final String assetIri = fixture.assetIriOf(fixture.sourceColumn());
+ final String assetId = assetIri.substring(assetIri.lastIndexOf('/') + 1);
+ return List.of(
+ new ToolCall("sparql_query", Map.of("query", "SELECT ?s WHERE { ?s ?p ?o } LIMIT 1")),
+ new ToolCall(
+ "entity_neighborhood",
+ Map.of("entityId", assetId, "entityType", "table", "depth", 1, "limit", 5)),
+ new ToolCall("find_by_tag", Map.of("tagFqn", "Tier.Tier1", "limit", 1)),
+ new ToolCall("ontology_describe", Map.of("resource", assetIri, "maxBytes", 2048)));
+ }
+
+ private static Map shaclScope() {
+ final String assetIri = fixture.assetIriOf(fixture.sourceColumn());
+ return Map.of("entityUri", assetIri, "maxBytes", 2048);
+ }
+
+ private static ToolOutcome call(
+ final String bearerToken, final String tool, final Map arguments)
+ throws Exception {
+ final JsonNode response =
+ MCP_CLIENT.executeMcpRequest(
+ McpTestUtils.createToolCallRequest(tool, arguments), bearerToken);
+ final JsonNode result = response.path("result");
+ return new ToolOutcome(result.path("isError").asBoolean(false), payloadOf(result));
+ }
+
+ private static JsonNode payloadOf(final JsonNode result) throws Exception {
+ final String text = result.path("content").path(0).path("text").asText("");
+ return text.isBlank() ? result.path("structuredContent") : OBJECT_MAPPER.readTree(text);
+ }
+
+ private static Paged page(
+ final String bearerToken,
+ final String startColumn,
+ final String path,
+ final String filter,
+ final int pageSize)
+ throws Exception {
+ final Paged paged = new Paged();
+ int offset = 0;
+ int rows;
+ do {
+ final long started = System.nanoTime();
+ final ToolOutcome outcome =
+ call(
+ bearerToken,
+ "sparql_query",
+ Map.of("query", pageQuery(startColumn, path, filter, pageSize, offset)));
+ final long millis = (System.nanoTime() - started) / 1_000_000;
+ rows = paged.add(outcome, millis);
+ offset += pageSize;
+ } while (rows == pageSize);
+ return paged;
+ }
+
+ /** The published template with the start column, direction, filter and page substituted in. */
+ private static String pageQuery(
+ final String startColumn,
+ final String path,
+ final String filter,
+ final int limit,
+ final int offset) {
+ final String filtered =
+ filter.isEmpty()
+ ? queryTemplate
+ : queryTemplate.replace(" } ORDER BY", " . " + filter + " } ORDER BY");
+ return "PREFIX om: <"
+ + BASE_URI
+ + "ontology/> "
+ + filtered
+ .replace(TEMPLATE_START_COLUMN, startColumn)
+ .replace(DOWNSTREAM_PATH, path)
+ .replace("LIMIT 250 OFFSET 0", "LIMIT " + limit + " OFFSET " + offset);
+ }
+
+ /** Reads the description a client sees, so the test exercises exactly what it advertises. */
+ private static String readPublishedTemplate() throws Exception {
+ final JsonNode list =
+ MCP_CLIENT.executeMcpRequest(
+ McpTestUtils.createJsonRpcRequest("tools/list", Map.of()), grantedToken);
+ for (final JsonNode tool : list.path("result").path("tools")) {
+ if ("sparql_query".equals(tool.path("name").asText())) {
+ final Matcher matcher = COLUMN_LINEAGE_TEMPLATE.matcher(tool.path("description").asText());
+ assertTrue(matcher.find(), "sparql_query must publish the column lineage template");
+ return matcher.group();
+ }
+ }
+ throw new AssertionError("sparql_query is not offered to a granted non-admin");
+ }
+
+ private static void createCallers() {
+ final var grant = access.allowRole(MetadataOperation.EXECUTE_SPARQL_QUERY, Entity.RDF);
+ final var wildcard = access.allowRole(MetadataOperation.ALL, "All");
+ final var deny = access.denyRole(MetadataOperation.EXECUTE_SPARQL_QUERY, Entity.RDF);
+ adminToken = authToken;
+ grantedToken = "Bearer " + access.userToken(GRANTED_USER, List.of(grant.getId()));
+ ungrantedToken = "Bearer " + access.userToken("plain", List.of());
+ wildcardToken = "Bearer " + access.userToken("wildcard", List.of(wildcard.getId()));
+ grantedAndDeniedToken =
+ "Bearer " + access.userToken("denied", List.of(grant.getId(), deny.getId()));
+ grantedBotToken = "Bearer " + access.botToken("grantedbot", List.of(grant.getId()));
+ ungrantedBotToken = "Bearer " + access.botToken("plainbot", List.of());
+ }
+
+ /** Batched by size so each update stays under the 100,000-character query ceiling. */
+ private static void loadFixture() throws Exception {
+ final StringWriter ntriples = new StringWriter();
+ RDFDataMgr.write(ntriples, fixture.model(), Lang.NTRIPLES);
+ assertFalse(ntriples.toString().contains("_:"), "INSERT DATA cannot carry blank nodes");
+ final StringBuilder batch = new StringBuilder();
+ for (final String triple : ntriples.toString().split("\n")) {
+ if (batch.length() + triple.length() > INSERT_BATCH_CHARS) {
+ insert(batch);
+ }
+ batch.append(triple).append('\n');
+ }
+ insert(batch);
+ }
+
+ private static void insert(final StringBuilder batch) throws Exception {
+ if (!batch.isEmpty()) {
+ adminUpdate("INSERT DATA { GRAPH <" + fixtureGraph + "> { " + batch + "} }");
+ batch.setLength(0);
+ }
+ }
+
+ private static void adminUpdate(final String sparql) {
+ SdkClients.adminClient()
+ .getHttpClient()
+ .execute(HttpMethod.POST, "/v1/rdf/sparql/update", Map.of("query", sparql), Void.class);
+ }
+
+ private static Table createTable(
+ final TestNamespace namespace, final DatabaseSchema schema, final String name) {
+ return createTable(namespace, schema, name, null);
+ }
+
+ private static Table createTable(
+ final TestNamespace namespace,
+ final DatabaseSchema schema,
+ final String name,
+ final Column extraColumn) {
+ final List columns = new ArrayList<>();
+ columns.add(ColumnBuilder.of("id", "BIGINT").primaryKey().notNull().build());
+ if (extraColumn != null) {
+ columns.add(extraColumn);
+ }
+ return Tables.create(
+ new CreateTable()
+ .withName(namespace.prefix(name))
+ .withDatabaseSchema(schema.getFullyQualifiedName())
+ .withDescription("RDF MCP knowledge graph integration fixture")
+ .withColumns(columns));
+ }
+
+ /** A struct column with one child, to see whether a real reindex projects {@code om:hasChildColumn}. */
+ private static Column nestedColumn() {
+ return new Column()
+ .withName("payload")
+ .withDataType(ColumnDataType.STRUCT)
+ .withChildren(List.of(new Column().withName("kind").withDataType(ColumnDataType.STRING)));
+ }
+
+ private static void addColumnLineage(
+ final OpenMetadataClient client,
+ final Table source,
+ final Table target,
+ final String sourceColumn,
+ final String targetColumn) {
+ final ColumnLineage mapping =
+ new ColumnLineage().withFromColumns(List.of(sourceColumn)).withToColumn(targetColumn);
+ final EntitiesEdge edge =
+ new EntitiesEdge()
+ .withFromEntity(source.getEntityReference())
+ .withToEntity(target.getEntityReference())
+ .withLineageDetails(new LineageDetails().withColumnsLineage(List.of(mapping)));
+ assertThat(client.lineage().addLineage(new AddLineage().withEdge(edge))).isNotNull();
+ }
+
+ private static void triggerReindexAndWait(final HttpClient httpClient) {
+ final Long previousStart = latestRunStart(httpClient);
+ final Map config = new HashMap<>();
+ config.put("entities", List.of("all"));
+ config.put("recreateIndex", true);
+ config.put("batchSize", 100);
+ config.put("producerThreads", 2);
+ Awaitility.await("Trigger " + APP_NAME)
+ .atMost(Duration.ofMinutes(2))
+ .pollInterval(Duration.ofSeconds(3))
+ .ignoreExceptionsMatching(
+ error -> error.getMessage() != null && error.getMessage().contains("already running"))
+ .until(
+ () -> {
+ httpClient.execute(
+ HttpMethod.POST, "/v1/apps/trigger/" + APP_NAME, config, Void.class);
+ return true;
+ });
+ Awaitility.await("RDF reindex completion")
+ .atMost(Duration.ofMinutes(10))
+ .pollDelay(Duration.ofSeconds(2))
+ .pollInterval(Duration.ofSeconds(5))
+ .ignoreExceptions()
+ .until(() -> isNewSuccessfulRun(httpClient, previousStart));
+ }
+
+ private static boolean isNewSuccessfulRun(final HttpClient httpClient, final Long previousStart) {
+ final AppRunRecord run =
+ httpClient.execute(HttpMethod.GET, LATEST_RUN_PATH, null, AppRunRecord.class);
+ final boolean isNew = previousStart == null || run.getStartTime() > previousStart;
+ if (isNew && FAILED_RUN_STATUSES.contains(run.getStatus())) {
+ throw new AssertionError("RDF reindex failed: " + run);
+ }
+ return isNew && FINISHED_RUN_STATUSES.contains(run.getStatus());
+ }
+
+ /** The server answers 204, which the client returns as null, when the app has never run. */
+ private static Long latestRunStart(final HttpClient httpClient) {
+ final AppRunRecord latest =
+ httpClient.execute(HttpMethod.GET, LATEST_RUN_PATH, null, AppRunRecord.class);
+ return latest == null ? null : latest.getStartTime();
+ }
+
+ private record ToolCall(String tool, Map arguments) {}
+
+ private record ToolOutcome(boolean error, JsonNode payload) {
+ int statusCode() {
+ return payload.path("statusCode").asInt(0);
+ }
+ }
+
+ /** The rows of every page, with what each page cost, for the timing the docs quote. */
+ private static final class Paged {
+ private final List columns = new ArrayList<>();
+ private final List assets = new ArrayList<>();
+ private final List timings = new ArrayList<>();
+
+ int add(final ToolOutcome outcome, final long millis) throws Exception {
+ assertThat(outcome.error()).as("page %d: %s", timings.size(), outcome.payload()).isFalse();
+ assertThat(outcome.payload().path("truncated").asBoolean())
+ .as(
+ "page %d was cut by the body budget at %d bytes",
+ timings.size(), outcome.payload().path("byteCount").asInt())
+ .isFalse();
+ assertThat(outcome.payload().path("completeness").path("status").asText())
+ .isEqualTo("COMPLETE");
+ assertThat(millis).isLessThan(SparqlQueryLimits.TIMEOUT_MILLIS);
+ final JsonNode bindings =
+ OBJECT_MAPPER
+ .readTree(outcome.payload().path("body").asText())
+ .path("results")
+ .path("bindings");
+ bindings.forEach(
+ row -> {
+ columns.add(row.path("column").path("value").asText());
+ assets.add(row.path("asset").path("value").asText());
+ });
+ timings.add(
+ "%d ms / %d bytes".formatted(millis, outcome.payload().path("byteCount").asInt()));
+ return bindings.size();
+ }
+
+ List columns() {
+ return columns;
+ }
+
+ List assets() {
+ return assets;
+ }
+
+ void logTimings(final String direction, final int lineageNodes) {
+ System.out.printf(
+ "[rdf-mcp-it-timing] %s over %d column-lineage nodes: %d rows in %d pages: %s%n",
+ direction, lineageNodes, columns.size(), timings.size(), timings);
+ }
+ }
+}
diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/RdfAccessFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/RdfAccessFixtures.java
new file mode 100644
index 000000000000..323cf0ba4a54
--- /dev/null
+++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/util/RdfAccessFixtures.java
@@ -0,0 +1,255 @@
+/*
+ * Copyright 2021 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.it.util;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.UUID;
+import org.openmetadata.it.auth.JwtAuthProvider;
+import org.openmetadata.schema.api.CreateBot;
+import org.openmetadata.schema.api.policies.CreatePolicy;
+import org.openmetadata.schema.api.teams.CreateRole;
+import org.openmetadata.schema.api.teams.CreateUser;
+import org.openmetadata.schema.auth.JWTAuthMechanism;
+import org.openmetadata.schema.auth.JWTTokenExpiry;
+import org.openmetadata.schema.entity.Bot;
+import org.openmetadata.schema.entity.app.AppExtension;
+import org.openmetadata.schema.entity.app.AppRunRecord;
+import org.openmetadata.schema.entity.policies.Policy;
+import org.openmetadata.schema.entity.policies.accessControl.Rule;
+import org.openmetadata.schema.entity.teams.AuthenticationMechanism;
+import org.openmetadata.schema.entity.teams.Role;
+import org.openmetadata.schema.entity.teams.User;
+import org.openmetadata.schema.type.MetadataOperation;
+import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.sdk.client.OpenMetadataClient;
+import org.openmetadata.sdk.network.HttpMethod;
+import org.openmetadata.service.Entity;
+import org.openmetadata.service.rdf.RdfProjectionHealth;
+
+/**
+ * Users, bots, roles and the readiness marker an RDF integration test needs, each removed by {@link
+ * #close()} in reverse order of creation.
+ *
+ * The Data Consumer policy may ship an {@code ExecuteSparqlQuery} rule, which makes every user
+ * "granted". {@link #withoutDefaultSparqlGrant} takes it out for the duration of a body, and does
+ * nothing when the rule is not seeded, so a test written against it passes either way.
+ */
+public final class RdfAccessFixtures implements AutoCloseable {
+ private static final String STATUS = AppExtension.ExtensionType.STATUS.toString();
+ public static final String RDF_INDEX_APP = "RdfIndexApp";
+ private static final String TEST_EMAIL_DOMAIN = "@test.openmetadata.org";
+ private static final String DATA_CONSUMER_POLICY = "DataConsumerPolicy";
+ private static final String DATA_CONSUMER_GRANT_RULE =
+ "DataConsumerPolicy-ExecuteSparqlQuery-Rule";
+ private static final long TOKEN_TTL_SECONDS = 3600;
+
+ private final String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
+ private final String prefix;
+ private final OpenMetadataClient admin = SdkClients.adminClient();
+ private final Deque cleanup = new ArrayDeque<>();
+ private final List principals = new ArrayList<>();
+ private long lastRunTimestamp;
+
+ public RdfAccessFixtures(final String prefix) {
+ this.prefix = prefix;
+ }
+
+ /** Unique per instance, for names and IRIs that must not collide across runs. */
+ public String suffix() {
+ return suffix;
+ }
+
+ private static String emailOf(final String userName) {
+ return userName + TEST_EMAIL_DOMAIN;
+ }
+
+ public Role allowRole(final MetadataOperation operation, final String resource) {
+ return role("allow" + operation.value(), operation, resource, Rule.Effect.ALLOW);
+ }
+
+ public Role denyRole(final MetadataOperation operation, final String resource) {
+ return role("deny" + operation.value(), operation, resource, Rule.Effect.DENY);
+ }
+
+ public String userToken(final String name, final List roleIds) {
+ final String userName = (prefix + name + suffix).toLowerCase(Locale.ROOT);
+ final User user =
+ admin
+ .users()
+ .create(
+ new CreateUser()
+ .withName(userName)
+ .withEmail(emailOf(userName))
+ .withRoles(roleIds));
+ cleanup.push(() -> admin.users().delete(user.getId()));
+ principals.add(userName);
+ final String email = emailOf(userName);
+ return JwtAuthProvider.tokenFor(email, email, new String[] {}, TOKEN_TTL_SECONDS);
+ }
+
+ /** A bot authorized on its own policies only; MCP has no impersonation header. */
+ public String botToken(final String name, final List roleIds) {
+ final String botUserName = prefix + name + suffix;
+ final User botUser =
+ admin
+ .users()
+ .create(
+ new CreateUser()
+ .withName(botUserName)
+ .withEmail(botUserName + "@test.com")
+ .withIsBot(true)
+ .withRoles(roleIds)
+ .withAuthenticationMechanism(
+ new AuthenticationMechanism()
+ .withAuthType(AuthenticationMechanism.AuthType.JWT)
+ .withConfig(
+ new JWTAuthMechanism()
+ .withJWTTokenExpiry(JWTTokenExpiry.Unlimited))));
+ cleanup.push(() -> admin.users().delete(botUser.getId()));
+ principals.add(botUser.getName());
+ final Bot bot =
+ admin
+ .bots()
+ .create(new CreateBot().withName(botUserName + "_bot").withBotUser(botUser.getName()));
+ cleanup.push(() -> admin.bots().delete(bot.getId()));
+ return admin.users().generateToken(botUser.getId(), JWTTokenExpiry.Seven).getJWTToken();
+ }
+
+ /**
+ * The projection state resolver reads the latest {@code RdfIndexApp} run, so a fresh success row
+ * makes the shared projection read as ready regardless of what earlier classes left behind.
+ */
+ public void markProjectionReady() {
+ recordProjectionRun(AppRunRecord.Status.SUCCESS);
+ RdfProjectionHealth.markReady();
+ }
+
+ /**
+ * Records an {@code RdfIndexApp} run with the given status, newer than every run this fixture
+ * recorded before, so the resolver reads it as the latest: {@code RUNNING} is a rebuild in
+ * progress, {@code FAILED} a degraded projection, {@code SUCCESS} a ready one.
+ */
+ public void recordProjectionRun(final AppRunRecord.Status status) {
+ final UUID appId = UUID.randomUUID();
+ lastRunTimestamp = Math.max(System.currentTimeMillis(), lastRunTimestamp + 1);
+ final AppRunRecord run =
+ new AppRunRecord()
+ .withAppId(appId)
+ .withAppName(RDF_INDEX_APP)
+ .withStatus(status)
+ .withTimestamp(lastRunTimestamp)
+ .withStartTime(lastRunTimestamp)
+ .withExtension(STATUS);
+ Entity.getCollectionDAO().appExtensionTimeSeriesDao().insert(JsonUtils.pojoToJson(run), STATUS);
+ cleanup.push(
+ () ->
+ Entity.getCollectionDAO().appExtensionTimeSeriesDao().delete(appId.toString(), STATUS));
+ }
+
+ /** The test class must be {@code @Isolated}: the policy is shared and edited while {@code body} runs. */
+ public void withoutDefaultSparqlGrant(final ThrowingRunnable body) throws Exception {
+ final Optional removed = removeDefaultGrant();
+ try {
+ body.run();
+ } finally {
+ removed.ifPresent(this::restoreDefaultGrant);
+ }
+ }
+
+ @Override
+ public void close() {
+ while (!cleanup.isEmpty()) {
+ cleanup.pop().run();
+ }
+ }
+
+ private Role role(
+ final String name,
+ final MetadataOperation operation,
+ final String resource,
+ final Rule.Effect effect) {
+ final Rule rule =
+ new Rule()
+ .withName(prefix + effect.value())
+ .withOperations(List.of(operation))
+ .withResources(List.of(resource))
+ .withEffect(effect);
+ final Policy policy =
+ admin
+ .policies()
+ .create(
+ new CreatePolicy()
+ .withName(prefix + name + "Policy" + suffix)
+ .withRules(List.of(rule)));
+ cleanup.push(() -> admin.policies().delete(policy.getId()));
+ final Role role =
+ admin
+ .roles()
+ .create(
+ new CreateRole()
+ .withName(prefix + name + "Role" + suffix)
+ .withPolicies(List.of(policy.getFullyQualifiedName())));
+ cleanup.push(() -> admin.roles().delete(role.getId()));
+ return role;
+ }
+
+ private Optional removeDefaultGrant() {
+ final Policy policy = admin.policies().getByName(DATA_CONSUMER_POLICY, "rules");
+ final Optional grant =
+ policy.getRules().stream()
+ .filter(rule -> DATA_CONSUMER_GRANT_RULE.equals(rule.getName()))
+ .findFirst();
+ grant.ifPresent(
+ rule -> {
+ policy.getRules().remove(rule);
+ admin.policies().update(policy.getId(), policy);
+ refreshPrincipalPermissions();
+ });
+ return grant;
+ }
+
+ private void restoreDefaultGrant(final Rule grant) {
+ final Policy current = admin.policies().getByName(DATA_CONSUMER_POLICY, "rules");
+ current.getRules().add(grant);
+ admin.policies().update(current.getId(), current);
+ refreshPrincipalPermissions();
+ }
+
+ /**
+ * Reads each created principal's effective permissions straight after a policy edit. A principal
+ * authorized before the edit can keep the removed rule in its per-user policy cache
+ * ({@code SubjectCache}) when its first request after the edit arrives via /mcp; this read forces
+ * a fresh evaluation. A test-side workaround, not a statement about the product; see #34826.
+ */
+ private void refreshPrincipalPermissions() {
+ for (final String principal : principals) {
+ admin
+ .getHttpClient()
+ .executeForString(HttpMethod.GET, "/v1/permissions/rdf?user=" + principal, null);
+ admin
+ .getHttpClient()
+ .executeForString(HttpMethod.GET, "/v1/permissions/debug/user/" + principal, null);
+ }
+ }
+
+ @FunctionalInterface
+ public interface ThrowingRunnable {
+ void run() throws Exception;
+ }
+}
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/AgentSparqlToolErrors.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/AgentSparqlToolErrors.java
new file mode 100644
index 000000000000..9f08e52df718
--- /dev/null
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/AgentSparqlToolErrors.java
@@ -0,0 +1,70 @@
+/*
+ * 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 org.openmetadata.schema.api.rdf.RdfProjectionState;
+import org.openmetadata.service.rdf.agent.AgentSparqlException;
+import org.openmetadata.service.security.AuthorizationException;
+
+/**
+ * Maps the stable agent-profile error codes onto the exception kinds {@code DefaultToolContext}
+ * already classifies by name, keeping the code in the message so a client can act on it.
+ */
+final class AgentSparqlToolErrors {
+
+ private AgentSparqlToolErrors() {}
+
+ private static final String ADMIN_RUNS_REBUILD = "an administrator needs to run RdfIndexApp";
+
+ static RuntimeException toToolException(final AgentSparqlException failure) {
+ final String message = "%s: %s".formatted(failure.getCode().value(), failure.getMessage());
+ return switch (failure.getCode()) {
+ case QUERY_INVALID,
+ QUERY_FORM_NOT_ALLOWED,
+ GRAPH_SELECTION_NOT_ALLOWED,
+ QUERY_LIMIT_EXCEEDED,
+ RESULT_OUTPUT_LIMIT_EXCEEDED -> new IllegalArgumentException(message, failure);
+ // A blocked SERVICE is a 403 on the REST endpoints and, for administrators, on this tool.
+ case FEDERATION_NOT_ALLOWED -> new AuthorizationException(message);
+ case EXECUTION_CAPACITY_EXHAUSTED, RDF_REPOSITORY_UNAVAILABLE -> new RdfRetryLaterException(
+ message + ". Retry shortly.", failure);
+ case PROJECTION_NOT_READY -> projectionNotReady(failure);
+ case EXECUTION_TIMEOUT -> new RdfQueryTimeoutException(message, failure);
+ default -> new IllegalStateException(message, failure);
+ };
+ }
+
+ /**
+ * A rebuild in progress, or no run recorded yet, finishes on its own and is worth retrying. A
+ * degraded projection does not: it stays that way until an administrator runs a full rebuild,
+ * so telling the client to retry would only make it loop.
+ */
+ private static RuntimeException projectionNotReady(final AgentSparqlException failure) {
+ final RdfProjectionState state = failure.getProjectionState();
+ if (state == RdfProjectionState.DEGRADED) {
+ return new RdfProjectionDegradedException(
+ "PROJECTION_NOT_READY: RDF projection is degraded; an administrator must run a full"
+ + " RdfIndexApp rebuild before graph queries can be answered.",
+ failure);
+ }
+ final String situation =
+ state == null
+ ? "RDF projection state could not be determined"
+ : "RDF projection is rebuilding";
+ return new RdfRetryLaterException(
+ "PROJECTION_NOT_READY: %s; retry later. If it persists, %s."
+ .formatted(situation, ADMIN_RUNS_REBUILD),
+ failure);
+ }
+}
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java
index 925ef55cdf52..1a6f74bf43c0 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/DefaultToolContext.java
@@ -337,7 +337,12 @@ private record ExceptionMeta(String name, String message) {}
private static final List CATEGORY_MATCHERS =
List.of(
new CategoryMatcher(
- meta -> meta.name().contains("RateLimit") || meta.message().contains("rate limit"),
+ meta ->
+ meta.name().contains("RateLimit")
+ // A refused or deferred graph read the caller may repeat shortly.
+ || meta.name().contains("RdfRetryLater")
+ || meta.name().contains("QueryCapacity")
+ || meta.message().contains("rate limit"),
McpToolCallUsage.ErrorCategory.RATE_LIMIT,
STATUS_TOO_MANY_REQUESTS),
new CategoryMatcher(
@@ -352,12 +357,15 @@ private record ExceptionMeta(String name, String message) {}
|| meta.message().contains("permission denied"),
McpToolCallUsage.ErrorCategory.AUTH,
STATUS_FORBIDDEN),
- // A disabled RDF triplestore is a deployment state, not an outage. Left unmatched it
- // fell through to 500, and summarizeFailure then told the caller the backend was broken
- // and that a narrower request might help - both wrong. Matched by name so the message
- // text stays free to change.
+ // A disabled RDF triplestore, or a degraded projection that only a full rebuild clears,
+ // is a deployment state, not an outage. Left unmatched it fell through to 500, and
+ // summarizeFailure then told the caller the backend was broken and that a narrower
+ // request might help - both wrong. Matched by name so the message text stays free to
+ // change.
new CategoryMatcher(
- meta -> meta.name().contains("RdfNotEnabled"),
+ meta ->
+ meta.name().contains("RdfNotEnabled")
+ || meta.name().contains("RdfProjectionDegraded"),
McpToolCallUsage.ErrorCategory.VALIDATION,
STATUS_BAD_REQUEST),
// Validation by class name runs before the NotFound message heuristic below, so a
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/EntityNeighborhoodTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/EntityNeighborhoodTool.java
index f95dbf28b647..ecfb9883d16b 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/EntityNeighborhoodTool.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/EntityNeighborhoodTool.java
@@ -24,6 +24,7 @@
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.openmetadata.mcp.util.ResponseBudget;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
@@ -50,6 +51,12 @@ public EntityNeighborhoodTool() {
super(repositorySupplier);
}
+ EntityNeighborhoodTool(
+ Supplier repositorySupplier,
+ Supplier projectionStateSupplier) {
+ super(repositorySupplier, projectionStateSupplier);
+ }
+
/** A single directed edge to a neighbor; {@code neighborLabel} is omitted when absent. */
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Edge(String direction, String predicate, String neighbor, String neighborLabel) {}
@@ -82,6 +89,7 @@ protected Neighborhood executeAuthorized(
int depth = clamp(parameters.integer("depth", DEFAULT_DEPTH), MIN_DEPTH, MAX_DEPTH);
int limit = clamp(parameters.integer("limit", DEFAULT_LIMIT), MIN_LIMIT, MAX_LIMIT);
RdfRepository repository = repository();
+ requireReadyProjectionForNonAdmin(securityContext);
return queryNeighborhood(
securityContext, repository, entity.uri(repository.getBaseUri()), depth, limit);
@@ -94,21 +102,30 @@ private Neighborhood queryNeighborhood(
int depth,
int limit) {
// guardedRead sits outside the wrapping below: a capacity or timeout rejection carries its own
- // 429/503 classification and must not be flattened into a generic "query failed".
- String triples =
- guardedRead(securityContext, () -> runConstruct(repository, entityUri, depth, limit));
- RdfBody.Bounded bounded = RdfBody.bound(triples, RdfBody.maxBytes());
- List edges = fetchEdges(repository, entityUri, limit);
+ // 429/503 classification and must not be flattened into a generic "query failed". Both reads
+ // share one admission slot so a busy guard cannot reject the summary after the CONSTRUCT ran.
+ GraphRead read =
+ guardedRead(securityContext, () -> readGraph(repository, entityUri, depth, limit));
+ RdfBody.Bounded bounded = RdfBody.bound(read.triples(), RdfBody.maxBytes());
return new Neighborhood(
entityUri,
depth,
limit,
bounded.value(),
- fitEdges(edges, bounded.value().length()),
+ fitEdges(read.edges(), bounded.value().length()),
bounded.truncated(),
bounded.byteCount());
}
+ private record GraphRead(String triples, List edges) {}
+
+ private static GraphRead readGraph(
+ RdfRepository repository, String entityUri, int depth, int limit) {
+ return new GraphRead(
+ runConstruct(repository, entityUri, depth, limit),
+ fetchEdges(repository, entityUri, limit));
+ }
+
private static String runConstruct(
RdfRepository repository, String entityUri, int depth, int limit) {
try {
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindByTagTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindByTagTool.java
index e8d3ede54675..6879b08dbbc0 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindByTagTool.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/FindByTagTool.java
@@ -22,6 +22,7 @@
import java.util.Optional;
import java.util.function.Supplier;
import org.apache.jena.query.ParameterizedSparqlString;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.RdfUtils;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
@@ -43,6 +44,12 @@ public FindByTagTool() {
super(repositorySupplier);
}
+ FindByTagTool(
+ Supplier repositorySupplier,
+ Supplier projectionStateSupplier) {
+ super(repositorySupplier, projectionStateSupplier);
+ }
+
@JsonInclude(JsonInclude.Include.NON_NULL)
public record EntityMatch(
String entity, String entityType, String fullyQualifiedName, String label) {}
@@ -75,10 +82,13 @@ protected Result executeAuthorized(
String entityType = validatedEntityType(parameters.optionalString("entityType"));
int limit = clamp(parameters.integer("limit", DEFAULT_LIMIT), 1, MAX_LIMIT);
int offset = Math.max(parameters.integer("offset", 0), 0);
+ RdfRepository repository = repository();
+ requireReadyProjectionForNonAdmin(securityContext);
+ String sparql = buildSparql(tagFqn, entityType, limit, offset);
String json =
- repository()
- .executeSparqlQuery(
- buildSparql(tagFqn, entityType, limit, offset), "application/sparql-results+json");
+ guardedRead(
+ securityContext,
+ () -> repository.executeSparqlQuery(sparql, "application/sparql-results+json"));
List matches = parseRows(json);
return Result.of(tagFqn, entityType, limit, offset, matches);
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/OntologyDescribeTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/OntologyDescribeTool.java
index 3526ea3d3962..7cacbfd6d275 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/OntologyDescribeTool.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/OntologyDescribeTool.java
@@ -18,14 +18,17 @@
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.service.rdf.OntologyDocument;
import org.openmetadata.service.rdf.RdfIriValidator;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.RdfSerializationFormat;
+import org.openmetadata.service.security.Authorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
/** Returns the canonical ontology or a focused description of one ontology resource. */
public class OntologyDescribeTool extends RdfMcpTool {
+ private static final String RESOURCE_PARAMETER = "resource";
public OntologyDescribeTool() {
super();
@@ -35,6 +38,12 @@ public OntologyDescribeTool() {
super(repositorySupplier);
}
+ OntologyDescribeTool(
+ Supplier repositorySupplier,
+ Supplier projectionStateSupplier) {
+ super(repositorySupplier, projectionStateSupplier);
+ }
+
/**
* {@code truncated} / {@code byteCount} mirror {@code SparqlQueryTool.Result}. Truncating the body
* here preserves result metadata when the full ontology exceeds the dispatch cap. Prefer
@@ -54,12 +63,27 @@ public record Result(
}
}
+ /**
+ * The bundled ontology is the same static file the unauthenticated {@code GET /v1/rdf/ontology}
+ * serves, so it needs no permission. A {@code resource} DESCRIBE reads instance data and does.
+ */
+ @Override
+ protected void authorize(
+ final Authorizer authorizer,
+ final CatalogSecurityContext securityContext,
+ final Map params) {
+ if (!McpToolParameters.isBlank(
+ McpToolParameters.from(params).optionalString(RESOURCE_PARAMETER))) {
+ super.authorize(authorizer, securityContext, params);
+ }
+ }
+
@Override
protected Result executeAuthorized(
final CatalogSecurityContext securityContext, final Map params)
throws IOException {
McpToolParameters parameters = McpToolParameters.from(params);
- String resource = parameters.optionalString("resource");
+ String resource = parameters.optionalString(RESOURCE_PARAMETER);
RdfSerializationFormat format =
RdfSerializationFormat.parse(parameters.optionalString("format"));
@@ -94,6 +118,7 @@ private Result describe(
RdfSerializationFormat format,
int maxBytes) {
RdfRepository repository = repository();
+ requireReadyProjectionForNonAdmin(securityContext);
// The guard call stays outside any catch: QueryCapacityException and QueryTimeoutException
// carry their own 429/503 classification, and folding them into an IllegalStateException here
// would report a busy or slow triplestore as an opaque server error.
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfMcpTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfMcpTool.java
index e91095613361..9f1913a832c3 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfMcpTool.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfMcpTool.java
@@ -17,22 +17,39 @@
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
+import org.openmetadata.schema.type.MetadataOperation;
+import org.openmetadata.service.Entity;
import org.openmetadata.service.limits.Limits;
+import org.openmetadata.service.rdf.RdfProjectionStateResolver;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
+import org.openmetadata.service.rdf.agent.AgentSparqlException;
+import org.openmetadata.service.rdf.agent.AgentSparqlService;
+import org.openmetadata.service.resources.rdf.RdfQueryResourceContext;
import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
+import org.openmetadata.service.security.policyevaluator.OperationContext;
abstract class RdfMcpTool implements TypedMcpTool {
private final Supplier repositorySupplier;
+ protected final Supplier projectionStateSupplier;
protected RdfMcpTool() {
this(RdfRepository::getInstanceOrNull);
}
protected RdfMcpTool(Supplier repositorySupplier) {
+ this(repositorySupplier, RdfProjectionStateResolver::resolveConfigured);
+ }
+
+ protected RdfMcpTool(
+ Supplier repositorySupplier,
+ Supplier projectionStateSupplier) {
this.repositorySupplier = Objects.requireNonNull(repositorySupplier);
+ this.projectionStateSupplier = Objects.requireNonNull(projectionStateSupplier);
}
protected final RdfRepository repository() {
@@ -43,16 +60,57 @@ protected final RdfRepository repository() {
return repository;
}
+ /**
+ * Non-admin reads wait for a {@code READY} projection, the rule {@code sparql_query} gets through
+ * {@link AgentSparqlService}, so a half-rebuilt graph is never presented as the answer.
+ * Administrators read the graph as it is, as they do through {@code sparql_query}. Call it after
+ * {@link #repository()}, so a deployment without RDF is reported first.
+ */
+ protected final void requireReadyProjectionForNonAdmin(
+ final CatalogSecurityContext securityContext) {
+ if (!isAdministrator(securityContext)) {
+ try {
+ AgentSparqlService.requireReadyProjection(projectionStateSupplier);
+ } catch (AgentSparqlException failure) {
+ throw AgentSparqlToolErrors.toToolException(failure);
+ }
+ }
+ }
+
+ /**
+ * Resolves the caller the way {@code Authorizer#authorizeAdmin} does, so administrator status has
+ * one definition. The permission check already ran, so this only picks what the caller gets.
+ */
+ protected static boolean isAdministrator(final CatalogSecurityContext securityContext) {
+ return DefaultAuthorizer.getSubjectContext(securityContext).isAdmin();
+ }
+
@Override
public final T execute(
final Authorizer authorizer,
final CatalogSecurityContext securityContext,
final Map params)
throws IOException {
- authorizer.authorizeAdmin(securityContext);
+ authorize(authorizer, securityContext, params);
return executeAuthorized(securityContext, params);
}
+ /**
+ * Requires the explicit {@code ExecuteSparqlQuery} grant on the {@code rdf} resource, the same
+ * check as {@code POST /v1/rdf/sparql/agent}. Admins pass through the authorizer's short-circuit.
+ * Runs before {@link #repository()}, so an unauthorized caller learns nothing about whether RDF
+ * is enabled.
+ */
+ protected void authorize(
+ final Authorizer authorizer,
+ final CatalogSecurityContext securityContext,
+ final Map params) {
+ authorizer.authorize(
+ securityContext,
+ new OperationContext(Entity.RDF, MetadataOperation.EXECUTE_SPARQL_QUERY),
+ RdfQueryResourceContext.INSTANCE);
+ }
+
/**
* Runs a triplestore read under the shared admission guard (global and per-principal concurrency
* plus a hard timeout).
@@ -79,6 +137,7 @@ private static String guardKey(final CatalogSecurityContext securityContext) {
: securityContext.getUserPrincipal().getName();
}
+ /** Runs after {@link #authorize}. */
protected abstract T executeAuthorized(
final CatalogSecurityContext securityContext, final Map params)
throws IOException;
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfProjectionDegradedException.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfProjectionDegradedException.java
new file mode 100644
index 000000000000..a9dc50bb8a0a
--- /dev/null
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfProjectionDegradedException.java
@@ -0,0 +1,27 @@
+/*
+ * 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;
+
+/**
+ * The RDF projection is degraded: a failed live write or a failed rebuild left it behind the
+ * catalog, and only a completed full {@code RdfIndexApp} rebuild clears that. A deployment state
+ * like a disabled triplestore, not a transient fault, so retrying does not help and the client is
+ * told an administrator has to act. Classified by name in {@code DefaultToolContext}.
+ */
+final class RdfProjectionDegradedException extends RuntimeException {
+
+ RdfProjectionDegradedException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfQueryTimeoutException.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfQueryTimeoutException.java
new file mode 100644
index 000000000000..22cef5df7652
--- /dev/null
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfQueryTimeoutException.java
@@ -0,0 +1,22 @@
+/*
+ * 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;
+
+/** A graph query that exceeded the server's time limit; classified by name as a timeout. */
+final class RdfQueryTimeoutException extends RuntimeException {
+
+ RdfQueryTimeoutException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfRetryLaterException.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfRetryLaterException.java
new file mode 100644
index 000000000000..b1aa76960385
--- /dev/null
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/RdfRetryLaterException.java
@@ -0,0 +1,26 @@
+/*
+ * 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;
+
+/**
+ * A graph read that failed for a transient reason the caller did not cause: the projection is
+ * rebuilding, the store is unreachable, or the server is at its query capacity. Classified as
+ * retryable rather than as a backend fault, so the client is not told that retrying will not help.
+ */
+final class RdfRetryLaterException extends RuntimeException {
+
+ RdfRetryLaterException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/ShaclValidateTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/ShaclValidateTool.java
index f6d104bd9676..07c11d700ec1 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/ShaclValidateTool.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/ShaclValidateTool.java
@@ -20,6 +20,7 @@
import java.util.function.Supplier;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.RdfValidationService;
+import org.openmetadata.service.security.Authorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
/** Runs SHACL validation against an entity subgraph or an explicitly requested full graph. */
@@ -54,6 +55,18 @@ public ShaclValidateTool() {
super(repositorySupplier);
}
+ /**
+ * Stays admin-only: {@code fullGraph=true} loads up to 100k triples into memory, and the REST
+ * {@code /v1/rdf/validate} is admin-only too. The query permission is meant for bounded SELECTs.
+ */
+ @Override
+ protected void authorize(
+ final Authorizer authorizer,
+ final CatalogSecurityContext securityContext,
+ final Map params) {
+ authorizer.authorizeAdmin(securityContext);
+ }
+
@Override
protected Result executeAuthorized(
final CatalogSecurityContext securityContext, final Map params)
diff --git a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/SparqlQueryTool.java b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/SparqlQueryTool.java
index 7fbda3143da6..bbe0899782a3 100644
--- a/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/SparqlQueryTool.java
+++ b/openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/SparqlQueryTool.java
@@ -15,19 +15,44 @@
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;
+import org.openmetadata.schema.api.rdf.AgentSparqlCompleteness;
+import org.openmetadata.schema.api.rdf.AgentSparqlErrorCode;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
+import org.openmetadata.service.rdf.RdfProjectionStateResolver;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.RdfSparqlService;
import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
+import org.openmetadata.service.rdf.agent.AgentSparqlAudit;
+import org.openmetadata.service.rdf.agent.AgentSparqlCaller;
+import org.openmetadata.service.rdf.agent.AgentSparqlException;
+import org.openmetadata.service.rdf.agent.AgentSparqlResult;
+import org.openmetadata.service.rdf.agent.AgentSparqlService;
import org.openmetadata.service.rdf.federation.SparqlFederationGuard;
+import org.openmetadata.service.security.AuthorizationException;
+import org.openmetadata.service.security.ImpersonationContext;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
-/** Executes bounded, read-only SPARQL queries for MCP clients. */
+/**
+ * Executes bounded, read-only SPARQL queries for MCP clients.
+ *
+ * Administrators keep the full read surface. Every other caller who holds {@code
+ * ExecuteSparqlQuery} runs through the same agent profile as {@code POST /v1/rdf/sparql/agent}:
+ * SELECT only, no graph selection or federation, no inference, a ready projection, and an audit
+ * event.
+ */
public class SparqlQueryTool extends RdfMcpTool {
private static final int MIN_MAX_BYTES = RdfBody.MIN_BYTES;
+ private static final String FORMAT_PARAMETER = "format";
+ private static final String INFERENCE_LEVEL_PARAMETER = "inferenceLevel";
+ private static final String JSON_FORMAT = "json";
+ private static final String NO_INFERENCE = "none";
+ private static final String SELECT_QUERY_TYPE = "SELECT";
private final GuardedQueryExecutor guardedQueryExecutor;
public SparqlQueryTool() {
@@ -41,7 +66,14 @@ public SparqlQueryTool() {
SparqlQueryTool(
Supplier repositorySupplier, GuardedQueryExecutor guardedQueryExecutor) {
- super(repositorySupplier);
+ this(repositorySupplier, guardedQueryExecutor, RdfProjectionStateResolver::resolveConfigured);
+ }
+
+ SparqlQueryTool(
+ Supplier repositorySupplier,
+ GuardedQueryExecutor guardedQueryExecutor,
+ Supplier projectionStateSupplier) {
+ super(repositorySupplier, projectionStateSupplier);
this.guardedQueryExecutor = Objects.requireNonNull(guardedQueryExecutor);
}
@@ -49,6 +81,9 @@ public SparqlQueryTool() {
* {@code warning} carries {@link RdfSparqlService.QueryResult#warning()}, which the REST endpoint
* surfaces as the {@code X-OpenMetadata-Inference-Warning} header, so a qualified answer is never
* presented as authoritative. Null when the query ran as asked.
+ *
+ * {@code completeness} is set only for non-administrators, whose body is the agent JSON. It is
+ * repeated here because that JSON carries it at the end, where a bounded body cuts first.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Result(
@@ -57,7 +92,30 @@ public record Result(
String body,
boolean truncated,
int byteCount,
- String warning) {}
+ String warning,
+ Completeness completeness) {
+
+ Result(
+ String format,
+ String queryType,
+ String body,
+ boolean truncated,
+ int byteCount,
+ String warning) {
+ this(format, queryType, body, truncated, byteCount, warning, null);
+ }
+ }
+
+ /** Whether the rows are every row the submitted query selects, and why not when they are not. */
+ @JsonInclude(JsonInclude.Include.NON_NULL)
+ public record Completeness(String status, String reason) {
+
+ static Completeness of(final AgentSparqlCompleteness completeness) {
+ return new Completeness(
+ completeness.getStatus().value(),
+ completeness.getReason() == null ? null : completeness.getReason().value());
+ }
+ }
@Override
protected Result executeAuthorized(
@@ -65,25 +123,27 @@ protected Result executeAuthorized(
throws IOException {
McpToolParameters parameters = McpToolParameters.from(params);
String sparql = parameters.requiredString("query");
+ return isAdministrator(securityContext)
+ ? executeAsAdministrator(securityContext, parameters, sparql)
+ : executeWithAgentProfile(securityContext, parameters, sparql);
+ }
+
+ private Result executeAsAdministrator(
+ final CatalogSecurityContext securityContext,
+ final McpToolParameters parameters,
+ final String sparql) {
RdfSparqlService.ReadQuery query = RdfSparqlService.ReadQuery.parse(sparql);
RdfRepository repository = repository();
- String inferenceLevel = parameters.optionalString("inferenceLevel");
- // Default and ceiling both come from the dispatch-level budget rather than a standalone
- // megabyte
- // figure. The previous 1 MiB default and 16 MiB ceiling were 10x and 160x the dispatch cap, so
- // a
- // large SELECT was executed and paid for in full, then discarded wholesale by
- // DefaultToolContext.applyBudget and replaced with a data-less truncation stub. See RdfBody.
- // maxBytes can therefore only narrow the response, never widen it.
- int budgetBytes = RdfBody.maxBytes();
- int maxBytes =
- RdfBody.clamp(parameters.integer("maxBytes", budgetBytes), MIN_MAX_BYTES, budgetBytes);
+ String inferenceLevel = parameters.optionalString(INFERENCE_LEVEL_PARAMETER);
+ int maxBytes = maxBytes(parameters);
RdfSparqlService sparqlService =
new RdfSparqlService(repository, new SparqlFederationGuard(repository.getConfig()));
RdfSparqlService.QueryResult queryResult =
guardedQueryExecutor.execute(
CommonUtils.principal(securityContext),
- () -> sparqlService.query(query, parameters.optionalString("format"), inferenceLevel));
+ () ->
+ sparqlService.query(
+ query, parameters.optionalString(FORMAT_PARAMETER), inferenceLevel));
RdfBody.Bounded body = RdfBody.bound(queryResult.body(), maxBytes);
return new Result(
@@ -95,6 +155,95 @@ protected Result executeAuthorized(
queryResult.warning());
}
+ private Result executeWithAgentProfile(
+ final CatalogSecurityContext securityContext,
+ final McpToolParameters parameters,
+ final String sparql) {
+ RdfRepository repository = repository();
+ AgentSparqlCaller caller =
+ AgentSparqlCaller.of(requirePrincipal(securityContext), serviceActor(securityContext));
+ AgentSparqlResult result = runAgentQuery(repository, caller, parameters, sparql);
+ RdfBody.Bounded body =
+ RdfBody.bound(new String(result.body(), StandardCharsets.UTF_8), maxBytes(parameters));
+
+ return new Result(
+ JSON_FORMAT,
+ SELECT_QUERY_TYPE,
+ body.value(),
+ body.truncated(),
+ body.byteCount(),
+ null,
+ Completeness.of(result.completeness()));
+ }
+
+ /**
+ * The option check runs inside the audited call, so a permitted caller whose options are refused
+ * leaves the same {@code agent_sparql_query} event as any other outcome.
+ */
+ private AgentSparqlResult runAgentQuery(
+ final RdfRepository repository,
+ final AgentSparqlCaller caller,
+ final McpToolParameters parameters,
+ final String sparql) {
+ AgentSparqlService service =
+ AgentSparqlService.forRepository(() -> repository, projectionStateSupplier);
+ try {
+ return AgentSparqlAudit.record(
+ caller,
+ () -> {
+ requireAgentProfileOptions(parameters);
+ return service.execute(caller.effectiveUser(), sparql);
+ });
+ } catch (AgentSparqlException failure) {
+ throw AgentSparqlToolErrors.toToolException(failure);
+ }
+ }
+
+ /**
+ * The bot behind the call, resolved the way {@code RdfResource} does for the REST endpoint: the
+ * validated swap on the context when there is one, else the request thread's impersonation.
+ * {@code McpServer} sets the latter to the MCP bot for every tool call.
+ */
+ private static String serviceActor(final CatalogSecurityContext securityContext) {
+ return securityContext.impersonatedUser() != null
+ ? securityContext.impersonatedUser()
+ : ImpersonationContext.getImpersonatedBy();
+ }
+
+ private static void requireAgentProfileOptions(final McpToolParameters parameters) {
+ requireOption(parameters, FORMAT_PARAMETER, JSON_FORMAT);
+ requireOption(parameters, INFERENCE_LEVEL_PARAMETER, NO_INFERENCE);
+ }
+
+ private static void requireOption(
+ final McpToolParameters parameters, final String name, final String allowed) {
+ String requested = parameters.optionalString(name);
+ if (!McpToolParameters.isBlank(requested)
+ && !allowed.equals(requested.toLowerCase(Locale.ROOT))) {
+ throw new AgentSparqlException(
+ AgentSparqlErrorCode.QUERY_INVALID,
+ "'%s' must be '%s' unless you are an administrator; got '%s'"
+ .formatted(name, allowed, requested));
+ }
+ }
+
+ private static String requirePrincipal(final CatalogSecurityContext securityContext) {
+ if (securityContext.getUserPrincipal() == null) {
+ throw new AuthorizationException("An authenticated principal is required");
+ }
+ return CommonUtils.principal(securityContext);
+ }
+
+ /**
+ * Default and ceiling both come from the dispatch-level budget: a larger response would be
+ * discarded wholesale by {@code DefaultToolContext.applyBudget}, so {@code maxBytes} can only
+ * narrow the response, never widen it.
+ */
+ private static int maxBytes(final McpToolParameters parameters) {
+ int budgetBytes = RdfBody.maxBytes();
+ return RdfBody.clamp(parameters.integer("maxBytes", budgetBytes), MIN_MAX_BYTES, budgetBytes);
+ }
+
@FunctionalInterface
interface GuardedQueryExecutor {
RdfSparqlService.QueryResult execute(
diff --git a/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json b/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json
index a2e224e6cb1e..2af2cbaa68c2 100644
--- a/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json
+++ b/openmetadata-mcp/src/main/resources/json/data/mcp/tools.json
@@ -924,7 +924,7 @@
"destructiveHint": false,
"openWorldHint": false
},
- "description": "Run a read-only SPARQL query (SELECT, ASK, DESCRIBE, CONSTRUCT) against the OpenMetadata knowledge graph. Use this when the question is graph-shaped — e.g. 'all tables with FK references into customers.id', 'all upstream tables of dashboard X', 'columns tagged PII whose null count > 0'. UPDATE / INSERT / DELETE / DROP / LOAD / CLEAR / CREATE are rejected; use the admin REST endpoint for writes. SERVICE clauses against external endpoints are rejected unless on the federation allowlist, which is empty and disabled by default - so in a default deployment this tool never reaches outside the local graph. Returns the result body in the chosen format (default 'json' for SELECT/ASK; 'turtle' is recommended for DESCRIBE/CONSTRUCT). Body is capped at maxBytes (default and maximum: the server's MCP response budget); when it does not fit you get a prefix plus 'truncated': true and the full 'byteCount'. Narrow the query with LIMIT rather than raising maxBytes. A 'warning' field appears when the requested inferenceLevel could not be applied because the graph was too large - results are then NOT inferred. Admin only: this tool requires an administrator principal and returns 403 for ordinary users and for bot tokens.",
+ "description": "Run a read-only SPARQL query against the OpenMetadata knowledge graph. Use it for graph-shaped questions: lineage paths, column lineage, and joins across owners, tags, tiers and services. Requires the ExecuteSparqlQuery permission; administrators always pass. Callers who are not administrators get SELECT only, with no FROM, GRAPH or SERVICE, no inference and JSON output. Administrators may also run ASK, DESCRIBE and CONSTRUCT and set format and inferenceLevel. Updates are rejected. PAGING: always ORDER BY a stable key, then LIMIT 250 (a page of typical column rows is 50-60 KB, under the default 80000-byte body cap; an administrator can lower that cap, and maxBytes can only narrow it further, never raise it) and OFFSET 0, 250, 500 and so on; stop when a page returns fewer rows than LIMIT. If 'truncated' is true the body was cut, so lower LIMIT and repeat the same OFFSET. If completeness.status is TRUNCATED the server capped the rows, so add an explicit LIMIT. VOCABULARY (PREFIX om: ): entities are https://open-metadata.org/entity/{type}/{uuid}, typed 'a om:Table', om:Dashboard, om:Pipeline, om:Topic or om:Container, with om:fullyQualifiedName and rdfs:label for the name. Related terms: om:hasOwner, om:hasTag and om:hasGlossaryTerm (tag nodes carry om:tagFQN), om:hasTier, om:belongsToService, om:belongsToSchema, om:belongsToDatabase, om:belongsToDomain. Table lineage points from the output to its source: ?output om:upstream ?source (om:downstream is the reverse). COLUMN LINEAGE: om:fromColumn and om:toColumn reference column IRIs; om:fromColumnFqn and om:toColumnFqn carry FQN literals. One mapping can have several fromColumn values. Columns are resources: ?asset om:hasColumn ?c, with om:fullyQualifiedName and nested columns under om:hasChildColumn. All columns downstream of one column, with their asset: SELECT DISTINCT ?column ?asset WHERE { ?start om:fullyQualifiedName \"svc.db.schema.table.col\" . ?start (^om:fromColumn/om:toColumn)+ ?c . ?c om:fullyQualifiedName ?column . ?c (^om:hasChildColumn)*/^om:hasColumn ?asset } ORDER BY ?column ?asset LIMIT 250 OFFSET 0. For upstream use ^om:toColumn/om:fromColumn. Filter by adding patterns on ?asset, for example ?asset a om:Table, ?asset om:belongsToService/om:fullyQualifiedName \"svc\", ?asset om:hasOwner/rdfs:label \"growth\", or ?asset om:hasTier/om:tagFQN \"Tier.Tier1\". Lineage columns whose table is not in the graph are skipped silently, and live writes and RdfIndexApp both project column mappings. A store not rebuilt since 2.1 can still hold FQN literals in om:fromColumn and om:toColumn, so an empty result does not prove a column has no lineage. Use ontology_describe for the rest of the vocabulary.",
"parameters": {
"type": "object",
"properties": {
@@ -934,12 +934,12 @@
},
"format": {
"type": "string",
- "description": "Result format. SELECT/ASK: json (default), xml, csv, tsv. CONSTRUCT/DESCRIBE: turtle, jsonld, ntriples, rdfxml.",
+ "description": "Result format. Non-administrators: json only. Administrators: SELECT/ASK json (default), xml, csv, tsv; CONSTRUCT/DESCRIBE turtle, jsonld, ntriples, rdfxml.",
"default": "json"
},
"inferenceLevel": {
"type": "string",
- "description": "Optional. none (default) queries the stored graph. custom also returns facts derived by materialized inference rules and needs materialized inference enabled. rdfs and owl are not available and fail.",
+ "description": "Optional. none (default) queries the stored graph. custom also returns facts derived by materialized inference rules and needs materialized inference enabled. rdfs and owl are not available and fail. Non-administrators: none only.",
"default": "none"
},
"maxBytes": {
@@ -960,7 +960,7 @@
"destructiveHint": false,
"openWorldHint": false
},
- "description": "Return the n-hop instance-data neighborhood of an OpenMetadata entity in the knowledge graph. Use this when you have a specific entity (UUID + type) and want to see what else is connected to it: hasColumn, belongsToSchema, hasTag, owners, lineage, etc. Ontology and SHACL definition graphs are excluded so schema triples do not consume result slots. The full 1..depth-hop subgraph (depth bounded 1-3) is returned as Turtle 'triples'. Each traversal branch gets its own share of 'limit', so deeper hops are always represented rather than being crowded out by a high-degree start node. The 'edges' array is a flat, DIRECT (1-hop) adjacency summary of the start entity only (direction, predicate, neighbor URI, neighbor label) — for 2nd/3rd-hop traversal parse 'triples', not 'edges'. Admin only: this tool requires an administrator principal and returns 403 for ordinary users and for bot tokens.",
+ "description": "Return the n-hop instance-data neighborhood of an OpenMetadata entity in the knowledge graph. Use this when you have a specific entity (UUID + type) and want to see what else is connected to it: hasColumn, belongsToSchema, hasTag, owners, lineage, etc. Ontology and SHACL definition graphs are excluded so schema triples do not consume result slots. The full 1..depth-hop subgraph (depth bounded 1-3) is returned as Turtle 'triples'. Each traversal branch gets its own share of 'limit', so deeper hops are always represented rather than being crowded out by a high-degree start node. The 'edges' array is a flat, DIRECT (1-hop) adjacency summary of the start entity only (direction, predicate, neighbor URI, neighbor label) — for 2nd/3rd-hop traversal parse 'triples', not 'edges'. Requires the ExecuteSparqlQuery permission; administrators always pass.",
"parameters": {
"type": "object",
"properties": {
@@ -997,7 +997,7 @@
"destructiveHint": false,
"openWorldHint": false
},
- "description": "Find all entities tagged with a given classification tag or glossary term FQN. Walks om:hasTag and om:hasGlossaryTerm. Use this for 'show me everything classified PII.Sensitive' or 'all assets associated with the BusinessTerms.Customer glossary term'. Optionally filter by entity type. Paginated. Admin only: this tool requires an administrator principal and returns 403 for ordinary users and for bot tokens.",
+ "description": "Find all entities tagged with a given classification tag or glossary term FQN. Walks om:hasTag and om:hasGlossaryTerm. Use this for 'show me everything classified PII.Sensitive' or 'all assets associated with the BusinessTerms.Customer glossary term'. Optionally filter by entity type. Paginated. Requires the ExecuteSparqlQuery permission; administrators always pass.",
"parameters": {
"type": "object",
"properties": {
@@ -1033,7 +1033,7 @@
"destructiveHint": false,
"openWorldHint": false
},
- "description": "Run SHACL validation against either a single entity's subgraph (scoped via entityId+entityType or entityUri) or the entire dataset. Returns conforms (boolean), violationCount, and the SHACL ValidationReport in the requested RDF format. Read-only; never blocks writes. Use this to debug data-quality issues before mutating the graph. The report body is capped at maxBytes; 'conforms' and 'violationCount' are always returned in full even when the report itself is truncated. Admin only: this tool requires an administrator principal and returns 403 for ordinary users and for bot tokens.",
+ "description": "Run SHACL validation against either a single entity's subgraph (scoped via entityId+entityType or entityUri) or the entire dataset. Returns conforms (boolean), violationCount, and the SHACL ValidationReport in the requested RDF format. Read-only; never blocks writes. Use this to debug data-quality issues before mutating the graph. The report body is capped at maxBytes; 'conforms' and 'violationCount' are always returned in full even when the report itself is truncated. Admin only: this tool requires an administrator principal, because whole-graph validation loads up to 100,000 triples into memory.",
"parameters": {
"type": "object",
"properties": {
@@ -1074,7 +1074,7 @@
"destructiveHint": false,
"openWorldHint": false
},
- "description": "Return the OpenMetadata ontology — either the full canonical ontology (when 'resource' is omitted) or a SPARQL DESCRIBE for a single class or property URI. Use this to discover available classes, properties, ranges, and domains the agent can query. Prefer passing 'resource' for a focused DESCRIBE because the full ontology can exceed the response limit; the body is capped at maxBytes and flagged 'truncated' when it does not fit. Format: turtle (default), jsonld, ntriples, rdfxml. Admin only: this tool requires an administrator principal and returns 403 for ordinary users and for bot tokens.",
+ "description": "Return the OpenMetadata ontology — either the full canonical ontology (when 'resource' is omitted) or a SPARQL DESCRIBE for a single class or property URI. Use this to discover available classes, properties, ranges, and domains the agent can query. Prefer passing 'resource' for a focused DESCRIBE because the full ontology can exceed the response limit; the body is capped at maxBytes and flagged 'truncated' when it does not fit. Format: turtle (default), jsonld, ntriples, rdfxml. The full ontology (no 'resource') is open to every caller, like the REST ontology endpoint. A DESCRIBE of a 'resource' reads instance data and requires the ExecuteSparqlQuery permission; administrators always pass.",
"parameters": {
"type": "object",
"properties": {
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/RdfToolDescriptionVocabularyTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/RdfToolDescriptionVocabularyTest.java
new file mode 100644
index 000000000000..6dfe5b5553e5
--- /dev/null
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/RdfToolDescriptionVocabularyTest.java
@@ -0,0 +1,182 @@
+/*
+ * 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.assertj.core.api.Assertions.assertThat;
+
+import io.modelcontextprotocol.spec.McpSchema;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.jena.query.QueryFactory;
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.rdf.model.Property;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.riot.RDFDataMgr;
+import org.apache.jena.vocabulary.OWL;
+import org.apache.jena.vocabulary.RDF;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+/**
+ * The RDF tool descriptions are public: every MCP client reads them. They may only advertise
+ * vocabulary the projection really writes, the same contract the ontology tests enforce for the
+ * SQL-to-SPARQL mappings.
+ */
+class RdfToolDescriptionVocabularyTest {
+
+ private static final String OM = "https://open-metadata.org/ontology/";
+ private static final Set RDF_TOOLS =
+ Set.of(
+ "sparql_query",
+ "entity_neighborhood",
+ "find_by_tag",
+ "shacl_validate",
+ "ontology_describe");
+ private static final Set QUERY_PERMISSION_TOOLS =
+ Set.of("sparql_query", "entity_neighborhood", "find_by_tag", "ontology_describe");
+ private static final int SPARQL_QUERY_DESCRIPTION_BUDGET = 3_000;
+ private static final Pattern OM_TERM = Pattern.compile("\\bom:([A-Za-z][A-Za-z0-9]*)");
+ private static final Pattern COLUMN_LINEAGE_QUERY =
+ Pattern.compile("SELECT DISTINCT \\?column.*?OFFSET 0");
+
+ private static Model ontology;
+ private static Map tools;
+
+ @BeforeAll
+ static void load() {
+ ontology = RDFDataMgr.loadModel("rdf/ontology/openmetadata.ttl");
+ tools = new HashMap<>();
+ McpUtils.getToolProperties("json/data/mcp/tools.json").stream()
+ .filter(tool -> RDF_TOOLS.contains(tool.name()))
+ .forEach(tool -> tools.put(tool.name(), tool));
+ }
+
+ @AfterAll
+ static void close() {
+ ontology.close();
+ }
+
+ @Test
+ void everyRdfToolIsDefined() {
+ assertThat(tools.keySet()).isEqualTo(RDF_TOOLS);
+ }
+
+ @Test
+ void everyAdvertisedTermIsDeclaredAndProjected() {
+ final Set problems = new TreeSet<>();
+ advertisedTerms().forEach(term -> collectProblem(term, problems));
+
+ assertThat(problems).isEmpty();
+ }
+
+ @Test
+ void unprojectedFieldsAreNeverAdvertised() {
+ tools
+ .values()
+ .forEach(
+ tool ->
+ assertThat(textOf(tool).toLowerCase(Locale.ROOT))
+ .as(tool.name())
+ .doesNotContain("changedescription", "votes"));
+ }
+
+ @Test
+ void sparqlQueryStaysWithinItsCharacterBudget() {
+ assertThat(tools.get("sparql_query").description().length())
+ .isLessThanOrEqualTo(SPARQL_QUERY_DESCRIPTION_BUDGET);
+ }
+
+ @Test
+ void permissionWordingMatchesTheAccessMatrix() {
+ QUERY_PERMISSION_TOOLS.forEach(
+ name ->
+ assertThat(tools.get(name).description())
+ .as(name)
+ .contains("ExecuteSparqlQuery")
+ .doesNotContain("Admin only"));
+ assertThat(tools.get("shacl_validate").description())
+ .contains("Admin only")
+ .doesNotContainIgnoringCase("bot");
+ assertThat(tools.get("ontology_describe").description())
+ .contains("no 'resource') is open to every caller");
+ }
+
+ @Test
+ void sparqlQueryDescribesPagingTheProfileAndTheColumnLineageContract() {
+ assertThat(tools.get("sparql_query").description())
+ .contains("ORDER BY", "LIMIT 250", "OFFSET", "fewer rows than LIMIT")
+ .contains("'truncated' is true", "completeness.status is TRUNCATED")
+ .contains("SELECT only", "no FROM, GRAPH or SERVICE", "no inference")
+ .contains("reference column IRIs", "om:fromColumnFqn", "om:toColumnFqn", "RdfIndexApp")
+ .contains("?output om:upstream ?source");
+ }
+
+ @Test
+ void theAdvertisedColumnLineageQueryIsValidSparql() {
+ final Matcher query = COLUMN_LINEAGE_QUERY.matcher(tools.get("sparql_query").description());
+
+ assertThat(query.find()).as("column lineage template present").isTrue();
+ QueryFactory.create("PREFIX om: <" + OM + ">\n" + query.group());
+ }
+
+ private static Set advertisedTerms() {
+ final Set terms = new TreeSet<>();
+ tools.values().forEach(tool -> addTerms(textOf(tool), terms));
+ return terms;
+ }
+
+ private static void addTerms(final String text, final Set terms) {
+ final Matcher matcher = OM_TERM.matcher(text);
+ while (matcher.find()) {
+ terms.add(matcher.group(1));
+ }
+ }
+
+ private static String textOf(final McpSchema.Tool tool) {
+ final StringBuilder text = new StringBuilder(tool.description());
+ tool.inputSchema()
+ .properties()
+ .values()
+ .forEach(property -> text.append(' ').append(((Map, ?>) property).get("description")));
+ return text.toString();
+ }
+
+ private static void collectProblem(final String term, final Set problems) {
+ final Resource resource = ontology.createResource(OM + term);
+ if (!ontology.contains(resource, RDF.type)) {
+ problems.add("om:" + term + " is not declared in the ontology");
+ } else if (isProperty(resource) && !isStored(term)) {
+ problems.add("om:" + term + " is a property that is not labeled om:Stored");
+ }
+ }
+
+ private static boolean isProperty(final Resource resource) {
+ return List.of(RDF.Property, OWL.ObjectProperty, OWL.DatatypeProperty, OWL.AnnotationProperty)
+ .stream()
+ .anyMatch(type -> ontology.contains(resource, RDF.type, type));
+ }
+
+ private static boolean isStored(final String term) {
+ final Property status = ontology.createProperty(OM + "projectionStatus");
+ return ontology.contains(
+ ontology.createResource(OM + term), status, ontology.createResource(OM + "Stored"));
+ }
+}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/AgentSparqlToolErrorsTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/AgentSparqlToolErrorsTest.java
new file mode 100644
index 000000000000..808088c9c4b9
--- /dev/null
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/AgentSparqlToolErrorsTest.java
@@ -0,0 +1,126 @@
+/*
+ * 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.assertj.core.api.Assertions.assertThat;
+
+import java.util.Set;
+import org.junit.jupiter.api.Test;
+import org.openmetadata.schema.api.rdf.AgentSparqlErrorCode;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
+import org.openmetadata.service.rdf.agent.AgentSparqlException;
+import org.openmetadata.service.security.AuthorizationException;
+
+class AgentSparqlToolErrorsTest {
+
+ private static final Set CLIENT_ERRORS =
+ Set.of(
+ AgentSparqlErrorCode.QUERY_INVALID,
+ AgentSparqlErrorCode.QUERY_FORM_NOT_ALLOWED,
+ AgentSparqlErrorCode.GRAPH_SELECTION_NOT_ALLOWED,
+ AgentSparqlErrorCode.QUERY_LIMIT_EXCEEDED,
+ AgentSparqlErrorCode.RESULT_OUTPUT_LIMIT_EXCEEDED);
+ private static final Set RETRYABLE =
+ Set.of(
+ AgentSparqlErrorCode.EXECUTION_CAPACITY_EXHAUSTED,
+ AgentSparqlErrorCode.RDF_REPOSITORY_UNAVAILABLE);
+
+ @Test
+ void queryShapeRejectionsAreClientErrorsThatKeepTheirCode() {
+ for (AgentSparqlErrorCode code : CLIENT_ERRORS) {
+ final RuntimeException mapped = map(code);
+
+ assertThat(mapped).as(code.value()).isInstanceOf(IllegalArgumentException.class);
+ assertThat(mapped.getMessage()).startsWith(code.value() + ": ");
+ }
+ }
+
+ @Test
+ void aBlockedServiceClauseIsForbiddenLikeOnTheRestEndpoints() {
+ assertThat(map(AgentSparqlErrorCode.FEDERATION_NOT_ALLOWED))
+ .isInstanceOf(AuthorizationException.class)
+ .hasMessageStartingWith("FEDERATION_NOT_ALLOWED: ");
+ }
+
+ @Test
+ void transientStatesTellTheClientToRetry() {
+ for (AgentSparqlErrorCode code : RETRYABLE) {
+ assertThat(map(code))
+ .as(code.value())
+ .isInstanceOf(RdfRetryLaterException.class)
+ .hasMessageStartingWith(code.value() + ": ")
+ .hasMessageEndingWith("Retry shortly.");
+ }
+ }
+
+ @Test
+ void aRebuildingProjectionIsRetryableAndNamesTheAdministratorStepIfItPersists() {
+ final RuntimeException mapped =
+ projectionNotReady(RdfProjectionState.REBUILDING, "RDF projection is not ready");
+
+ assertThat(mapped)
+ .isInstanceOf(RdfRetryLaterException.class)
+ .hasMessageStartingWith("PROJECTION_NOT_READY: RDF projection is rebuilding; retry later.")
+ .hasMessageContaining("an administrator needs to run RdfIndexApp");
+ }
+
+ @Test
+ void aProjectionWhoseStateCannotBeDeterminedIsRetryable() {
+ assertThat(projectionNotReady(null, "RDF projection state could not be determined"))
+ .isInstanceOf(RdfRetryLaterException.class)
+ .hasMessageContaining("state could not be determined; retry later")
+ .hasMessageContaining("an administrator needs to run RdfIndexApp");
+ }
+
+ @Test
+ void aDegradedProjectionIsNotRetryableAndSaysAnAdministratorMustRebuild() {
+ assertThat(projectionNotReady(RdfProjectionState.DEGRADED, "RDF projection is not ready"))
+ .isInstanceOf(RdfProjectionDegradedException.class)
+ .hasMessageStartingWith("PROJECTION_NOT_READY: RDF projection is degraded;")
+ .hasMessageContaining("an administrator must run a full RdfIndexApp rebuild")
+ .satisfies(mapped -> assertThat(mapped.getMessage()).doesNotContain("Retry"));
+ }
+
+ @Test
+ void aTimeoutIsClassifiedAsATimeout() {
+ assertThat(map(AgentSparqlErrorCode.EXECUTION_TIMEOUT))
+ .isInstanceOf(RdfQueryTimeoutException.class);
+ }
+
+ @Test
+ void everyOtherCodeIsAServerFaultWithTheOriginalAsCause() {
+ for (AgentSparqlErrorCode code : AgentSparqlErrorCode.values()) {
+ if (!CLIENT_ERRORS.contains(code)
+ && !RETRYABLE.contains(code)
+ && code != AgentSparqlErrorCode.PROJECTION_NOT_READY
+ && code != AgentSparqlErrorCode.FEDERATION_NOT_ALLOWED
+ && code != AgentSparqlErrorCode.EXECUTION_TIMEOUT) {
+ final RuntimeException mapped = map(code);
+
+ assertThat(mapped).as(code.value()).isInstanceOf(IllegalStateException.class);
+ assertThat(mapped.getCause()).isInstanceOf(AgentSparqlException.class);
+ }
+ }
+ }
+
+ private static RuntimeException projectionNotReady(
+ final RdfProjectionState state, final String message) {
+ return AgentSparqlToolErrors.toToolException(
+ AgentSparqlException.projectionNotReady(state, message, null));
+ }
+
+ private static RuntimeException map(final AgentSparqlErrorCode code) {
+ return AgentSparqlToolErrors.toToolException(new AgentSparqlException(code, "detail"));
+ }
+}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/DefaultToolContextTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/DefaultToolContextTest.java
index 43fbe94d6332..536cbee62624 100644
--- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/DefaultToolContextTest.java
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/DefaultToolContextTest.java
@@ -25,6 +25,7 @@
import org.openmetadata.schema.api.configuration.MCPConfiguration;
import org.openmetadata.schema.entity.app.mcp.McpToolCallUsage;
import org.openmetadata.service.limits.Limits;
+import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
import org.openmetadata.service.security.AuthorizationException;
import org.openmetadata.service.security.Authorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
@@ -94,6 +95,38 @@ void classifyRateLimitException() {
.isEqualTo(McpToolCallUsage.ErrorCategory.RATE_LIMIT);
}
+ @Test
+ void classifyGraphReadsThatShouldBeRetriedAsRateLimited() {
+ assertThat(
+ DefaultToolContext.classifyException(
+ new RdfRetryLaterException("PROJECTION_NOT_READY: rebuilding", null)))
+ .isEqualTo(McpToolCallUsage.ErrorCategory.RATE_LIMIT);
+ assertThat(
+ DefaultToolContext.classifyException(
+ new SparqlQueryExecutionGuard.QueryCapacityException("concurrency limit reached")))
+ .isEqualTo(McpToolCallUsage.ErrorCategory.RATE_LIMIT);
+ assertThat(DefaultToolContext.resolveStatusCode(new RdfRetryLaterException("not ready", null)))
+ .isEqualTo(429);
+ }
+
+ @Test
+ void aDegradedProjectionIsADeploymentStateNotARetryableFault() {
+ final RdfProjectionDegradedException degraded =
+ new RdfProjectionDegradedException("PROJECTION_NOT_READY: degraded", null);
+
+ assertThat(DefaultToolContext.classifyException(degraded))
+ .isEqualTo(McpToolCallUsage.ErrorCategory.VALIDATION);
+ assertThat(DefaultToolContext.resolveStatusCode(degraded)).isEqualTo(400);
+ }
+
+ @Test
+ void classifyGraphQueryTimeoutAsTimeout() {
+ assertThat(
+ DefaultToolContext.classifyException(
+ new RdfQueryTimeoutException("EXECUTION_TIMEOUT: too slow", null)))
+ .isEqualTo(McpToolCallUsage.ErrorCategory.TIMEOUT);
+ }
+
@Test
void classifyFallsBackToInternalForUnknownException() {
assertThat(DefaultToolContext.classifyException(new RuntimeException("kaboom")))
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/EntityNeighborhoodToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/EntityNeighborhoodToolTest.java
index bcc9cf72dd9a..981ed3851751 100644
--- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/EntityNeighborhoodToolTest.java
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/EntityNeighborhoodToolTest.java
@@ -20,6 +20,8 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -36,9 +38,16 @@
import org.apache.jena.vocabulary.OWL;
import org.apache.jena.vocabulary.RDF;
import org.apache.jena.vocabulary.RDFS;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.service.rdf.RdfRepository;
+import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
+import org.openmetadata.service.security.AuthorizationException;
import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
class EntityNeighborhoodToolTest {
@@ -48,6 +57,20 @@ class EntityNeighborhoodToolTest {
private static final String ONTOLOGY_GRAPH = BASE_URI + "graph/ontology";
private static final Authorizer AUTHORIZER = mock(Authorizer.class);
private static final CatalogSecurityContext SECURITY_CONTEXT = mock(CatalogSecurityContext.class);
+ private static final Map NEIGHBORHOOD_PARAMS =
+ Map.of("entityId", "11111111-1111-1111-1111-111111111111", "entityType", "table");
+
+ private MockedStatic subjects;
+
+ @BeforeEach
+ void callersAreAdministrators() {
+ subjects = RdfToolAuthorization.resolvingCallersAs(true);
+ }
+
+ @AfterEach
+ void releaseTheCallerResolution() {
+ subjects.close();
+ }
@Test
void rejectsMissingEntityId() {
@@ -251,6 +274,106 @@ void deeperHopsSurviveAHighDegreeStartNode() {
}
}
+ @Test
+ void aNonAdministratorIsToldToRetryWhileTheProjectionRebuildsAndNothingIsRead() {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = enabledRepository();
+
+ assertThrows(
+ RdfRetryLaterException.class,
+ () ->
+ projectionTool(repository, RdfProjectionState.REBUILDING)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, NEIGHBORHOOD_PARAMS));
+
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aNonAdministratorIsNotToldToRetryWhenTheProjectionIsDegraded() {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = enabledRepository();
+
+ assertThrows(
+ RdfProjectionDegradedException.class,
+ () ->
+ projectionTool(repository, RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, NEIGHBORHOOD_PARAMS));
+
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aNonAdministratorIsAnsweredOnceTheProjectionIsReady() throws IOException {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+
+ final EntityNeighborhoodTool.Neighborhood result =
+ projectionTool(answeringRepository(), RdfProjectionState.READY)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, NEIGHBORHOOD_PARAMS);
+
+ assertEquals(0, result.edges().size());
+ }
+
+ @Test
+ void anAdministratorIsAnsweredWhateverTheProjectionState() throws IOException {
+ final EntityNeighborhoodTool.Neighborhood result =
+ projectionTool(answeringRepository(), RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, NEIGHBORHOOD_PARAMS);
+
+ assertEquals(0, result.edges().size());
+ }
+
+ private static RdfRepository answeringRepository() {
+ final RdfRepository repository = enabledRepository();
+ when(repository.executeSparqlQuery(anyString(), org.mockito.ArgumentMatchers.eq("text/turtle")))
+ .thenReturn("");
+ when(repository.executeSparqlQuery(
+ anyString(), org.mockito.ArgumentMatchers.eq("application/sparql-results+json")))
+ .thenReturn("{\"results\":{\"bindings\":[]}}");
+ return repository;
+ }
+
+ private static EntityNeighborhoodTool projectionTool(
+ final RdfRepository repository, final RdfProjectionState state) {
+ return new EntityNeighborhoodTool(() -> repository, () -> state);
+ }
+
+ @Test
+ void deniedCallerNeverReachesTheGraph() {
+ final Authorizer authorizer = RdfToolAuthorization.denyingAuthorizer();
+ final RdfRepository repository = enabledRepository();
+
+ assertThrows(
+ AuthorizationException.class,
+ () ->
+ tool(repository)
+ .execute(
+ authorizer,
+ SECURITY_CONTEXT,
+ Map.of("entityId", UUID.randomUUID().toString(), "entityType", "table")));
+
+ RdfToolAuthorization.assertSparqlGrantRequested(authorizer, SECURITY_CONTEXT);
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void bothGraphReadsRunInsideTheSharedAdmissionGuard() throws Exception {
+ final CatalogSecurityContext caller = RdfToolAuthorization.caller("neighborhood-user");
+ final RdfRepository repository = enabledRepository();
+
+ try (var saturation = RdfToolAuthorization.saturateGuardFor("neighborhood-user")) {
+ assertThrows(
+ SparqlQueryExecutionGuard.QueryCapacityException.class,
+ () ->
+ tool(repository)
+ .execute(
+ AUTHORIZER,
+ caller,
+ Map.of("entityId", UUID.randomUUID().toString(), "entityType", "table")));
+ }
+
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
private static EntityNeighborhoodTool tool(RdfRepository repository) {
return new EntityNeighborhoodTool(() -> repository);
}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/FindByTagToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/FindByTagToolTest.java
index 62c3858e862a..f33d6bab0081 100644
--- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/FindByTagToolTest.java
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/FindByTagToolTest.java
@@ -19,6 +19,8 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -32,9 +34,16 @@
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.service.rdf.RdfRepository;
+import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
+import org.openmetadata.service.security.AuthorizationException;
import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
class FindByTagToolTest {
@@ -42,6 +51,18 @@ class FindByTagToolTest {
private static final Authorizer AUTHORIZER = mock(Authorizer.class);
private static final CatalogSecurityContext SECURITY_CONTEXT = mock(CatalogSecurityContext.class);
+ private MockedStatic subjects;
+
+ @BeforeEach
+ void callersAreAdministrators() {
+ subjects = RdfToolAuthorization.resolvingCallersAs(true);
+ }
+
+ @AfterEach
+ void releaseTheCallerResolution() {
+ subjects.close();
+ }
+
@Test
void rejectsMissingTagFqn() {
IllegalArgumentException exception =
@@ -187,6 +208,95 @@ void returnsAnEmptyImmutableResultAndClampsLimit() throws IOException {
assertEquals(List.of(), result.results());
}
+ @Test
+ void aNonAdministratorIsToldToRetryWhileTheProjectionRebuildsAndNothingIsRead() {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = enabledRepository();
+
+ assertThrows(
+ RdfRetryLaterException.class,
+ () ->
+ projectionTool(repository, RdfProjectionState.REBUILDING)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, Map.of("tagFqn", "PII.Sensitive")));
+
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aNonAdministratorIsNotToldToRetryWhenTheProjectionIsDegraded() {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = enabledRepository();
+
+ assertThrows(
+ RdfProjectionDegradedException.class,
+ () ->
+ projectionTool(repository, RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, Map.of("tagFqn", "PII.Sensitive")));
+
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aNonAdministratorIsAnsweredOnceTheProjectionIsReady() throws IOException {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = enabledRepository();
+ when(repository.executeSparqlQuery(anyString(), anyString()))
+ .thenReturn("{\"results\":{\"bindings\":[]}}");
+
+ final FindByTagTool.Result result =
+ projectionTool(repository, RdfProjectionState.READY)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, Map.of("tagFqn", "PII.Sensitive"));
+
+ assertEquals(0, result.returnedCount());
+ }
+
+ @Test
+ void anAdministratorIsAnsweredWhateverTheProjectionState() throws IOException {
+ final RdfRepository repository = enabledRepository();
+ when(repository.executeSparqlQuery(anyString(), anyString()))
+ .thenReturn("{\"results\":{\"bindings\":[]}}");
+
+ final FindByTagTool.Result result =
+ projectionTool(repository, RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, Map.of("tagFqn", "PII.Sensitive"));
+
+ assertEquals(0, result.returnedCount());
+ }
+
+ private static FindByTagTool projectionTool(
+ final RdfRepository repository, final RdfProjectionState state) {
+ return new FindByTagTool(() -> repository, () -> state);
+ }
+
+ @Test
+ void deniedCallerNeverReachesTheGraph() {
+ final Authorizer authorizer = RdfToolAuthorization.denyingAuthorizer();
+ final RdfRepository repository = enabledRepository();
+
+ assertThrows(
+ AuthorizationException.class,
+ () ->
+ tool(repository)
+ .execute(authorizer, SECURITY_CONTEXT, Map.of("tagFqn", "PII.Sensitive")));
+
+ RdfToolAuthorization.assertSparqlGrantRequested(authorizer, SECURITY_CONTEXT);
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void readsRunInsideTheSharedAdmissionGuard() throws Exception {
+ final CatalogSecurityContext caller = RdfToolAuthorization.caller("find-by-tag-user");
+ final RdfRepository repository = enabledRepository();
+
+ try (var saturation = RdfToolAuthorization.saturateGuardFor("find-by-tag-user")) {
+ assertThrows(
+ SparqlQueryExecutionGuard.QueryCapacityException.class,
+ () -> tool(repository).execute(AUTHORIZER, caller, Map.of("tagFqn", "PII.Sensitive")));
+ }
+
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
private static FindByTagTool tool(RdfRepository repository) {
return new FindByTagTool(() -> repository);
}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/OntologyDescribeToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/OntologyDescribeToolTest.java
index a348bfa53871..04d559ad6a4b 100644
--- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/OntologyDescribeToolTest.java
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/OntologyDescribeToolTest.java
@@ -19,19 +19,42 @@
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Map;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.service.rdf.RdfRepository;
+import org.openmetadata.service.security.AuthorizationException;
import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
class OntologyDescribeToolTest {
private static final Authorizer AUTHORIZER = mock(Authorizer.class);
private static final CatalogSecurityContext SECURITY_CONTEXT = mock(CatalogSecurityContext.class);
+ private static final Map DESCRIBE_PARAMS =
+ Map.of("resource", "https://open-metadata.org/entity/table/abc");
+
+ private MockedStatic subjects;
+
+ @BeforeEach
+ void callersAreAdministrators() {
+ subjects = RdfToolAuthorization.resolvingCallersAs(true);
+ }
+
+ @AfterEach
+ void releaseTheCallerResolution() {
+ subjects.close();
+ }
@Test
void servesFullOntologyWithoutARepository() throws IOException {
@@ -43,6 +66,113 @@ void servesFullOntologyWithoutARepository() throws IOException {
assertFalse(result.body().isBlank());
}
+ @Test
+ void fullOntologyNeedsNoPermission() throws IOException {
+ final Authorizer deniedAuthorizer = RdfToolAuthorization.denyingAuthorizer();
+
+ final OntologyDescribeTool.Result withoutResource =
+ new OntologyDescribeTool(() -> null).execute(deniedAuthorizer, SECURITY_CONTEXT, Map.of());
+ final OntologyDescribeTool.Result blankResource =
+ new OntologyDescribeTool(() -> null)
+ .execute(deniedAuthorizer, SECURITY_CONTEXT, Map.of("resource", " "));
+
+ assertEquals("full-ontology", withoutResource.scope());
+ assertFalse(withoutResource.body().isBlank());
+ assertEquals("full-ontology", blankResource.scope());
+ assertFalse(blankResource.body().isBlank());
+ }
+
+ @Test
+ void aNonAdministratorDescribingAResourceIsToldToRetryWhileTheProjectionRebuilds() {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = mock(RdfRepository.class);
+ when(repository.isEnabled()).thenReturn(true);
+
+ assertThrows(
+ RdfRetryLaterException.class,
+ () ->
+ projectionTool(repository, RdfProjectionState.REBUILDING)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, DESCRIBE_PARAMS));
+
+ verify(repository, never()).executeSparqlQueryDirect(anyString(), anyString());
+ }
+
+ @Test
+ void aNonAdministratorDescribingAResourceIsNotToldToRetryWhenTheProjectionIsDegraded() {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+ final RdfRepository repository = mock(RdfRepository.class);
+ when(repository.isEnabled()).thenReturn(true);
+
+ assertThrows(
+ RdfProjectionDegradedException.class,
+ () ->
+ projectionTool(repository, RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, DESCRIBE_PARAMS));
+
+ verify(repository, never()).executeSparqlQueryDirect(anyString(), anyString());
+ }
+
+ @Test
+ void aNonAdministratorDescribingAResourceIsAnsweredOnceTheProjectionIsReady() throws IOException {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+
+ final OntologyDescribeTool.Result result =
+ projectionTool(describingRepository(), RdfProjectionState.READY)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, DESCRIBE_PARAMS);
+
+ assertEquals("describe", result.scope());
+ }
+
+ @Test
+ void anAdministratorDescribingAResourceIsAnsweredWhateverTheProjectionState() throws IOException {
+ final OntologyDescribeTool.Result result =
+ projectionTool(describingRepository(), RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, DESCRIBE_PARAMS);
+
+ assertEquals("describe", result.scope());
+ }
+
+ @Test
+ void theFullOntologyIsNeverGatedOnTheProjection() throws IOException {
+ RdfToolAuthorization.resolveCallersAs(subjects, false);
+
+ final OntologyDescribeTool.Result result =
+ projectionTool(describingRepository(), RdfProjectionState.DEGRADED)
+ .execute(AUTHORIZER, SECURITY_CONTEXT, Map.of());
+
+ assertEquals("full-ontology", result.scope());
+ }
+
+ private static RdfRepository describingRepository() {
+ final RdfRepository repository = mock(RdfRepository.class);
+ when(repository.isEnabled()).thenReturn(true);
+ when(repository.executeSparqlQueryDirect(anyString(), anyString())).thenReturn("");
+ return repository;
+ }
+
+ private static OntologyDescribeTool projectionTool(
+ final RdfRepository repository, final RdfProjectionState state) {
+ return new OntologyDescribeTool(() -> repository, () -> state);
+ }
+
+ @Test
+ void describingAResourceRequiresTheSparqlGrantBeforeAnyRead() {
+ final Authorizer authorizer = RdfToolAuthorization.denyingAuthorizer();
+ final RdfRepository repository = mock(RdfRepository.class);
+
+ assertThrows(
+ AuthorizationException.class,
+ () ->
+ new OntologyDescribeTool(() -> repository)
+ .execute(
+ authorizer,
+ SECURITY_CONTEXT,
+ Map.of("resource", "https://open-metadata.org/entity/table/abc")));
+
+ RdfToolAuthorization.assertSparqlGrantRequested(authorizer, SECURITY_CONTEXT);
+ verifyNoInteractions(repository);
+ }
+
@Test
void rejectsInvalidResourceIri() {
IllegalArgumentException exception =
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/RdfToolAuthorization.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/RdfToolAuthorization.java
new file mode 100644
index 000000000000..42dea5aa4330
--- /dev/null
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/RdfToolAuthorization.java
@@ -0,0 +1,133 @@
+/*
+ * 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.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+
+import jakarta.ws.rs.core.SecurityContext;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+import org.openmetadata.schema.entity.teams.User;
+import org.openmetadata.schema.type.MetadataOperation;
+import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
+import org.openmetadata.service.resources.rdf.RdfQueryResourceContext;
+import org.openmetadata.service.security.AuthorizationException;
+import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
+import org.openmetadata.service.security.auth.CatalogSecurityContext;
+import org.openmetadata.service.security.policyevaluator.OperationContext;
+import org.openmetadata.service.security.policyevaluator.SubjectContext;
+
+/** Shared assertions for the RDF MCP tools' authorization and admission-guard behavior. */
+final class RdfToolAuthorization {
+
+ private static final int PRINCIPAL_CONCURRENCY = 2;
+
+ private RdfToolAuthorization() {}
+
+ static CatalogSecurityContext caller(final String name) {
+ return new CatalogSecurityContext(() -> name, "https", "JWT", Set.of());
+ }
+
+ /**
+ * Makes every caller resolve to an administrator or to a plain user, as the tools see it through
+ * {@link DefaultAuthorizer#getSubjectContext}. The caller closes the returned mock.
+ */
+ static MockedStatic resolvingCallersAs(final boolean administrator) {
+ final MockedStatic subjects = mockStatic(DefaultAuthorizer.class);
+ resolveCallersAs(subjects, administrator);
+ return subjects;
+ }
+
+ static void resolveCallersAs(
+ final MockedStatic subjects, final boolean administrator) {
+ final SubjectContext subject =
+ new SubjectContext(new User().withName("caller").withIsAdmin(administrator), null, null);
+ subjects
+ .when(() -> DefaultAuthorizer.getSubjectContext(any(SecurityContext.class)))
+ .thenReturn(subject);
+ }
+
+ static Authorizer denyingAuthorizer() {
+ final Authorizer authorizer = mock(Authorizer.class);
+ doThrow(new AuthorizationException("not allowed"))
+ .when(authorizer)
+ .authorize(any(), any(OperationContext.class), any());
+ return authorizer;
+ }
+
+ static void assertSparqlGrantRequested(
+ final Authorizer authorizer, final CatalogSecurityContext caller) {
+ final ArgumentCaptor operation =
+ ArgumentCaptor.forClass(OperationContext.class);
+ verify(authorizer)
+ .authorize(eq(caller), operation.capture(), same(RdfQueryResourceContext.INSTANCE));
+ assertEquals(
+ List.of(MetadataOperation.EXECUTE_SPARQL_QUERY), operation.getValue().getOperations(null));
+ }
+
+ /**
+ * Holds every concurrency slot the principal may use in the shared admission guard, so any
+ * further read by the same principal is rejected with a capacity error unless it bypasses the
+ * guard.
+ */
+ static GuardSaturation saturateGuardFor(final String principal) throws InterruptedException {
+ final CountDownLatch release = new CountDownLatch(1);
+ final CountDownLatch started = new CountDownLatch(PRINCIPAL_CONCURRENCY);
+ for (int slot = 0; slot < PRINCIPAL_CONCURRENCY; slot++) {
+ Thread.startVirtualThread(() -> holdSlot(principal, started, release));
+ }
+ assertTrue(started.await(5, TimeUnit.SECONDS), "guard slots were not occupied");
+ return new GuardSaturation(release);
+ }
+
+ private static void holdSlot(
+ final String principal, final CountDownLatch started, final CountDownLatch release) {
+ SparqlQueryExecutionGuard.shared()
+ .execute(
+ principal,
+ () -> {
+ started.countDown();
+ awaitQuietly(release);
+ return null;
+ });
+ }
+
+ private static void awaitQuietly(final CountDownLatch latch) {
+ try {
+ latch.await(30, TimeUnit.SECONDS);
+ } catch (final InterruptedException exception) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ record GuardSaturation(CountDownLatch release) implements AutoCloseable {
+ @Override
+ public void close() {
+ release.countDown();
+ }
+ }
+}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/ShaclValidateToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/ShaclValidateToolTest.java
index 9ffcbdfc1ebd..2b19d58e5b31 100644
--- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/ShaclValidateToolTest.java
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/ShaclValidateToolTest.java
@@ -18,18 +18,26 @@
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
+import jakarta.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.openmetadata.service.rdf.RdfRepository;
+import org.openmetadata.service.security.AuthorizationException;
import org.openmetadata.service.security.Authorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
+import org.openmetadata.service.security.policyevaluator.OperationContext;
class ShaclValidateToolTest {
@@ -165,6 +173,23 @@ void acceptsBooleanAndStringFullGraphOptIn() throws IOException {
}
}
+ @Test
+ void staysAdminOnlyBecauseTheFullGraphModeIsExpensive() {
+ final Authorizer authorizer = mock(Authorizer.class);
+ final RdfRepository repository = enabledRepository();
+ doThrow(new AuthorizationException("Admin permission is required"))
+ .when(authorizer)
+ .authorizeAdmin(any(SecurityContext.class));
+
+ assertThrows(
+ AuthorizationException.class,
+ () -> tool(repository).execute(authorizer, SECURITY_CONTEXT, Map.of("fullGraph", true)));
+
+ verify(authorizer).authorizeAdmin(SECURITY_CONTEXT);
+ verify(authorizer, never()).authorize(any(), any(OperationContext.class), any());
+ verifyNoInteractions(repository);
+ }
+
private static ShaclValidateTool tool(RdfRepository repository) {
return new ShaclValidateTool(() -> repository);
}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolAgentProfileTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolAgentProfileTest.java
new file mode 100644
index 000000000000..ee18a62aada9
--- /dev/null
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolAgentProfileTest.java
@@ -0,0 +1,340 @@
+/*
+ * 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.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+import java.io.IOException;
+import java.util.Map;
+import java.util.function.Supplier;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.openmetadata.schema.api.configuration.rdf.RdfConfiguration;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
+import org.openmetadata.service.rdf.RdfRepository;
+import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
+import org.openmetadata.service.rdf.agent.AgentSparqlAudit;
+import org.openmetadata.service.security.AuthorizationException;
+import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
+import org.openmetadata.service.security.ImpersonationContext;
+import org.openmetadata.service.security.auth.CatalogSecurityContext;
+import org.slf4j.LoggerFactory;
+
+/** What a caller who holds only {@code ExecuteSparqlQuery} gets from {@code sparql_query}. */
+class SparqlQueryToolAgentProfileTest {
+
+ private static final String JSON = "application/sparql-results+json";
+ private static final String EMPTY_SELECT_RESULT =
+ "{\"head\":{\"vars\":[\"s\"]},\"results\":{\"bindings\":[]}}";
+ private static final String SELECT_ALL = "SELECT ?s WHERE { ?s ?p ?o } LIMIT 10";
+ private static final CatalogSecurityContext CALLER =
+ RdfToolAuthorization.caller("agent-profile-user");
+
+ private MockedStatic subjects;
+
+ @BeforeEach
+ void callersAreNotAdministrators() {
+ subjects = RdfToolAuthorization.resolvingCallersAs(false);
+ }
+
+ @AfterEach
+ void releaseTheCallerResolution() {
+ subjects.close();
+ }
+
+ @Test
+ void selectReturnsTheAgentJsonWithCompletenessOutsideTheBoundedBody() throws IOException {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ final SparqlQueryTool.Result result = run(repository, Map.of("query", SELECT_ALL));
+
+ assertEquals("json", result.format());
+ assertEquals("SELECT", result.queryType());
+ assertEquals("COMPLETE", result.completeness().status());
+ assertNull(result.completeness().reason());
+ assertTrue(result.body().contains("\"completeness\""));
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aSelectWithoutALimitIsMarkedTruncatedWhenTheServerCapCutsIt() throws IOException {
+ final RdfRepository repository = repositoryReturning(rows(1_001));
+
+ final SparqlQueryTool.Result result =
+ run(repository, Map.of("query", "SELECT ?s WHERE { ?s ?p ?o }"));
+
+ assertEquals("TRUNCATED", result.completeness().status());
+ assertEquals("SERVER_ROW_LIMIT", result.completeness().reason());
+ }
+
+ @Test
+ void completenessSurvivesWhenTheMcpBodyBudgetCutsTheJson() throws IOException {
+ final RdfRepository repository = repositoryReturning(rows(900));
+
+ final SparqlQueryTool.Result result =
+ run(
+ repository,
+ Map.of("query", "SELECT ?s WHERE { ?s ?p ?o } LIMIT 900", "maxBytes", 1024));
+
+ assertTrue(result.truncated());
+ assertFalse(result.body().contains("\"completeness\""));
+ assertEquals("COMPLETE", result.completeness().status());
+ }
+
+ @Test
+ void queryFormsOutsideTheProfileAreRejectedWithTheirCodeAndNeverReachTheGraph() {
+ final Map expectedCodeByQuery =
+ Map.of(
+ "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }", "QUERY_FORM_NOT_ALLOWED",
+ "ASK { ?s ?p ?o }", "QUERY_FORM_NOT_ALLOWED",
+ "DESCRIBE ", "QUERY_FORM_NOT_ALLOWED",
+ "SELECT * WHERE { GRAPH ?g { ?s ?p ?o } }", "GRAPH_SELECTION_NOT_ALLOWED",
+ "SELECT * FROM WHERE { ?s ?p ?o }", "GRAPH_SELECTION_NOT_ALLOWED",
+ "SELECT * WHERE { ?s ?p ?o FILTER((1)) }",
+ "QUERY_FORM_NOT_ALLOWED");
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ expectedCodeByQuery.forEach(
+ (query, code) -> {
+ final IllegalArgumentException rejected =
+ assertThrows(
+ IllegalArgumentException.class, () -> run(repository, Map.of("query", query)));
+ assertTrue(rejected.getMessage().startsWith(code + ":"), query + " -> " + rejected);
+ });
+
+ verify(repository, never()).executeAssertedSparqlQuery(anyString(), anyString());
+ verify(repository, never()).executeSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aBlockedServiceClauseIsForbiddenLikeOnTheRestEndpointsAndTheAdminPath() {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ final AuthorizationException blocked =
+ assertThrows(
+ AuthorizationException.class,
+ () ->
+ run(
+ repository,
+ Map.of(
+ "query",
+ "SELECT * WHERE { SERVICE { ?s ?p ?o } }")));
+
+ assertTrue(blocked.getMessage().startsWith("FEDERATION_NOT_ALLOWED:"));
+ verify(repository, never()).executeAssertedSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void inferenceAndNonJsonFormatsAreRejectedUpFrontNamingTheRule() {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ final IllegalArgumentException inference =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> run(repository, Map.of("query", SELECT_ALL, "inferenceLevel", "rdfs")));
+ final IllegalArgumentException format =
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> run(repository, Map.of("query", SELECT_ALL, "format", "csv")));
+
+ assertTrue(inference.getMessage().contains("'inferenceLevel' must be 'none'"));
+ assertTrue(format.getMessage().contains("'format' must be 'json'"));
+ verify(repository, never()).executeAssertedSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aRefusedOptionIsAuditedLikeAnyOtherOutcomeOfAPermittedCall() {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+ final Logger auditLogger = (Logger) LoggerFactory.getLogger(AgentSparqlAudit.class);
+ final ListAppender events = new ListAppender<>();
+ events.start();
+ auditLogger.addAppender(events);
+ try {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> run(repository, Map.of("query", SELECT_ALL, "inferenceLevel", "rdfs")));
+
+ final String event = events.list.get(0).getFormattedMessage();
+ assertTrue(event.contains("effectiveUser=agent-profile-user"), event);
+ assertTrue(event.contains("outcome=QUERY_INVALID"), event);
+ } finally {
+ auditLogger.detachAppender(events);
+ }
+ }
+
+ @Test
+ void theAuditLineNamesTheMcpBotAsServiceActorAndTheImpersonationIsLeftClean() throws IOException {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+ final Logger auditLogger = (Logger) LoggerFactory.getLogger(AgentSparqlAudit.class);
+ final ListAppender events = new ListAppender<>();
+ events.start();
+ auditLogger.addAppender(events);
+ ImpersonationContext.setImpersonatedBy("mcp-bot");
+ try {
+ run(repository, Map.of("query", SELECT_ALL));
+
+ final String event = events.list.get(0).getFormattedMessage();
+ assertTrue(event.contains("serviceActor=mcp-bot"), event);
+ assertTrue(event.contains("effectiveUser=agent-profile-user"), event);
+ } finally {
+ ImpersonationContext.clear();
+ auditLogger.detachAppender(events);
+ }
+ assertNull(ImpersonationContext.getImpersonatedBy());
+ }
+
+ @Test
+ void explicitlyAskingForTheDefaultsIsAccepted() throws IOException {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ final SparqlQueryTool.Result result =
+ run(repository, Map.of("query", SELECT_ALL, "inferenceLevel", "none", "format", "JSON"));
+
+ assertNotNull(result.completeness());
+ }
+
+ @Test
+ void anUnreadyProjectionIsARetryableErrorAndTheGraphIsNotQueried() {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ final RdfRetryLaterException notReady =
+ assertThrows(
+ RdfRetryLaterException.class,
+ () ->
+ tool(repository, () -> RdfProjectionState.REBUILDING)
+ .execute(grantedAuthorizer(), CALLER, Map.of("query", SELECT_ALL)));
+
+ assertTrue(notReady.getMessage().startsWith("PROJECTION_NOT_READY:"));
+ verify(repository, never()).executeAssertedSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aDegradedProjectionIsNotRetryableAndTheGraphIsNotQueried() {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+
+ final RdfProjectionDegradedException degraded =
+ assertThrows(
+ RdfProjectionDegradedException.class,
+ () ->
+ tool(repository, () -> RdfProjectionState.DEGRADED)
+ .execute(grantedAuthorizer(), CALLER, Map.of("query", SELECT_ALL)));
+
+ assertTrue(degraded.getMessage().contains("an administrator must run a full RdfIndexApp"));
+ verify(repository, never()).executeAssertedSparqlQuery(anyString(), anyString());
+ }
+
+ @Test
+ void aGrantedCallerOnADeploymentWithoutRdfGetsTheNotEnabledMessage() {
+ assertThrows(
+ RdfNotEnabledException.class,
+ () ->
+ new SparqlQueryTool(() -> null, SparqlQueryExecutionGuard.shared()::execute)
+ .execute(grantedAuthorizer(), CALLER, Map.of("query", SELECT_ALL)));
+ }
+
+ @Test
+ void aCallerWithoutAPrincipalIsRefusedInsteadOfFailingWithANullPointer() {
+ final RdfRepository repository = repositoryReturning(EMPTY_SELECT_RESULT);
+ final CatalogSecurityContext anonymous = mock(CatalogSecurityContext.class);
+
+ assertThrows(
+ AuthorizationException.class,
+ () ->
+ tool(repository, () -> RdfProjectionState.READY)
+ .execute(grantedAuthorizer(), anonymous, Map.of("query", SELECT_ALL)));
+ }
+
+ @Test
+ void administratorsKeepConstructGraphAndInferenceOnTheExistingPath() throws IOException {
+ final RdfRepository repository = enabledRepository();
+ when(repository.executeAssertedSparqlQuery(anyString(), anyString())).thenReturn("{}");
+ final Authorizer administrator = grantedAuthorizer();
+ RdfToolAuthorization.resolveCallersAs(subjects, true);
+
+ final SparqlQueryTool.Result construct =
+ tool(repository, () -> RdfProjectionState.READY)
+ .execute(
+ administrator,
+ CALLER,
+ Map.of("query", "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o } LIMIT 1"));
+ final SparqlQueryTool.Result graph =
+ tool(repository, () -> RdfProjectionState.READY)
+ .execute(
+ administrator,
+ CALLER,
+ Map.of("query", "SELECT * WHERE { GRAPH ?g { ?s ?p ?o } } LIMIT 1"));
+
+ assertEquals("CONSTRUCT", construct.queryType());
+ assertEquals("SELECT", graph.queryType());
+ assertNull(construct.completeness());
+ assertNull(graph.completeness());
+ verify(repository, never()).executeSparqlQueryDirect(anyString(), anyString());
+ }
+
+ private static SparqlQueryTool.Result run(
+ final RdfRepository repository, final Map params) throws IOException {
+ return tool(repository, () -> RdfProjectionState.READY)
+ .execute(grantedAuthorizer(), CALLER, params);
+ }
+
+ private static SparqlQueryTool tool(
+ final RdfRepository repository, final Supplier projectionState) {
+ return new SparqlQueryTool(
+ () -> repository, SparqlQueryExecutionGuard.shared()::execute, projectionState);
+ }
+
+ private static Authorizer grantedAuthorizer() {
+ return mock(Authorizer.class);
+ }
+
+ private static RdfRepository repositoryReturning(final String selectJson) {
+ final RdfRepository repository = enabledRepository();
+ when(repository.executeAssertedSparqlQuery(anyString(), eq(JSON))).thenReturn(selectJson);
+ return repository;
+ }
+
+ private static RdfRepository enabledRepository() {
+ final RdfRepository repository = mock(RdfRepository.class);
+ when(repository.isEnabled()).thenReturn(true);
+ when(repository.getConfig()).thenReturn(new RdfConfiguration());
+ return repository;
+ }
+
+ private static String rows(final int count) {
+ final StringBuilder bindings = new StringBuilder();
+ for (int row = 0; row < count; row++) {
+ bindings.append(row == 0 ? "" : ",");
+ bindings.append(
+ "{\"s\":{\"type\":\"uri\",\"value\":\"https://open-metadata.org/e/%d\"}}".formatted(row));
+ }
+ return "{\"head\":{\"vars\":[\"s\"]},\"results\":{\"bindings\":[%s]}}".formatted(bindings);
+ }
+}
diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolTest.java
index 0912a1c2f045..b452e648b095 100644
--- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolTest.java
+++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/SparqlQueryToolTest.java
@@ -17,26 +17,32 @@
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import jakarta.ws.rs.core.SecurityContext;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
import org.openmetadata.schema.api.configuration.rdf.RdfConfiguration;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.federation.SparqlFederationGuard;
import org.openmetadata.service.security.AuthorizationException;
import org.openmetadata.service.security.Authorizer;
+import org.openmetadata.service.security.DefaultAuthorizer;
import org.openmetadata.service.security.auth.CatalogSecurityContext;
class SparqlQueryToolTest {
@@ -45,13 +51,22 @@ class SparqlQueryToolTest {
private static final CatalogSecurityContext SECURITY_CONTEXT =
new CatalogSecurityContext(() -> "mcp-admin", "https", "JWT", Set.of());
+ private MockedStatic subjects;
+
+ @BeforeEach
+ void callersAreAdministrators() {
+ subjects = RdfToolAuthorization.resolvingCallersAs(true);
+ }
+
+ @AfterEach
+ void releaseTheCallerResolution() {
+ subjects.close();
+ }
+
@Test
- void rejectsNonAdminBeforeAccessingTheGraph() {
- final Authorizer deniedAuthorizer = mock(Authorizer.class);
+ void deniedCallerNeverReachesTheGraph() {
+ final Authorizer deniedAuthorizer = RdfToolAuthorization.denyingAuthorizer();
final RdfRepository repository = enabledRepository();
- doThrow(new AuthorizationException("Admin permission is required"))
- .when(deniedAuthorizer)
- .authorizeAdmin(SECURITY_CONTEXT);
assertThrows(
AuthorizationException.class,
@@ -62,10 +77,41 @@ void rejectsNonAdminBeforeAccessingTheGraph() {
SECURITY_CONTEXT,
Map.of("query", "SELECT * WHERE { ?s ?p ?o }")));
- verify(deniedAuthorizer).authorizeAdmin(SECURITY_CONTEXT);
+ RdfToolAuthorization.assertSparqlGrantRequested(deniedAuthorizer, SECURITY_CONTEXT);
+ subjects.verify(() -> DefaultAuthorizer.getSubjectContext(any(SecurityContext.class)), never());
verify(repository, never()).executeAssertedSparqlQuery(anyString(), anyString());
}
+ @Test
+ void deniedCallerLearnsNothingAboutWhetherRdfIsEnabled() {
+ assertThrows(
+ AuthorizationException.class,
+ () ->
+ new SparqlQueryTool(() -> null)
+ .execute(
+ RdfToolAuthorization.denyingAuthorizer(),
+ SECURITY_CONTEXT,
+ Map.of("query", "SELECT * WHERE { ?s ?p ?o }")));
+ }
+
+ @Test
+ void grantedCallerOnADeploymentWithoutRdfGetsTheNotEnabledMessage() {
+ final Authorizer grantingAuthorizer = mock(Authorizer.class);
+
+ final RdfNotEnabledException exception =
+ assertThrows(
+ RdfNotEnabledException.class,
+ () ->
+ new SparqlQueryTool(() -> null)
+ .execute(
+ grantingAuthorizer,
+ SECURITY_CONTEXT,
+ Map.of("query", "SELECT * WHERE { ?s ?p ?o }")));
+
+ RdfToolAuthorization.assertSparqlGrantRequested(grantingAuthorizer, SECURITY_CONTEXT);
+ assertTrue(exception.getMessage().toLowerCase(Locale.ROOT).contains("rdf"));
+ }
+
@Test
void rejectsMissingBlankAndMalformedQueries() {
assertValidationError("'query' parameter is required", Map.of());
@@ -175,18 +221,18 @@ void truncatesAtUtf8Boundary() throws IOException {
@Test
void routesInferenceThroughTheSharedService() throws IOException {
RdfRepository repository = enabledRepository();
- when(repository.executeSparqlQueryWithInferenceResult(anyString(), anyString(), eq("rdfs")))
+ when(repository.executeSparqlQueryWithInferenceResult(anyString(), anyString(), eq("custom")))
.thenReturn(new RdfRepository.InferenceQueryResult("{}", null));
tool(repository)
.execute(
AUTHORIZER,
SECURITY_CONTEXT,
- Map.of("query", "SELECT * WHERE { ?s ?p ?o }", "inferenceLevel", "rdfs"));
+ Map.of("query", "SELECT * WHERE { ?s ?p ?o }", "inferenceLevel", "custom"));
verify(repository)
.executeSparqlQueryWithInferenceResult(
- anyString(), eq("application/sparql-results+json"), eq("rdfs"));
+ anyString(), eq("application/sparql-results+json"), eq("custom"));
}
@Test
diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfProjectionStateResolver.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfProjectionStateResolver.java
index 884f313aec3d..52f8727f4471 100644
--- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfProjectionStateResolver.java
+++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/RdfProjectionStateResolver.java
@@ -23,6 +23,7 @@
import org.openmetadata.schema.entity.app.AppRunRecord;
import org.openmetadata.schema.exception.JsonParsingException;
import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.service.Entity;
import org.openmetadata.service.jdbi3.TimeSeriesDAOs.AppExtensionTimeSeries;
@Slf4j
@@ -41,6 +42,12 @@ public RdfProjectionStateResolver(
this.isDegraded = isDegraded;
}
+ /** Resolves the state from the server's own run store; the production wiring. */
+ public static RdfProjectionState resolveConfigured() {
+ return new RdfProjectionStateResolver(Entity.getCollectionDAO().appExtensionTimeSeriesDao())
+ .resolve();
+ }
+
public RdfProjectionState resolve() {
final List latestRuns =
runStore.listAppExtensionByName(
diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlException.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlException.java
index ce8fdc182d09..3e6d5d0c4882 100644
--- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlException.java
+++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlException.java
@@ -15,40 +15,60 @@
import java.util.Objects;
import org.openmetadata.schema.api.rdf.AgentSparqlErrorCode;
+import org.openmetadata.schema.api.rdf.RdfProjectionState;
/** A failure of the agent SPARQL endpoint, carrying its stable wire code. */
public final class AgentSparqlException extends RuntimeException {
private final AgentSparqlErrorCode code;
private final String requestId;
+ private final RdfProjectionState projectionState;
public AgentSparqlException(final AgentSparqlErrorCode code, final String message) {
- this(code, message, null, null);
+ this(code, message, null, null, null);
}
public AgentSparqlException(
final AgentSparqlErrorCode code, final String message, final Throwable cause) {
- this(code, message, cause, null);
+ this(code, message, cause, null, null);
}
private AgentSparqlException(
final AgentSparqlErrorCode code,
final String message,
final Throwable cause,
- final String requestId) {
+ final String requestId,
+ final RdfProjectionState projectionState) {
super(message, cause);
this.code = Objects.requireNonNull(code);
this.requestId = requestId;
+ this.projectionState = projectionState;
+ }
+
+ /**
+ * The projection is not {@code READY}. {@code state} is what the resolver reported, or {@code
+ * null} when it could not be determined; callers use it to tell a rebuild that will finish from a
+ * degraded projection that stays down until an administrator runs a full rebuild.
+ */
+ public static AgentSparqlException projectionNotReady(
+ final RdfProjectionState state, final String message, final Throwable cause) {
+ return new AgentSparqlException(
+ AgentSparqlErrorCode.PROJECTION_NOT_READY, message, cause, null, state);
}
/** The same failure, attributed to the request whose audit event already logged it. */
public AgentSparqlException forRequest(final String requestId) {
- return new AgentSparqlException(code, getMessage(), getCause(), requestId);
+ return new AgentSparqlException(code, getMessage(), getCause(), requestId, projectionState);
}
public AgentSparqlErrorCode getCode() {
return code;
}
+ /** The projection state behind a {@code PROJECTION_NOT_READY}, or {@code null} when unknown. */
+ public RdfProjectionState getProjectionState() {
+ return projectionState;
+ }
+
/** The request id already assigned to this failure, or {@code null} for pre-resource failures. */
public String getRequestId() {
return requestId;
diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlResult.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlResult.java
index 68a59bdbb1e9..638f16f495d2 100644
--- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlResult.java
+++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlResult.java
@@ -14,10 +14,15 @@
package org.openmetadata.service.rdf.agent;
import java.util.Objects;
+import org.openmetadata.schema.api.rdf.AgentSparqlCompleteness;
-/** A serialized agent response and the row count reported in the audit log. */
-public record AgentSparqlResult(byte[] body, int rowCount) {
+/**
+ * A serialized agent response, the row count reported in the audit log, and the completeness
+ * already embedded in the body, so a transport that bounds the body can still report it.
+ */
+public record AgentSparqlResult(byte[] body, int rowCount, AgentSparqlCompleteness completeness) {
public AgentSparqlResult {
Objects.requireNonNull(body);
+ Objects.requireNonNull(completeness);
}
}
diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlService.java b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlService.java
index 6a69416452f4..ab60e5597dad 100644
--- a/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlService.java
+++ b/openmetadata-service/src/main/java/org/openmetadata/service/rdf/agent/AgentSparqlService.java
@@ -20,9 +20,11 @@
import org.openmetadata.schema.api.rdf.AgentSparqlResponse;
import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.RdfSparqlService;
import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
import org.openmetadata.service.rdf.SparqlQueryLimits;
+import org.openmetadata.service.rdf.federation.SparqlFederationGuard;
/**
* Executes agent-authored SELECT queries against the server-configured RDF dataset.
@@ -47,6 +49,23 @@ public AgentSparqlService(
this.executionGuard = Objects.requireNonNull(executionGuard);
}
+ /**
+ * The one way to wire this service to a repository, shared by the REST endpoint and the MCP
+ * tools so both run the same readiness check, admission guard and SPARQL service.
+ */
+ public static AgentSparqlService forRepository(
+ final Supplier repositorySupplier,
+ final Supplier projectionStateSupplier) {
+ return new AgentSparqlService(
+ () -> sparqlServiceFor(repositorySupplier.get()),
+ projectionStateSupplier,
+ SparqlQueryExecutionGuard.shared());
+ }
+
+ private static RdfSparqlService sparqlServiceFor(final RdfRepository repository) {
+ return new RdfSparqlService(repository, new SparqlFederationGuard(repository.getConfig()));
+ }
+
/**
* @param effectiveUser the validated effective caller, resolved before the guard's thread handoff
* so per-user concurrency never keys on the impersonating bot
@@ -69,21 +88,35 @@ private AgentSparqlResult executeValidated(
final AgentSparqlResponse response = resultMapper.toResponse(sparqlJson, plan);
requireReadyProjection();
return new AgentSparqlResult(
- serializeBounded(response), response.getResults().getBindings().size());
+ serializeBounded(response),
+ response.getResults().getBindings().size(),
+ response.getMetadata().getCompleteness());
}
private void requireReadyProjection() {
- final RdfProjectionState state = currentProjectionState();
+ requireReadyProjection(projectionStateSupplier);
+ }
+
+ /**
+ * The readiness rule for every non-admin graph read. Public so the MCP tools that do not run
+ * through {@link #execute} apply the same check and raise the same failure.
+ */
+ public static void requireReadyProjection(
+ final Supplier projectionStateSupplier) {
+ final RdfProjectionState state = currentProjectionState(projectionStateSupplier);
if (state != RdfProjectionState.READY) {
- throw projectionNotReady("RDF projection is not ready (" + state + ")", null);
+ throw AgentSparqlException.projectionNotReady(
+ state, "RDF projection is not ready (" + state + ")", null);
}
}
- private RdfProjectionState currentProjectionState() {
+ private static RdfProjectionState currentProjectionState(
+ final Supplier projectionStateSupplier) {
try {
return projectionStateSupplier.get();
} catch (RuntimeException exception) {
- throw projectionNotReady("RDF projection state could not be determined", exception);
+ throw AgentSparqlException.projectionNotReady(
+ null, "RDF projection state could not be determined", exception);
}
}
@@ -100,9 +133,4 @@ private static byte[] serializeBounded(final AgentSparqlResponse response) {
}
return body;
}
-
- private static AgentSparqlException projectionNotReady(
- final String message, final Throwable cause) {
- return new AgentSparqlException(AgentSparqlErrorCode.PROJECTION_NOT_READY, message, cause);
- }
}
diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfQueryResourceContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfQueryResourceContext.java
index 012f8b2f5a83..7795f97b569d 100644
--- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfQueryResourceContext.java
+++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfQueryResourceContext.java
@@ -24,7 +24,7 @@
* Policy resource for the RDF query surface. RDF has no entity repository, so the entity-backed
* {@code ResourceContext} cannot be used; the dataset has no owners, tags, or domains to evaluate.
*/
-enum RdfQueryResourceContext implements ResourceContextInterface {
+public enum RdfQueryResourceContext implements ResourceContextInterface {
INSTANCE;
@Override
diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java
index 81577b1c0401..b80d621d1737 100644
--- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java
+++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/rdf/RdfResource.java
@@ -138,7 +138,7 @@ public RdfResource(Authorizer authorizer) {
RdfRepository::getInstanceOrNull,
null,
null,
- RdfResource::configuredProjectionState);
+ RdfProjectionStateResolver::resolveConfigured);
}
RdfResource(Authorizer authorizer, Supplier repositorySupplier) {
@@ -192,14 +192,7 @@ public RdfResource(Authorizer authorizer) {
this.inferenceRuleService = inferenceRuleService;
this.projectionStateSupplier = Objects.requireNonNull(projectionStateSupplier);
this.agentSparqlService =
- new AgentSparqlService(
- this::sparqlService, projectionStateSupplier, SPARQL_EXECUTION_GUARD);
- }
-
- private static RdfProjectionState configuredProjectionState() {
- final RdfProjectionStateResolver resolver =
- new RdfProjectionStateResolver(Entity.getCollectionDAO().appExtensionTimeSeriesDao());
- return resolver.resolve();
+ AgentSparqlService.forRepository(this::requireRdfRepository, projectionStateSupplier);
}
private RdfRepository getRdfRepository() {
diff --git a/openmetadata-service/src/main/resources/json/data/policy/DataConsumerPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/DataConsumerPolicy.json
index 7ab902c2180c..19bc790d806f 100644
--- a/openmetadata-service/src/main/resources/json/data/policy/DataConsumerPolicy.json
+++ b/openmetadata-service/src/main/resources/json/data/policy/DataConsumerPolicy.json
@@ -37,7 +37,7 @@
},
{
"name": "DataConsumerPolicy-ExecuteSparqlQuery-Rule",
- "description" : "Allow authenticated users to run read-only SPARQL queries through the agent SPARQL endpoint. The endpoint does not filter results by asset, so remove this rule if viewing is restricted through custom policies.",
+ "description" : "Allow authenticated users and bots to run read-only SPARQL queries through the agent SPARQL endpoint and the MCP knowledge-graph tools (sparql_query, entity_neighborhood, find_by_tag, and ontology_describe with a resource). Results are not filtered by asset or domain policies, so remove this rule if viewing is restricted through custom policies.",
"resources" : ["all"],
"operations": ["ExecuteSparqlQuery"],
"effect": "allow"
diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/DataConsumerPolicyGrantSqlMigrationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/DataConsumerPolicyGrantSqlMigrationTest.java
index c71af6eff72d..e87fdd84183b 100644
--- a/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/DataConsumerPolicyGrantSqlMigrationTest.java
+++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/utils/v210/DataConsumerPolicyGrantSqlMigrationTest.java
@@ -23,7 +23,10 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.HashSet;
import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import java.util.stream.Stream;
import org.jdbi.v3.core.Handle;
@@ -38,6 +41,7 @@
import org.openmetadata.service.Entity;
import org.openmetadata.service.jdbi3.locator.ConnectionType;
import org.openmetadata.service.migration.utils.MigrationFile;
+import org.openmetadata.service.util.EntityUtil;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
@@ -56,8 +60,8 @@
* conditions or resources, and it cannot see deny rules in other policies. The "known limit"
* scenarios pin those gaps so they stay visible.
*
- * That a statement runs only once per installation is the migration framework's guarantee for
- * schema-changes statements, not something SQL can show, so it is not asserted here.
+ *
The SPARQL grant's recorded statement hash is pinned so a description-only migration cannot
+ * restore a rule an administrator deleted.
*/
@Testcontainers(disabledWithoutDocker = true)
class DataConsumerPolicyGrantSqlMigrationTest {
@@ -68,10 +72,28 @@ class DataConsumerPolicyGrantSqlMigrationTest {
private static final String EDIT_RULE = "DataConsumerPolicy-EditRule";
private static final String OTHER_RULE = "OtherPolicy-Rule";
private static final String STATEMENT = "UPDATE policy_entity";
+ private static final String SHIPPED_DESCRIPTION =
+ "Allow authenticated users to run read-only SPARQL queries through the agent SPARQL"
+ + " endpoint. The endpoint does not filter results by asset, so remove this rule if"
+ + " viewing is restricted through custom policies.";
+ private static final String CUSTOM_DESCRIPTION = "Kept by the administrator";
private static final String ALL_RESOURCES = "all";
private static final String MYSQL_DIALECT = "mysql";
private static final String POSTGRES_DIALECT = "postgres";
+ /**
+ * MD5 of the grant statement as 2.1.0 first shipped it, which is what environments already at
+ * 2.1.0 recorded. The runner tracks statements by a hash of their text, so editing the statement
+ * would run it again there, and its only guard (the rule does not exist) would add back a rule an
+ * administrator deleted. Change the description with a new statement instead.
+ */
+ private static final Map RECORDED_GRANT_STATEMENT_HASH =
+ Map.of(
+ MYSQL_DIALECT,
+ "38ef58a4f3b4e037bf70417b3c490c6a",
+ POSTGRES_DIALECT,
+ "f99d8f93f30f81c15c46a65bd31c818d");
+
private static final Grant SPARQL_GRANT =
new Grant(
"DataConsumerPolicy-ExecuteSparqlQuery-Rule",
@@ -201,6 +223,125 @@ void addsTheRuleOnceToTheDataConsumerPolicyOnly(Grant grant, String dialect) {
}
}
+ @ParameterizedTest
+ @MethodSource("dialects")
+ void theGrantStatementKeepsTheTextEnvironmentsAlreadyRecorded(String dialect) {
+ assertEquals(
+ RECORDED_GRANT_STATEMENT_HASH.get(dialect),
+ EntityUtil.hash(grantStatement(SPARQL_GRANT, dialect)),
+ "The grant statement was edited; add a new statement instead (see the constant's note)");
+ }
+
+ @ParameterizedTest
+ @MethodSource("dialects")
+ void anAppendedStatementUpdatesOnlyTheOldDescriptionOfTheRule(String dialect) {
+ try (Handle handle = open(dialect)) {
+ Database db = new Database(handle, dialect);
+ createPolicyTable(db);
+ insertPolicy(
+ db, DATA_CONSUMER_POLICY, List.of(premiseRule(SPARQL_GRANT, ALL_RESOURCES, null)));
+ insertPolicy(
+ db,
+ OTHER_POLICY,
+ List.of(premiseRule(SPARQL_GRANT, ALL_RESOURCES, null), shippedGrant()));
+ handle.execute(grantStatement(SPARQL_GRANT, dialect));
+ assertEquals(SHIPPED_DESCRIPTION, grantDescription(db, DATA_CONSUMER_POLICY));
+
+ handle.execute(descriptionStatement(dialect));
+
+ assertEquals(seededDescription(), grantDescription(db, DATA_CONSUMER_POLICY));
+ assertEquals(List.of(EDIT_RULE, SPARQL_GRANT.rule()), ruleNames(db, DATA_CONSUMER_POLICY));
+ assertGrantsOnlyTheNamedOperation(db, SPARQL_GRANT);
+ assertEquals(SHIPPED_DESCRIPTION, grantDescription(db, OTHER_POLICY));
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("dialects")
+ void aRuleAnAdministratorDeletedStaysDeletedWhenOnlyUnrecordedStatementsRun(String dialect) {
+ try (Handle handle = open(dialect)) {
+ Database db = new Database(handle, dialect);
+ createPolicyTable(db);
+ insertPolicy(
+ db, DATA_CONSUMER_POLICY, List.of(premiseRule(SPARQL_GRANT, ALL_RESOURCES, null)));
+ Set recorded = new HashSet<>();
+ runUnrecorded(db, recorded, List.of(grantStatement(SPARQL_GRANT, dialect)));
+ deleteGrantRule(db);
+ assertEquals(List.of(EDIT_RULE), ruleNames(db, DATA_CONSUMER_POLICY));
+
+ runUnrecorded(
+ db,
+ recorded,
+ List.of(grantStatement(SPARQL_GRANT, dialect), descriptionStatement(dialect)));
+
+ assertEquals(List.of(EDIT_RULE), ruleNames(db, DATA_CONSUMER_POLICY));
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("dialects")
+ void aDescriptionTheAdministratorCustomisedIsLeftAlone(String dialect) {
+ try (Handle handle = open(dialect)) {
+ Database db = new Database(handle, dialect);
+ createPolicyTable(db);
+ insertPolicy(
+ db,
+ DATA_CONSUMER_POLICY,
+ List.of(
+ premiseRule(SPARQL_GRANT, ALL_RESOURCES, null),
+ shippedGrant().withDescription(CUSTOM_DESCRIPTION)));
+
+ handle.execute(descriptionStatement(dialect));
+
+ assertEquals(CUSTOM_DESCRIPTION, grantDescription(db, DATA_CONSUMER_POLICY));
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("dialects")
+ void aFreshInstallSeededWithTheNewTextIsLeftAlone(String dialect) {
+ try (Handle handle = open(dialect)) {
+ Database db = new Database(handle, dialect);
+ createPolicyTable(db);
+ insertPolicy(
+ db,
+ DATA_CONSUMER_POLICY,
+ List.of(
+ premiseRule(SPARQL_GRANT, ALL_RESOURCES, null),
+ shippedGrant().withDescription(seededDescription())));
+
+ handle.execute(descriptionStatement(dialect));
+
+ assertEquals(seededDescription(), grantDescription(db, DATA_CONSUMER_POLICY));
+ assertEquals(List.of(EDIT_RULE, SPARQL_GRANT.rule()), ruleNames(db, DATA_CONSUMER_POLICY));
+ }
+ }
+
+ @ParameterizedTest
+ @MethodSource("dialects")
+ void runningTheWholeFileAgainChangesNothing(String dialect) {
+ try (Handle handle = open(dialect)) {
+ Database db = new Database(handle, dialect);
+ createPolicyTable(db);
+ insertPolicy(
+ db, DATA_CONSUMER_POLICY, List.of(premiseRule(SPARQL_GRANT, ALL_RESOURCES, null)));
+ List file =
+ List.of(grantStatement(SPARQL_GRANT, dialect), descriptionStatement(dialect));
+ file.forEach(handle::execute);
+ Policy once = policy(db, DATA_CONSUMER_POLICY);
+
+ file.forEach(handle::execute);
+
+ assertEquals(
+ JsonUtils.pojoToJson(once), JsonUtils.pojoToJson(policy(db, DATA_CONSUMER_POLICY)));
+ assertEquals(seededDescription(), grantDescription(db, DATA_CONSUMER_POLICY));
+ }
+ }
+
+ static Stream dialects() {
+ return Stream.of(MYSQL_DIALECT, POSTGRES_DIALECT);
+ }
+
/** The shipped seed as an install created before {@code grant} existed holds it. */
private static List seededRulesBefore(Grant grant) {
try (InputStream seed =
@@ -329,11 +470,83 @@ private static String grantStatement(Grant grant, String dialect) {
List statements =
MigrationFile.parseSQLFile(migrationFile(dialect).toFile(), connectionType).stream()
.filter(sql -> sql.contains(grant.rule()) && sql.contains(STATEMENT))
+ .filter(sql -> !sql.contains(seededDescription()))
.toList();
assertEquals(1, statements.size(), "Expected one " + grant + " statement in " + dialect);
return statements.getFirst();
}
+ /** The appended statement that gives the rule its current description. */
+ private static String descriptionStatement(String dialect) {
+ List statements =
+ ruleStatements(dialect).stream().filter(sql -> sql.contains(seededDescription())).toList();
+ assertEquals(1, statements.size(), "Expected one description statement in " + dialect);
+ return statements.getFirst();
+ }
+
+ private static List ruleStatements(String dialect) {
+ ConnectionType connectionType =
+ MYSQL_DIALECT.equals(dialect) ? ConnectionType.MYSQL : ConnectionType.POSTGRES;
+ return MigrationFile.parseSQLFile(migrationFile(dialect).toFile(), connectionType).stream()
+ .filter(sql -> sql.contains(SPARQL_GRANT.rule()) && sql.contains(STATEMENT))
+ .toList();
+ }
+
+ /** The description new installations are seeded with, so the appended statement must match it. */
+ private static String seededDescription() {
+ try (InputStream seed =
+ DataConsumerPolicyGrantSqlMigrationTest.class
+ .getClassLoader()
+ .getResourceAsStream("json/data/policy/DataConsumerPolicy.json")) {
+ Policy policy = JsonUtils.readValue(new String(seed.readAllBytes()), Policy.class);
+ return policy.getRules().stream()
+ .filter(rule -> SPARQL_GRANT.rule().equals(rule.getName()))
+ .findFirst()
+ .orElseThrow()
+ .getDescription();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ private static Rule shippedGrant() {
+ return new Rule()
+ .withName(SPARQL_GRANT.rule())
+ .withDescription(SHIPPED_DESCRIPTION)
+ .withResources(List.of(ALL_RESOURCES))
+ .withOperations(List.of(MetadataOperation.EXECUTE_SPARQL_QUERY))
+ .withEffect(Rule.Effect.ALLOW);
+ }
+
+ private static String grantDescription(Database db, String policyName) {
+ return policy(db, policyName).getRules().stream()
+ .filter(rule -> SPARQL_GRANT.rule().equals(rule.getName()))
+ .findFirst()
+ .orElseThrow()
+ .getDescription();
+ }
+
+ /** What the runner does: a statement whose hash is already recorded is not run again. */
+ private static void runUnrecorded(Database db, Set recorded, List statements) {
+ for (String statement : statements) {
+ if (recorded.add(EntityUtil.hash(statement))) {
+ db.handle().execute(statement);
+ }
+ }
+ }
+
+ /** An administrator removing the rule, as the release note recommends for opting out. */
+ private static void deleteGrantRule(Database db) {
+ Policy policy = policy(db, DATA_CONSUMER_POLICY);
+ policy.getRules().removeIf(rule -> SPARQL_GRANT.rule().equals(rule.getName()));
+ String value = db.isPostgres() ? "CAST(:json AS JSONB)" : ":json";
+ db.handle()
+ .createUpdate("UPDATE policy_entity SET json = " + value + " WHERE name = :name")
+ .bind("json", JsonUtils.pojoToJson(policy))
+ .bind("name", DATA_CONSUMER_POLICY)
+ .execute();
+ }
+
private static Path migrationFile(String dialect) {
Path current = Path.of("").toAbsolutePath();
while (current != null && !Files.isDirectory(current.resolve("bootstrap/sql/migrations"))) {
diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/ColumnLineageFixture.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/ColumnLineageFixture.java
new file mode 100644
index 000000000000..b482c384135c
--- /dev/null
+++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/ColumnLineageFixture.java
@@ -0,0 +1,338 @@
+package org.openmetadata.service.rdf;
+
+import java.lang.reflect.Proxy;
+import java.net.URI;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.IntStream;
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.rdf.model.ModelFactory;
+import org.openmetadata.schema.EntityInterface;
+import org.openmetadata.schema.api.configuration.rdf.RdfConfiguration;
+import org.openmetadata.schema.entity.data.DashboardDataModel;
+import org.openmetadata.schema.entity.data.Table;
+import org.openmetadata.schema.type.Column;
+import org.openmetadata.schema.type.ColumnDataType;
+import org.openmetadata.schema.type.ColumnLineage;
+import org.openmetadata.schema.type.LineageDetails;
+import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.service.Entity;
+import org.openmetadata.service.rdf.storage.RdfStorageInterface;
+import org.openmetadata.service.rdf.translator.JsonLdTranslator;
+
+/**
+ * About 5,000 column-lineage mappings in exactly the shape {@code RdfIndexApp} projects.
+ *
+ * Column resources come from {@link JsonLdTranslator} and lineage from {@code
+ * RdfRepository#buildLineageModel}, the two production writers, so a query that works here works
+ * on a reindexed catalog. The expected results are computed by walking the recorded edge list in
+ * Java, never by SPARQL, so they stay an independent oracle for the query under test.
+ *
+ *
Shapes: a fan-out of one column into {@value #FAN_WIDTH}, a six-hop chain with a rename hop, a
+ * mapping with several source columns, a cycle, a hop into a dashboard data model, a nested child
+ * column, and unrelated noise chains.
+ *
+ *
Table names within the schema are fixed ({@code src}, {@code fan}, {@code h1}..{@code h5},
+ * {@code other}, {@code joined}, {@code nested}, {@code cyc}, {@code cyc2}, {@code dm}, {@code
+ * n0}..); the schema prefix and base URI are the caller's, so an integration test can keep its
+ * assets apart from everything else in a shared graph.
+ */
+public final class ColumnLineageFixture {
+ public static final int FAN_WIDTH = 450;
+ public static final int NOISE_TABLES = 24;
+ public static final int NOISE_WIDTH = 100;
+ public static final String TABLE_TYPE = "table";
+ private static final String DATA_MODEL_TYPE = "dashboardDataModel";
+
+ private final String baseUri;
+ private final String schemaPrefix;
+ private final Model model = ModelFactory.createDefaultModel();
+ private final RdfRepository repository;
+ private final JsonLdTranslator translator;
+ private final Map> downstreamOf = new HashMap<>();
+ private final Map> upstreamOf = new HashMap<>();
+ private final Map assetTypeByColumn = new HashMap<>();
+ private final Map assetIriByColumn = new HashMap<>();
+ private final Map tables = new HashMap<>();
+ private int columnLineageNodes;
+
+ private ColumnLineageFixture(final String baseUri, final String schemaPrefix) {
+ this.baseUri = baseUri;
+ this.schemaPrefix = schemaPrefix;
+ this.repository =
+ new RdfRepository(
+ new RdfConfiguration().withEnabled(true).withBaseUri(URI.create(baseUri)),
+ unusedStorage(),
+ null);
+ this.translator = new JsonLdTranslator(JsonUtils.getObjectMapper(), baseUri);
+ }
+
+ /**
+ * @param schemaPrefix the FQN prefix every table sits under, including the trailing dot, for
+ * example {@code svc.db.s.}
+ */
+ public static ColumnLineageFixture build(final String baseUri, final String schemaPrefix) {
+ EntityInterface.CANONICAL_ENTITY_NAME_MAP.put(TABLE_TYPE, Entity.TABLE);
+ EntityInterface.CANONICAL_ENTITY_NAME_MAP.put(
+ "dashboarddatamodel", Entity.DASHBOARD_DATA_MODEL);
+ final ColumnLineageFixture fixture = new ColumnLineageFixture(baseUri, schemaPrefix);
+ fixture.addFanOutAndChain();
+ fixture.addSpecialShapes();
+ fixture.addNoiseChains();
+ return fixture;
+ }
+
+ /** Every table, column and lineage triple; the caller may add its own before querying. */
+ public Model model() {
+ return model;
+ }
+
+ public int columnLineageNodes() {
+ return columnLineageNodes;
+ }
+
+ public String columnFqn(final String tableName, final String columnName) {
+ return schemaPrefix + tableName + "." + columnName;
+ }
+
+ /** The column whose downstream set spans several pages and every special shape. */
+ public String sourceColumn() {
+ return columnFqn("src", "col");
+ }
+
+ /** The nested child column, whose asset sits two levels above it. */
+ public String nestedColumn() {
+ return schemaPrefix + "nested.payload.id";
+ }
+
+ public Set downstreamOf(final String columnFqn) {
+ return reachable(downstreamOf, columnFqn);
+ }
+
+ public Set upstreamOf(final String columnFqn) {
+ return reachable(upstreamOf, columnFqn);
+ }
+
+ public Set onlyTableColumns(final Set columnFqns) {
+ final Set filtered = new HashSet<>(columnFqns);
+ filtered.removeIf(fqn -> !TABLE_TYPE.equals(assetTypeByColumn.get(fqn)));
+ return filtered;
+ }
+
+ public String assetIriOf(final String columnFqn) {
+ return assetIriByColumn.get(columnFqn);
+ }
+
+ private void addFanOutAndChain() {
+ final Table src = table("src", List.of("col", "col_b"));
+ final Table fan = table("fan", numbered("f"));
+ final Table h1 = table("h1", numbered("f"));
+ final Table h2 = table("h2", numbered("f"));
+ final Table h3 = table("h3", numbered("g"));
+ final Table h4 = table("h4", numbered("g"));
+ final Table h5 = table("h5", numbered("g"));
+
+ addEdge(src, fan, fanOut(src, fan));
+ addEdge(fan, h1, identity(fan, h1, "f", "f", FAN_WIDTH));
+ addEdge(h1, h2, identity(h1, h2, "f", "f", FAN_WIDTH));
+ addEdge(h2, h3, identity(h2, h3, "f", "g", FAN_WIDTH));
+ addEdge(h3, h4, identity(h3, h4, "g", "g", FAN_WIDTH));
+ addEdge(h4, h5, identity(h4, h5, "g", "g", FAN_WIDTH));
+ }
+
+ private void addSpecialShapes() {
+ final Table h1 = tables.get("h1");
+ final Table other = table("other", List.of("x"));
+ final Table joined = table("joined", List.of("combined"));
+ final Table nested = nestedTable("nested");
+ final Table cyc = table("cyc", List.of("a"));
+ final Table cyc2 = table("cyc2", List.of("b"));
+
+ addEdge(
+ h1,
+ joined,
+ List.of(
+ lineage(
+ List.of(columnFqn(h1, "f000"), columnFqn(other, "x")),
+ columnFqn(joined, "combined"))));
+ addEdge(h1, nested, List.of(lineage(columnFqn(h1, "f002"), nestedColumn())));
+ addEdge(
+ tables.get("h5"),
+ cyc,
+ List.of(lineage(columnFqn(tables.get("h5"), "g001"), columnFqn(cyc, "a"))));
+ addEdge(cyc, cyc2, List.of(lineage(columnFqn(cyc, "a"), columnFqn(cyc2, "b"))));
+ addEdge(cyc2, cyc, List.of(lineage(columnFqn(cyc2, "b"), columnFqn(cyc, "a"))));
+ addDataModelEdge(tables.get("h2"), dataModel("dm", List.of("metric")));
+ }
+
+ private void addNoiseChains() {
+ Table previous = table("n0", numbered("c", NOISE_WIDTH));
+ for (int hop = 1; hop < NOISE_TABLES; hop++) {
+ final Table next = table("n" + hop, numbered("c", NOISE_WIDTH));
+ addEdge(previous, next, identity(previous, next, "c", "c", NOISE_WIDTH));
+ previous = next;
+ }
+ }
+
+ private List fanOut(final Table from, final Table to) {
+ return numbered("f").stream()
+ .map(column -> lineage(columnFqn(from, "col"), columnFqn(to, column)))
+ .toList();
+ }
+
+ private List identity(
+ final Table from,
+ final Table to,
+ final String fromPrefix,
+ final String toPrefix,
+ final int width) {
+ final List lineage = new ArrayList<>();
+ for (int i = 0; i < width; i++) {
+ lineage.add(
+ lineage(
+ columnFqn(from, "%s%03d".formatted(fromPrefix, i)),
+ columnFqn(to, "%s%03d".formatted(toPrefix, i))));
+ }
+ return lineage;
+ }
+
+ private static List numbered(final String prefix) {
+ return numbered(prefix, FAN_WIDTH);
+ }
+
+ private static List numbered(final String prefix, final int width) {
+ return IntStream.range(0, width).mapToObj(i -> "%s%03d".formatted(prefix, i)).toList();
+ }
+
+ private Table table(final String name, final List columnNames) {
+ final String fqn = schemaPrefix + name;
+ return register(
+ new Table()
+ .withId(UUID.randomUUID())
+ .withName(name)
+ .withFullyQualifiedName(fqn)
+ .withColumns(columnNames.stream().map(c -> column(fqn, c)).toList()));
+ }
+
+ private Table nestedTable(final String name) {
+ final String fqn = schemaPrefix + name;
+ final Column child = column(fqn + ".payload", "id");
+ final Column parent = column(fqn, "payload").withChildren(List.of(child));
+ return register(
+ new Table()
+ .withId(UUID.randomUUID())
+ .withName(name)
+ .withFullyQualifiedName(fqn)
+ .withColumns(List.of(parent)));
+ }
+
+ private DashboardDataModel dataModel(final String name, final List columnNames) {
+ final String fqn = schemaPrefix + name;
+ final DashboardDataModel dataModel =
+ new DashboardDataModel()
+ .withId(UUID.randomUUID())
+ .withName(name)
+ .withFullyQualifiedName(fqn)
+ .withColumns(columnNames.stream().map(c -> column(fqn, c)).toList());
+ model.add(translator.toRdf(dataModel));
+ columnNames.forEach(c -> indexColumn(fqn + "." + c, DATA_MODEL_TYPE, dataModel.getId()));
+ return dataModel;
+ }
+
+ private Table register(final Table table) {
+ model.add(translator.toRdf(table));
+ tables.put(table.getName(), table);
+ table.getColumns().forEach(column -> indexColumnTree(column, table.getId()));
+ return table;
+ }
+
+ private void indexColumnTree(final Column column, final UUID tableId) {
+ indexColumn(column.getFullyQualifiedName(), TABLE_TYPE, tableId);
+ if (column.getChildren() != null) {
+ column.getChildren().forEach(child -> indexColumnTree(child, tableId));
+ }
+ }
+
+ private void indexColumn(final String fqn, final String type, final UUID assetId) {
+ assetTypeByColumn.put(fqn, type);
+ assetIriByColumn.put(fqn, baseUri + "entity/" + type + "/" + assetId);
+ }
+
+ private static Column column(final String parentFqn, final String name) {
+ return new Column()
+ .withName(name)
+ .withFullyQualifiedName(parentFqn + "." + name)
+ .withDataType(ColumnDataType.STRING);
+ }
+
+ private static String columnFqn(final Table table, final String name) {
+ return table.getFullyQualifiedName() + "." + name;
+ }
+
+ private static ColumnLineage lineage(final String fromColumn, final String toColumn) {
+ return lineage(List.of(fromColumn), toColumn);
+ }
+
+ private static ColumnLineage lineage(final List fromColumns, final String toColumn) {
+ return new ColumnLineage().withFromColumns(fromColumns).withToColumn(toColumn);
+ }
+
+ private void addEdge(final Table from, final Table to, final List lineage) {
+ writeEdge(TABLE_TYPE, from.getId(), TABLE_TYPE, to.getId(), lineage);
+ }
+
+ private void addDataModelEdge(final Table from, final DashboardDataModel to) {
+ final ColumnLineage lineage =
+ lineage(columnFqn(from, "f000"), to.getFullyQualifiedName() + ".metric");
+ writeEdge(TABLE_TYPE, from.getId(), DATA_MODEL_TYPE, to.getId(), List.of(lineage));
+ }
+
+ private void writeEdge(
+ final String fromType,
+ final UUID fromId,
+ final String toType,
+ final UUID toId,
+ final List lineage) {
+ final LineageDetails details = new LineageDetails().withColumnsLineage(lineage);
+ model.add(repository.buildLineageModel(fromType, fromId, toType, toId, details));
+ lineage.forEach(this::recordInOracle);
+ columnLineageNodes += lineage.size();
+ }
+
+ private void recordInOracle(final ColumnLineage lineage) {
+ for (final String from : lineage.getFromColumns()) {
+ downstreamOf.computeIfAbsent(from, key -> new HashSet<>()).add(lineage.getToColumn());
+ upstreamOf.computeIfAbsent(lineage.getToColumn(), key -> new HashSet<>()).add(from);
+ }
+ }
+
+ private static Set reachable(final Map> edges, final String start) {
+ final Set seen = new HashSet<>();
+ final Deque frontier = new ArrayDeque<>(edges.getOrDefault(start, Set.of()));
+ while (!frontier.isEmpty()) {
+ final String next = frontier.poll();
+ if (seen.add(next)) {
+ frontier.addAll(edges.getOrDefault(next, Set.of()));
+ }
+ }
+ return seen;
+ }
+
+ /** Building lineage triples never touches storage; a stub avoids a Mockito dependency. */
+ private static RdfStorageInterface unusedStorage() {
+ return (RdfStorageInterface)
+ Proxy.newProxyInstance(
+ ColumnLineageFixture.class.getClassLoader(),
+ new Class>[] {RdfStorageInterface.class},
+ (proxy, method, arguments) -> {
+ throw new UnsupportedOperationException(method.getName());
+ });
+ }
+}
diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfColumnLineageTraversalTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfColumnLineageTraversalTest.java
new file mode 100644
index 000000000000..a9ed0468e4d9
--- /dev/null
+++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfColumnLineageTraversalTest.java
@@ -0,0 +1,279 @@
+package org.openmetadata.service.rdf;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.UUID;
+import org.apache.jena.query.QueryExecution;
+import org.apache.jena.query.QuerySolution;
+import org.apache.jena.rdf.model.Model;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.openmetadata.schema.entity.data.Table;
+import org.openmetadata.schema.type.Column;
+import org.openmetadata.schema.type.ColumnDataType;
+import org.openmetadata.schema.type.EntityReference;
+import org.openmetadata.schema.type.TagLabel;
+import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.service.rdf.translator.JsonLdTranslator;
+
+/**
+ * Proves that the column-lineage shape written by {@code RdfIndexApp} can be traversed and paged
+ * with plain SPARQL. The data comes from {@link ColumnLineageFixture}, which is built by the two
+ * production writers, and every expected set is the fixture's independent walk of its own edge
+ * list.
+ */
+class RdfColumnLineageTraversalTest {
+ private static final String BASE = "https://open-metadata.org/";
+ private static final String PREFIXES = "PREFIX om: <" + BASE + "ontology/>\n";
+ private static final String SCHEMA_FQN = "svc.db.s.";
+ private static final int PAGE_SIZE = 250;
+ private static final String DOWNSTREAM_PATH = "^om:fromColumn/om:toColumn";
+ private static final String UPSTREAM_PATH = "^om:toColumn/om:fromColumn";
+
+ private ColumnLineageFixture fixture;
+ private Model graph;
+ private String sourceColumn;
+
+ @BeforeEach
+ void buildFixture() {
+ fixture = ColumnLineageFixture.build(BASE, SCHEMA_FQN);
+ graph = fixture.model();
+ sourceColumn = fixture.sourceColumn();
+ }
+
+ @Test
+ void fixtureIsRealisticallyLarge() {
+ assertTrue(
+ fixture.columnLineageNodes() >= 5_000,
+ "column lineage nodes: " + fixture.columnLineageNodes());
+ assertEquals(fixture.columnLineageNodes(), count("?c a om:ColumnLineage"));
+ }
+
+ @Test
+ void downstreamTraversalMatchesTheIndependentWalkOfTheEdgeList() {
+ final Set expected = fixture.downstreamOf(sourceColumn);
+
+ final List actual = pagedColumns(sourceColumn, DOWNSTREAM_PATH, "", PAGE_SIZE);
+
+ assertTrue(expected.size() > 2 * PAGE_SIZE, "fixture must need several pages");
+ assertEquals(expected, new HashSet<>(actual));
+ assertEquals(expected.size(), actual.size(), "paged union must not repeat rows");
+ }
+
+ @Test
+ void upstreamTraversalCrossesRenameHopsAndMultiSourceNodes() {
+ for (final String start :
+ List.of(
+ fixture.columnFqn("h5", "g001"),
+ fixture.columnFqn("joined", "combined"),
+ fixture.columnFqn("cyc", "a"))) {
+ final List actual = pagedColumns(start, UPSTREAM_PATH, "", 3);
+
+ assertEquals(fixture.upstreamOf(start), new HashSet<>(actual), start);
+ assertEquals(new HashSet<>(actual).size(), actual.size(), start);
+ }
+ }
+
+ @Test
+ void cycleTerminatesAndReachesItself() {
+ final String start = fixture.columnFqn("cyc", "a");
+
+ final List actual = pagedColumns(start, DOWNSTREAM_PATH, "", PAGE_SIZE);
+
+ assertEquals(Set.of(fixture.columnFqn("cyc2", "b"), start), new HashSet<>(actual));
+ }
+
+ @Test
+ void pagesAreOrderedAndStableAcrossPageSizes() {
+ final List full = pagedColumns(sourceColumn, DOWNSTREAM_PATH, "", PAGE_SIZE);
+
+ assertEquals(full, pagedColumns(sourceColumn, DOWNSTREAM_PATH, "", 97));
+ assertEquals(full.stream().sorted().toList(), full);
+ }
+
+ @Test
+ void typeFilterDropsTheDataModelHopAndKeepsNestedColumnsOnTheirTable() {
+ final Set tableColumns = fixture.onlyTableColumns(fixture.downstreamOf(sourceColumn));
+
+ final List actual =
+ pagedColumns(sourceColumn, DOWNSTREAM_PATH, "?asset a om:Table .", PAGE_SIZE);
+
+ assertEquals(tableColumns, new HashSet<>(actual));
+ assertFalse(actual.contains(fixture.columnFqn("dm", "metric")));
+ assertTrue(actual.contains(fixture.nestedColumn()));
+ }
+
+ @Test
+ void assetColumnJoinResolvesEveryReachableColumnToItsOwningAsset() {
+ final Set reachable = fixture.downstreamOf(sourceColumn);
+ final Map assetByColumn = new TreeMap<>();
+
+ pagedRows(sourceColumn, DOWNSTREAM_PATH, "", PAGE_SIZE)
+ .forEach(row -> assetByColumn.put(row.column(), row.asset()));
+
+ assertEquals(reachable, assetByColumn.keySet());
+ reachable.forEach(fqn -> assertEquals(fixture.assetIriOf(fqn), assetByColumn.get(fqn), fqn));
+ }
+
+ @Test
+ void fullDownstreamWalkStaysFarInsideTheGuardTimeout() {
+ final long started = System.nanoTime();
+ final List rows = pagedColumns(sourceColumn, DOWNSTREAM_PATH, "", PAGE_SIZE);
+ final long totalMillis = (System.nanoTime() - started) / 1_000_000;
+
+ System.out.printf(
+ "[column-lineage-timing] downstream of %s: %d rows in %d ms over %d columnLineage nodes%n",
+ sourceColumn, rows.size(), totalMillis, fixture.columnLineageNodes());
+ assertTrue(totalMillis < SparqlQueryLimits.TIMEOUT_MILLIS, "took " + totalMillis + " ms");
+ }
+
+ /**
+ * The sparql_query tool description tells clients to narrow the asset join with these patterns,
+ * so each one is pinned against what the production translator writes for an asset.
+ */
+ @Test
+ void assetFilterPatternsAdvertisedToClientsMatchTheProjection() {
+ final Table orders = projectedOrdersTable();
+ graph.add(new JsonLdTranslator(JsonUtils.getObjectMapper(), BASE).toRdf(orders));
+ final String assetFqn = orders.getFullyQualifiedName();
+
+ assertTrue(ask("?a om:fullyQualifiedName \"%s\" . ?a a om:Table".formatted(assetFqn)));
+ assertTrue(
+ ask(
+ "?a om:fullyQualifiedName \"%s\" . ?a om:belongsToService/om:fullyQualifiedName \"svc\""
+ .formatted(assetFqn)));
+ assertTrue(
+ ask(
+ "?a om:fullyQualifiedName \"%s\" . ?a om:hasOwner/rdfs:label \"growth\""
+ .formatted(assetFqn)));
+ assertTrue(
+ ask(
+ "?a om:fullyQualifiedName \"%s\" . ?a om:hasTier/om:tagFQN \"Tier.Tier1\""
+ .formatted(assetFqn)));
+ assertTrue(
+ ask(
+ "?a om:fullyQualifiedName \"%s\" . ?a om:hasTag/om:tagFQN \"Tier.Tier1\""
+ .formatted(assetFqn)));
+ }
+
+ private static Table projectedOrdersTable() {
+ final Table table =
+ new Table()
+ .withId(UUID.randomUUID())
+ .withName("orders")
+ .withFullyQualifiedName(SCHEMA_FQN + "orders")
+ .withService(reference("databaseService", "svc"))
+ .withOwners(List.of(reference("team", "growth")))
+ .withTags(
+ List.of(
+ new TagLabel()
+ .withTagFQN("Tier.Tier1")
+ .withSource(TagLabel.TagSource.CLASSIFICATION)
+ .withLabelType(TagLabel.LabelType.MANUAL)
+ .withState(TagLabel.State.CONFIRMED)));
+ return table.withColumns(
+ List.of(
+ new Column()
+ .withName("id")
+ .withFullyQualifiedName(table.getFullyQualifiedName() + ".id")
+ .withDataType(ColumnDataType.STRING)));
+ }
+
+ private static EntityReference reference(final String type, final String name) {
+ return new EntityReference()
+ .withId(UUID.randomUUID())
+ .withType(type)
+ .withName(name)
+ .withFullyQualifiedName(name);
+ }
+
+ private boolean ask(final String pattern) {
+ final String query =
+ PREFIXES + "PREFIX rdfs: \nASK { " + pattern + " }";
+ try (QueryExecution execution = QueryExecution.create(query, graph)) {
+ return execution.execAsk();
+ }
+ }
+
+ private int count(final String pattern) {
+ return countRows("SELECT (COUNT(*) AS ?n) WHERE { " + pattern + " }");
+ }
+
+ private int countRows(final String select) {
+ try (QueryExecution execution = QueryExecution.create(PREFIXES + select, graph)) {
+ return execution.execSelect().next().getLiteral("n").getInt();
+ }
+ }
+
+ private List pagedColumns(
+ final String start, final String path, final String filter, final int pageSize) {
+ return pagedRows(start, path, filter, pageSize).stream().map(Row::column).toList();
+ }
+
+ private List pagedRows(
+ final String start, final String path, final String filter, final int pageSize) {
+ final List rows = new ArrayList<>();
+ int offset = 0;
+ List page;
+ do {
+ page = runPage(start, path, filter, pageSize, offset);
+ rows.addAll(page);
+ offset += pageSize;
+ } while (page.size() == pageSize);
+ return rows;
+ }
+
+ private List runPage(
+ final String start,
+ final String path,
+ final String filter,
+ final int pageSize,
+ final int offset) {
+ final String query = columnQuery(start, path, filter, pageSize, offset);
+ final long started = System.nanoTime();
+ final List page = new ArrayList<>();
+ try (QueryExecution execution = QueryExecution.create(query, graph)) {
+ execution.execSelect().forEachRemaining(solution -> page.add(Row.from(solution)));
+ }
+ final long millis = (System.nanoTime() - started) / 1_000_000;
+ assertTrue(millis < SparqlQueryLimits.TIMEOUT_MILLIS, "page took " + millis + " ms");
+ return page;
+ }
+
+ // The asset join walks up from the already-bound column. The forward form
+ // `?asset om:hasColumn/om:hasChildColumn* ?c` made ARQ enumerate every node as a zero-length
+ // start and took ~6.6 s per page on this fixture versus ~50 ms for the inverse form.
+ private static String columnQuery(
+ final String start,
+ final String path,
+ final String filter,
+ final int pageSize,
+ final int offset) {
+ return PREFIXES
+ + """
+ SELECT DISTINCT ?column ?asset WHERE {
+ ?start om:fullyQualifiedName "%s" .
+ ?start (%s)+ ?c .
+ ?c om:fullyQualifiedName ?column .
+ ?c (^om:hasChildColumn)*/^om:hasColumn ?asset .
+ %s
+ } ORDER BY ?column ?asset LIMIT %d OFFSET %d
+ """
+ .formatted(start, path, filter, pageSize, offset);
+ }
+
+ private record Row(String column, String asset) {
+ static Row from(final QuerySolution solution) {
+ return new Row(
+ solution.getLiteral("column").getString(), solution.getResource("asset").getURI());
+ }
+ }
+}
diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfProjectionStateResolverTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfProjectionStateResolverTest.java
index 9c1de3d7298f..e7e2b800b802 100644
--- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfProjectionStateResolverTest.java
+++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/RdfProjectionStateResolverTest.java
@@ -15,6 +15,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
import java.util.List;
@@ -24,9 +25,12 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
+import org.mockito.MockedStatic;
import org.openmetadata.schema.api.rdf.RdfProjectionState;
import org.openmetadata.schema.entity.app.AppRunRecord;
import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.service.Entity;
+import org.openmetadata.service.jdbi3.CollectionDAO;
import org.openmetadata.service.jdbi3.TimeSeriesDAOs.AppExtensionTimeSeries;
class RdfProjectionStateResolverTest {
@@ -53,6 +57,22 @@ void mapsLatestApplicationRunState(
assertEquals(expectedState, resolver.resolve());
}
+ @Test
+ void resolveConfiguredReadsTheRunStoreOfTheRunningServer() {
+ RdfProjectionHealth.markReady();
+ final AppRunRecord run = new AppRunRecord().withStatus(AppRunRecord.Status.SUCCESS);
+ when(runStore.listAppExtensionByName("RdfIndexApp", 1, 0, "status"))
+ .thenReturn(List.of(JsonUtils.pojoToJson(run)));
+ final CollectionDAO dao = mock(CollectionDAO.class);
+ when(dao.appExtensionTimeSeriesDao()).thenReturn(runStore);
+
+ try (MockedStatic entity = mockStatic(Entity.class)) {
+ entity.when(Entity::getCollectionDAO).thenReturn(dao);
+
+ assertEquals(RdfProjectionState.READY, RdfProjectionStateResolver.resolveConfigured());
+ }
+ }
+
@Test
void reportsDegradedForMalformedRunState() {
when(runStore.listAppExtensionByName("RdfIndexApp", 1, 0, "status"))
diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/agent/AgentSparqlServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/agent/AgentSparqlServiceTest.java
index 0b9d7e5a5fc4..4184752dacef 100644
--- a/openmetadata-service/src/test/java/org/openmetadata/service/rdf/agent/AgentSparqlServiceTest.java
+++ b/openmetadata-service/src/test/java/org/openmetadata/service/rdf/agent/AgentSparqlServiceTest.java
@@ -21,6 +21,7 @@
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
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.verifyNoInteractions;
@@ -40,6 +41,8 @@
import org.apache.jena.query.QueryFactory;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+import org.openmetadata.schema.api.configuration.rdf.RdfConfiguration;
import org.openmetadata.schema.api.rdf.AgentSparqlBinding;
import org.openmetadata.schema.api.rdf.AgentSparqlCompletenessReason;
import org.openmetadata.schema.api.rdf.AgentSparqlCompletenessStatus;
@@ -48,7 +51,13 @@
import org.openmetadata.schema.api.rdf.AgentSparqlRdfTermType;
import org.openmetadata.schema.api.rdf.AgentSparqlResponse;
import org.openmetadata.schema.api.rdf.RdfProjectionState;
+import org.openmetadata.schema.entity.app.AppRunRecord;
import org.openmetadata.schema.utils.JsonUtils;
+import org.openmetadata.service.Entity;
+import org.openmetadata.service.jdbi3.CollectionDAO;
+import org.openmetadata.service.jdbi3.TimeSeriesDAOs.AppExtensionTimeSeries;
+import org.openmetadata.service.rdf.RdfProjectionHealth;
+import org.openmetadata.service.rdf.RdfProjectionStateResolver;
import org.openmetadata.service.rdf.RdfRepository;
import org.openmetadata.service.rdf.RdfSparqlService;
import org.openmetadata.service.rdf.SparqlQueryExecutionGuard;
@@ -131,6 +140,89 @@ void emptyResultIsACompleteSuccess() {
response.getMetadata().getCompleteness().getStatus());
}
+ @Test
+ void resultCarriesTheCompletenessEmbeddedInItsBody() {
+ returnRows(1_001);
+
+ AgentSparqlResult result = readyService().execute("user", SELECT_ALL);
+
+ assertEquals(AgentSparqlCompletenessStatus.TRUNCATED, result.completeness().getStatus());
+ assertEquals(AgentSparqlCompletenessReason.SERVER_ROW_LIMIT, result.completeness().getReason());
+ }
+
+ @Test
+ void theSharedFactoryWiresTheRepositoryReadinessAndGuardTogether() {
+ returnRows(2);
+ when(repository.getConfig()).thenReturn(new RdfConfiguration());
+ AgentSparqlService wired =
+ AgentSparqlService.forRepository(() -> repository, () -> RdfProjectionState.READY);
+
+ AgentSparqlResult result = wired.execute("user", SELECT_ALL + " LIMIT 5");
+
+ assertEquals(2, result.rowCount());
+ assertEquals(AgentSparqlCompletenessStatus.COMPLETE, result.completeness().getStatus());
+ }
+
+ @Test
+ void theConfiguredResolverReadsReadinessFromTheServersRunStore() {
+ returnRows(1);
+ when(repository.getConfig()).thenReturn(new RdfConfiguration());
+ final AppExtensionTimeSeries runStore = mock(AppExtensionTimeSeries.class);
+ final AppRunRecord run = new AppRunRecord().withStatus(AppRunRecord.Status.SUCCESS);
+ when(runStore.listAppExtensionByName("RdfIndexApp", 1, 0, "status"))
+ .thenReturn(List.of(JsonUtils.pojoToJson(run)));
+ final CollectionDAO dao = mock(CollectionDAO.class);
+ when(dao.appExtensionTimeSeriesDao()).thenReturn(runStore);
+ RdfProjectionHealth.markReady();
+
+ try (MockedStatic entity = mockStatic(Entity.class)) {
+ entity.when(Entity::getCollectionDAO).thenReturn(dao);
+
+ AgentSparqlResult result =
+ AgentSparqlService.forRepository(
+ () -> repository, RdfProjectionStateResolver::resolveConfigured)
+ .execute("user", SELECT_ALL + " LIMIT 5");
+
+ assertEquals(1, result.rowCount());
+ }
+ }
+
+ @Test
+ void theSharedFactoryHonoursTheReadinessSupplierItIsGiven() {
+ when(repository.getConfig()).thenReturn(new RdfConfiguration());
+ AgentSparqlService wired =
+ AgentSparqlService.forRepository(() -> repository, () -> RdfProjectionState.REBUILDING);
+
+ assertCode(AgentSparqlErrorCode.PROJECTION_NOT_READY, () -> wired.execute("user", SELECT_ALL));
+ verify(repository, never()).executeSparqlQueryDirect(anyString(), anyString());
+ }
+
+ @Test
+ void aProjectionFailureCarriesTheStateTheResolverReported() {
+ final AgentSparqlException rebuilding =
+ assertThrows(
+ AgentSparqlException.class,
+ () -> AgentSparqlService.requireReadyProjection(() -> RdfProjectionState.REBUILDING));
+ final AgentSparqlException degraded =
+ assertThrows(
+ AgentSparqlException.class,
+ () -> AgentSparqlService.requireReadyProjection(() -> RdfProjectionState.DEGRADED));
+ final AgentSparqlException unknown =
+ assertThrows(
+ AgentSparqlException.class,
+ () ->
+ AgentSparqlService.requireReadyProjection(
+ () -> {
+ throw new IllegalStateException("run store unavailable");
+ }));
+
+ assertEquals(RdfProjectionState.REBUILDING, rebuilding.getProjectionState());
+ assertEquals(RdfProjectionState.DEGRADED, degraded.getProjectionState());
+ assertNull(unknown.getProjectionState());
+ assertEquals(AgentSparqlErrorCode.PROJECTION_NOT_READY, unknown.getCode());
+ AgentSparqlService.requireReadyProjection(() -> RdfProjectionState.READY);
+ }
+
@Test
void explicitLimitIsCompleteRelativeToTheSubmittedQuery() {
returnRows(10);