Skip to content

Fixes #34270: Make the MCP knowledge-graph tools usable by non-admins for column lineage at scale - #34790

Merged
fmcardoso merged 42 commits into
mainfrom
fmcardoso/mcp-knowledge-graph-tools-non-admin-access-and-c
Oct 14, 2026
Merged

fmcardoso merged 42 commits into
mainfrom
fmcardoso/mcp-knowledge-graph-tools-non-admin-access-and-c

Conversation

@fmcardoso

@fmcardoso fmcardoso commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Describe your changes:

Fixes #34270

The MCP server has had knowledge-graph tools since #28042, but only administrators could call them, so in practice no MCP user, and no bot token, could ask the graph anything. One customer needed the full column lineage of a column (4,523 edges). get_entity_lineage clipped it to 139, and the graph tools were closed to them.

This PR makes those tools usable for that question:

  1. access: ExecuteSparqlQuery instead of admin-only;
  2. a restricted read-only query profile for non-admins;
  3. guidance and proof: the sparql_query description teaches paging and the column-lineage query, and multi-hop traversal is verified at about 5,000 column mappings.

Where RDF is off the graph tools are not offered at all (see "Done when (c)" below).

It extends the existing RDF MCP tools in the shared OpenMetadata implementation, which Collate's MCP server (CollateMcpServer extends McpServer) also uses, so the change reaches Collate and OSS users alike. It does not touch get_entity_lineage (separate MCP work) or asset-level SPARQL RBAC (#33224).

What changes

Tool Access now
sparql_query ExecuteSparqlQuery; non-admins get the agent profile, admins keep today's behavior unchanged
entity_neighborhood, find_by_tag ExecuteSparqlQuery
ontology_describe without resource no check (same static file as unauthenticated GET /v1/rdf/ontology)
ontology_describe with resource ExecuteSparqlQuery
shacl_validate admin only, unchanged (fullGraph=true loads up to 100k triples)

Non-admin sparql_query: SELECT only, JSON output, inference forced to none, no FROM/GRAPH/SERVICE/CALL/java:, projection must be READY before and after execution, an audit event per call that passes authorization, attributed to the MCP bot as service actor (refusals are logged by the MCP layer's authorization handling), and a completeness field on the result. find_by_tag, entity_neighborhood and ontology_describe(resource) apply the same READY check for non-admins; admins are unchanged. These three tools check readiness before the read only (ADR A3). Bot tokens have no special case, but by default every bot holds the grant: POST /v1/users with isBot=true attaches DefaultBotRole, which includes DataConsumerPolicy, which ships DataConsumerPolicy-ExecuteSparqlQuery-Rule (#34253). A bot loses access only if that rule is removed or a policy denies the operation.

The sparql_query description now carries the column-lineage template (column-IRI om:fromColumn/om:toColumn form since #34970, paging, asset-type/service/owner/tier filters). Data-model facts only, no agent routing strategy. A vocabulary test pins every om: term it uses against the ontology and the live projection.

Done when (c), RDF off: with RDF off the graph tools (sparql_query, entity_neighborhood, find_by_tag, shacl_validate) are not offered in tools/list (existing gating, unchanged), and a direct call is refused by the SDK before the server's tool code runs. ontology_describe stays offered, and ontology_describe(resource) answers 400 "RDF knowledge graph is not enabled" (covered by McpRdfNotEnabledIT).

Behavior changes beyond the RDF tools:

  • DefaultToolContext now classifies QueryCapacityException (and the new retry-later exception) as 429 for every MCP tool, the administrator path of sparql_query included. It was 500 before.
  • Admins keep today's sparql_query behavior; their call goes through the old code path unchanged.

Type of change:

  • Bug fix
  • Improvement
  • New feature
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation

High-level design:

  • Authorization: RdfMcpTool.execute stays final and calls an overridable authorize hook. The default requires ExecuteSparqlQuery on the RDF resource (reusing RdfQueryResourceContext); shacl_validate overrides it back to admin, and ontology_describe skips it when no resource is given. Authorization runs before the RDF-enabled check, so an unauthorized caller learns nothing about deployment configuration.
  • Non-admin execution: SparqlQueryTool picks the profile from DefaultAuthorizer.getSubjectContext(...).isAdmin(), the same definition authorizeAdmin uses and the pattern other MCP tools already follow; the admin branch is the previous code. Non-admins go through AgentSparqlService.forRepository(...), a new shared factory that RdfResource also uses, so the REST endpoint and MCP share one execution profile, guard and audit path.
  • Errors: query-shape rejections and the oversize result map to 400; federation attempts to 403; capacity and repository unavailable to 429 "Retry shortly."; projection not ready depends on its state: rebuilding (or no run recorded yet) is a retryable 429 ("retry later; if it persists, an administrator needs to run RdfIndexApp"), degraded is a 400 in the same bucket as "RDF not enabled" ("an administrator must run a full RdfIndexApp rebuild"), because a degraded projection only clears after a full rebuild and retrying would loop; execution timeout to 504. The REST endpoint's 503 mapping is unchanged. Both are recorded in ADR A3.
  • Column lineage at scale: since Fixes 34969: Correct inference rule inputs and materialize rules to a fixed point #34970, om:fromColumn/om:toColumn reference column IRIs (FQNs are in om:fromColumnFqn/om:toColumnFqn), so traversal binds the start column by om:fullyQualifiedName, walks ^om:fromColumn/om:toColumn and the asset join is the inverse path ?c (^om:hasChildColumn)*/^om:hasColumn ?asset (the forward form measured ~6.6 s/page vs ~50 ms). Published page size is 250 rows (400 rows overflowed the 80,000-byte MCP body).
  • Freshness: since Fixes 34969: Correct inference rule inputs and materialize rules to a fixed point #34970, live PUT /v1/lineage writes and RdfIndexApp both project column mappings. A store indexed before 2.1 keeps literal endpoints until it is rebuilt, so the tool text tells clients that an empty result there does not prove there is no lineage.
  • Accepted risk: without asset-level filtering (Add asset-level RBAC for read-only SPARQL queries #33224), a user with ExecuteSparqlQuery can see aggregates over assets they cannot otherwise view. Same decision as the agent endpoint (Add permissioned read-only SPARQL execution for the 2.1 graph agent tool #33384/Fixes #34231: grant ExecuteSparqlQuery to the Data Consumer role by default #34253); recorded in the ADR amendment "MCP knowledge-graph tools (MCP knowledge-graph tools: non-admin access and column-level lineage at scale #34270)".
  • Alternatives rejected: gating on Add asset-level RBAC for read-only SPARQL queries #33224 first (blocks the customer case); a separate column-lineage tool (duplicates SPARQL, more surface); changing the live-write projection (out of scope, risky).
  • Docs: ADR amendment A1–A8 and a "Column lineage" section in docs/rdf-ontology-contract.md.

Known limitation (pre-existing, tracked in #34826): removing ExecuteSparqlQuery from a policy may not take effect for a principal whose first request after the edit arrives via /mcp. With the default cache provider none, a local run saw the principal stay allowed for at least 171 s while the policy row and API already had the rule removed, and REST and GET /v1/permissions/rdf then also reported allow; an explicit SubjectCache.invalidateAll() ended it. This is the existing policy-cache behavior (the in-transaction SubjectCache.invalidateAll() in PolicyRepository); this PR does not change it, and it is not shown to be specific to MCP. The "no grant" ITs work around it: RdfAccessFixtures reads the test principals' permissions right after each policy edit (see its Javadoc).

Release note: with the #34253 default grant, the MCP graph tools (sparql_query, entity_neighborhood, find_by_tag, ontology_describe with a resource) are open to every user and bot, and results are not filtered by asset or domain policies (ADR A5). Admins who rely on deny or domain policies for metadata confidentiality should remove DataConsumerPolicy-ExecuteSparqlQuery-Rule; because of #34826 that removal can lag for principals already active over MCP. The rule's description now says which tools it covers; existing installs get the text through an appended, description-only statement in the 2.1.0 migration, and the shipped INSERT is left untouched. After upgrading to 2.1, run a full RdfIndexApp rebuild (recreateIndex=true) so column lineage written before the upgrade uses column IRIs; until then the published column-lineage query can miss those edges.

Scope note for reviewers: #34270's checklist includes a "Benchmark" item (a column-lineage row in ai-platform's collate_graph_routing_v1.tsv). That item is moved out of this PR's scope, so there is no companion ai-platform PR. That benchmark measures how the Collate agent routes between getLineage and the graph, not MCP; the MCP capability is proven by RdfMcpKnowledgeGraphIT (a regular user pages all 5,006 column links). The row would be meaningful together with the Collate routing rule, which is separate work, and adding it changes a pinned benchmark contract and invalidates saved baselines.

Tests:

Use cases covered

  • Admin, granted non-admin, ungranted user and bot token (with and without the policy) against each tool.
  • Complete downstream and upstream column lineage from one column over several hops, with rename hops, multi-source nodes and a cycle, paged without duplicates or gaps.
  • Scale: 5,006 column mappings, 2,705 reachable columns paged over 11 pages (49–230 ms/page, ~51 KB/page).
  • Asset-type filter (drops the data-model hop, keeps nested columns on their table).
  • Oversize page returns a truncated result and recovery by lowering the page size.
  • Query rejections (non-SELECT, federation, inference level, non-JSON format, blocked SERVICE).
  • RDF off: the four graph tools are withheld from tools/list and refused on direct call; ontology_describe with a resource returns 400 "RDF knowledge graph is not enabled".
  • Real reindex: om:hasChildColumn (struct columns) is materialized by an actual RdfIndexApp run.

Unit tests

  • I added unit tests for the new/changed logic.
  • Files: RdfColumnLineageTraversalTest, ColumnLineageFixture (shared fixture built by the two production writers), RdfToolDescriptionVocabularyTest, SparqlQueryToolAgentProfileTest, AgentSparqlToolErrorsTest, RdfToolAuthorization (helper), updates to SparqlQueryToolTest, ShaclValidateToolTest, FindByTagToolTest, EntityNeighborhoodToolTest, OntologyDescribeToolTest, DefaultToolContextTest, AgentSparqlServiceTest, RdfProjectionStateResolverTest.
  • Coverage on changed classes (measured before the final rebase): 89–100%.
  • CI on e01ac33c2e: the openmetadata-service unit suite, 11,517 tests, 0 failures, 1 skipped, which includes DataConsumerSparqlGrantSqlMigrationTest 28/28 against MySQL 8 and Postgres 15 and FlowableCharsetMigrationTest 6/6. Locally the whole openmetadata-mcp module, 765 tests, 0 failures; mvn spotless:check on openmetadata-service, openmetadata-mcp and openmetadata-integration-tests is clean.

Backend integration tests

  • I added integration tests in openmetadata-integration-tests/ for new/changed API endpoints.
  • Files: RdfMcpKnowledgeGraphIT (21), McpRdfNotEnabledIT (4), shared RdfAccessFixtures; AgentSparqlResourceIT (22) re-run because RdfResource now shares the new factory.
  • Status: CI on e01ac33c2e is 86 pass, 0 fail (22 skipped). In the RDF lane, on MySQL + Elasticsearch (job) and on PostgreSQL + OpenSearch (job), RdfMcpKnowledgeGraphIT ran 21/21 and AgentSparqlResourceIT 22/22. McpRdfNotEnabledIT ran 4/4 locally (-Ppostgres-opensearch) on an earlier head.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Manual testing performed

No manual UI testing; the change has no UI. Verification was through the integration tests above, which run a real RDF store (Fuseki), a real MCP endpoint and real reindexing. Reproduce locally:

  1. mvn -pl openmetadata-integration-tests verify -Ppostgres-rdf-tests -Dit.test='RdfMcpKnowledgeGraphIT,AgentSparqlResourceIT'
  2. mvn -pl openmetadata-integration-tests verify -Ppostgres-opensearch -Dit.test='McpRdfNotEnabledIT'

(The IT module needs openmetadata-spec, -sdk, -service and -mcp installed into the local Maven repository first.)

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: N/A, no schema changes.
  • For UI changes: N/A, no UI changes.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • I have added tests around the new logic.
  • The issue properly describes why the new feature is needed, what's the goal, and how we are building it.
  • I have updated the documentation (ADR amendment, ontology contract).

@fmcardoso fmcardoso self-assigned this Oct 6, 2026
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Hi there 👋 Thanks for your contribution!

The OpenMetadata team will review the PR shortly! Once it has been labeled as safe to test, the CI workflows
will start executing and we'll be able to make sure everything is working as expected.

Let us know if you need any help!

@fmcardoso
fmcardoso added this pull request to the merge queue Oct 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-10-08T17:30:30Z)

Blocked the queue: py-tests-status, py-tests-status

@fmcardoso
fmcardoso added this pull request to the merge queue Oct 8, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-10-08T21:53:31Z)

Blocked the queue: playwright-summary

Failed Playwright tests:

  • Pages/IngestionLogStreamLive.spec.ts › Live logs arrive over SSE while the agent runs, with no polling

…rebuilt since 2.1 does not prove there is no lineage
@gitar-bot

gitar-bot Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved 1 closed / 1 findings

🔴 High risk · Granting MCP graph reads under the default ExecuteSparqlQuery policy could reveal unfiltered metadata about assets users cannot otherwise view.

Makes the MCP knowledge-graph tools (sparql_query, entity_neighborhood, find_by_tag, ontology_describe with a resource) usable by non-admins, with a restricted read-only query profile for non-admin sparql_query calls and a column-lineage query template. Resolved the MCP agent-profile audit logging a null service actor, so audit events are now attributed to the MCP bot. No issues found.

✅ 1 closed
✅ Quality: MCP agent-profile audit always logs serviceActor=null

📄 openmetadata-mcp/src/main/java/org/openmetadata/mcp/tools/SparqlQueryTool.java:205-215
McpServer calls ImpersonationContext.setImpersonatedBy(getMcpBotName()) around every tool call. But runAgentQuery builds AgentSparqlCaller.of(principal, null), so every agent_sparql_query audit line from MCP logs serviceActor=null. The REST endpoint (RdfResource.agentSparqlCaller) reads ImpersonationContext.getImpersonatedBy() and CatalogSecurityContext.impersonatedUser() so the audit records the bot behind the call. That means MCP-originated queries can't be told apart from direct REST calls in the audit log, even though the PR says both paths share one audit path. Fix: resolve the service actor the same way the REST endpoint does.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@fmcardoso
fmcardoso enabled auto-merge October 13, 2026 09:39
@fmcardoso
fmcardoso added this pull request to the merge queue Oct 13, 2026
@sonarqubecloud

Copy link
Copy Markdown

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Oct 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — failed_checks (2026-10-13T16:09:02Z)

Blocked the queue: integration-tests-postgres-opensearch

@fmcardoso
fmcardoso added this pull request to the merge queue Oct 13, 2026
Merged via the queue into main with commit 77e23a2 Oct 14, 2026
85 checks passed
@fmcardoso
fmcardoso deleted the fmcardoso/mcp-knowledge-graph-tools-non-admin-access-and-c branch October 14, 2026 04:51

This branch was previously deployed

1 inactive deployment
test — 5596ca55 Deployed Oct 13, 2026 by fmcardoso via RDF Playwright execution #30616
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP knowledge-graph tools: non-admin access and column-level lineage at scale

2 participants