Skip to content

Feat/palantir mcp token autodiscovery - #123

Merged
nicornk merged 12 commits into
mainfrom
feat/palantir-mcp-token-autodiscovery
Nov 19, 2026
Merged

nicornk merged 12 commits into
mainfrom
feat/palantir-mcp-token-autodiscovery

Conversation

@nicornk

@nicornk nicornk commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Summary

Adds PalantirMCPTokenProvider and automatic discovery of the token Palantir MCP
caches in ~/.palantir/mcp-config.json. If no Foundry DevTools credentials are
configured, FoundryContext() now works out of the box with the Palantir MCP
token; explicit JWT/OAuth/custom credentials always take precedence.

Users who already work with Palantir MCP no longer need a second, separately
expiring Foundry credential (or a Foundry DevTools config file) just to use the
API clients.

What changed

Automatic token discovery

  • PalantirMCPTokenProvider (exported from foundry_dev_tools) reads the
    cached token, re-reads it on every access so re-authorization is picked up
    without a restart, and raises clear errors for missing/expired tokens.
  • Config fallback: when credentials are absent or incomplete,
    get_config_dict() selects a single unambiguous unexpired cached credential
    and takes host and scheme from the same entry.
  • Explicit credentials always win. Explicitly selected non-MCP providers
    never inherit a host from the MCP cache; FoundryContext(token_provider=...)
    and v1 configs with explicit credentials skip discovery entirely.
  • Multiple cached hosts: without a configured host the choice is ambiguous
    and raises a clear error asking for credentials.domain.
  • Selection is origin-exact, including the scheme: a token cached for
    https://host is never used for an http://host origin.
  • A single notice is printed to stderr the first time a token is picked up;
    adding palantir_mcp = {} to the credentials config silences it. The notice
    goes to stderr so the git credential helper's machine-readable stdout stays
    valid.
  • Palantir MCP itself always writes ~/.palantir/mcp-config.json; there is no
    custom config-path option.

Better auth / scope errors

  • Exact JWT expiry is appended to 401/403 errors for every provider.
    Expiry is decoded from the token in use without triggering an OAuth refresh
    or any network call.
  • For Palantir MCP tokens, 401 keeps the re-authorize hint, and permission
    errors list the Compass resources the token can access.
  • Foundry masks out-of-scope Compass resources as 404 Compass:NotFound
    rather than 403; that case now gets the same scoped-resource explanation.
  • Diagnostics are best-effort, bounded by short timeouts, and never replace or
    mask the original API error. Hints also survive error translation
    (FoundryAPIError.add_info() now updates the structured info field).

Docs

README and getting-started docs now present Palantir MCP token discovery as the
primary authentication path; JWT/OAuth are documented as alternatives. Docs
cover choosing a host, silencing the notice, and the re-authorization
requirement (Foundry DevTools never triggers the MCP authorization flow).
Changelog updated.

Also included

  • CI and release workflows pin Java 17 so the Spark tests keep working on newer
    runner images.

Testing

  • Unit tests cover credential selection (scheme matches, expired entries,
    multiple hosts), explicit credentials from files/profiles/environment/v1
    coexisting with an ambiguous MCP cache, and the 401/403/404 hint paths.
  • 124 non-Spark unit tests pass; Spark tests run with the Java 17 pin.
  • Docs build verified with Sphinx.

Notes for reviewers

  • No new runtime dependencies.
  • tokens are never modified; discovery only reads the cache. Re-authorization
    remains the responsibility of the Palantir MCP client.

🤖 Generated with Claude Code

Checklist

  • You agree with our CLA
  • Included tests (or is not applicable).
  • Updated documentation (or is not applicable).
  • Used pre-commit hooks to format and lint the code.

nicornk and others added 2 commits November 17, 2026 21:38
Use the token cached by Palantir MCP in ~/.palantir/mcp-config.json when
Foundry DevTools credentials do not resolve. The provider loads the host
from the same entry, warns once per process, and fails with a clear
re-authorization hint for missing or expired tokens.

For scoped MCP tokens, append the accessible Compass resources to 403
errors by combining the Multipass scope API with Compass batch name
resolution.

Co-Authored-By: Claude Code <noreply@anthropic.com>
ubuntu-latest moved to Ubuntu 26, whose JDK 24+ makes Spark 3.5's
Hadoop UserGroupInformation fail with "getSubject is not supported".
Set up Temurin 17 explicitly in the CI and release test jobs.

Co-Authored-By: Claude Code <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved credential-selection flaws can send explicit credentials to unintended deployments or transmit HTTPS-origin tokens over plaintext HTTP.

6 open issues
What changed in this PR

Adds Palantir MCP token discovery to Foundry DevTools’ configuration and authentication system, allowing cached credentials to be reused without a separate DevTools configuration.

Changes:

  • Adds a cache-backed token provider with automatic discovery, token reloads, and expiry checks.
  • Adds authentication-error diagnostics, unit tests, and configuration documentation.
  • Pins Java 17 in CI and release workflows for Spark compatibility.
File Description
tests/​unit/​utils/​test_scope.py Tests scope parsing and diagnostic hints.
tests/​unit/​utils/​test_errors.py Tests appending context to API errors.
tests/​unit/​conftest.py Isolates tests from the local MCP cache.
tests/​unit/​config/​test_palantir_mcp.py Tests discovery, token reloads, expiry, and error hints.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​utils/​scope.py Parses token scopes and builds diagnostic messages.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​errors/​meta.py Supports adding context to existing errors.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​config/​token_provider.py Implements and registers the MCP token provider.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​config/​palantir_mcp.py Reads cached credentials and selects tokens.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​config/​config.py Integrates MCP discovery into configuration loading.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​clients/​api_client.py Appends scope hints to authentication errors.
libs/​foundry-dev-tools/​src/​foundry_dev_tools/​__init__.py Exports the new provider.
docs/​configuration.md Documents discovery and explicit MCP configuration.
docs/​changelog.md Records the authentication and diagnostic additions.
.github/​workflows/​release.yml Pins Java 17 for release jobs.
.github/​workflows/​ci.yml Pins Java 17 for CI jobs.

Review effort: Balanced

nicornk and others added 5 commits November 18, 2026 13:34
- require an exact origin (scheme) match before using a cached MCP token
- never infer a host for an explicitly selected non-MCP provider
- use the configured domain during discovery and skip discovery when
  credentials are supplied explicitly
- respect union/intersection semantics when propagating universal scope
- bound scope diagnostics request timeouts
- drop the custom config_path option: Palantir MCP always writes
  ~/.palantir/mcp-config.json
- print the auto-pickup notice instead of emitting a warning and remove
  tux-specific wording from hints and docs

Co-Authored-By: Claude Code <noreply@anthropic.com>
Mention the explicit `palantir_mcp = {}` provider in the message itself and
consolidate the configuration docs to a single example with both `domain`
and `palantir_mcp` set.

Co-Authored-By: Claude Code <noreply@anthropic.com>
Co-Authored-By: Claude Code <noreply@anthropic.com>
Pin down that explicit file, profile, environment, and v1 credentials keep
working when several hosts are cached by Palantir MCP, so discovery cannot
reintroduce an ambiguity error for existing configurations.

Co-Authored-By: Claude Code <noreply@anthropic.com>
- add token_expires_at() to token providers; JWT and cached providers decode
  their token, MCP returns the cached expiry even when the token is expired,
  and none of them trigger a refresh
- append the exact expiry to 401/403 errors for any provider
- treat Compass 404 Compass:NotFound as a masked scope denial for MCP tokens
  and list the Compass resources the token can access
- remove the branch's noqa directives by using contextlib.suppress, extracting
  profile resolution, and replacing the global print flag with a notice class

Co-Authored-By: Claude Code <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

- pass the configured scheme or an explicit v1 foundry_url host into MCP
  credential discovery instead of assuming HTTPS
- write the auto-pickup notice to stderr so the git credential helper's
  machine-readable output stays valid
- keep FoundryAPIError.info in sync in add_info so translated errors retain
  scope hints
- update the README and getting-started docs to present Palantir MCP token
  discovery as the primary authentication path

Co-Authored-By: Claude Code <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Error diagnostics can report the wrong token’s expiry, misrepresent scope references as access boundaries, and delay the original failure by about 20 seconds.

2 open issues
3 previously missed issues

In code that hasn't changed since last review

Medium severity Avoid provider-specific hints for requests authenticated with another token

libs/​foundry-dev-tools/​src/​foundry_dev_tools/​clients/​api_client.py:48

With an auth override or an explicit Authorization header, a failed request may use a different token from context.token_provider. This helper then reports the wrong token's expiry or queries scope with unrelated credentials. Track whether the context provider authenticated the prepared request and skip provider-specific hints otherwise, in both API clients.

Medium severity Bound diagnostic latency with a non-retrying request path

libs/​foundry-dev-tools/​src/​foundry_dev_tools/​utils/​scope.py:122

The five-second connection timeout is applied to each of four attempts in ContextHTTPClient.request, so a diagnostic connection timeout can delay the original error by about 20 seconds. Name resolution at scope.py:103 uses the same retrying path, and these uncached diagnostics also run on ordinary Compass:NotFound responses. Use a short total diagnostic budget and a non-retrying request path, or cached scope information, to keep error handling prompt.

Medium severity Do not present flattened RIDs as an exhaustive access list

libs/​foundry-dev-tools/​src/​foundry_dev_tools/​utils/​scope.py:205

The flattened RID list is not an access boundary: includeChildren=True includes descendants, and unions can allow operations on resources absent from the list. This 404 hint therefore gives incorrect access guidance; the 403 formatter at scope.py:154–163 makes the same assumption. Describe these RIDs as scope references rather than an exhaustive access list, or preserve the full scope semantics before making permission claims.

4 resolved since last review

Review effort: Balanced

- only report Compass resource RIDs collected from /multipass/api/me/scope;
  drop operation, union/intersection, universal, and name-resolution
  assumptions, and describe the RIDs as scope references including descendants
- perform a single diagnostic request per hint instead of resolving names
- skip token hints when a caller passes a custom auth handler, since the
  request may not have been authenticated by the context token provider

Co-Authored-By: Claude Code <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed to evaluate MCP credential-origin mismatches and authentication diagnostics that may describe a different token than the one used by the failed request.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@nicornk

nicornk commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Reviewed the full main...HEAD diff (9 commits) and read the surrounding code. Four correctness issues, each reproduced against the current head:


1. Profile-specific [<profile>.config] options are silently dropped

libs/foundry-dev-tools/src/foundry_dev_tools/config/config.py:303

_resolve_profile_config already returns the inner config section, so profile_config.get("config", {}) is always {}. A profile like

[one.config]
requests_ca_bundle = "/bundle/one"

comes back as profile_config == {"requests_ca_bundle": ...}, the .get("config") misses, and the returned config has no config section. parse_general_config then yields the defaults, so the CA bundle (or cache_dir, etc.) is ignored. Reproduced with real config files: the result was {'credentials': {'domain': 'one.example', 'jwt': 'tok1'}} with the profile config missing.

2. fdt info aborts with a traceback on an ambiguous / all-expired MCP cache

libs/foundry-dev-tools/src/foundry_dev_tools/cli/info.py:219

get_config_dict now raises TokenProviderConfigError (ambiguous or all-expired MCP cache) where it previously returned None, but info calls it before entering its try block (line 228). With two valid hosts in ~/.palantir/mcp-config.json and no Foundry DevTools config, fdt info terminates with TokenProviderConfigError: Found Palantir MCP tokens for multiple Foundry hosts ... instead of rendering the config/diagnostic output — a diagnostic command failing on the exact condition it should explain. Confirmed by calling info._config_section(None) with an ambiguous cache.

3. token re-reads and re-parses the MCP file on every request, with no last-good fallback

libs/foundry-dev-tools/src/foundry_dev_tools/config/token_provider.py:345

requests_auth_handler accesses token for every HTTP request, so each API call pays a file read + json.loads + base64/JWT decode. More importantly, while Palantir MCP rewrites ~/.palantir/mcp-config.json, read_palantir_mcp_credentials can observe partial/empty JSON (OSError/ValueError → []), select returns None, and the very next request raises TokenProviderConfigError: No Palantir MCP token found ... even though a valid token was read moments earlier. Unlike the constructor path, token treats a transient read/parse problem as fatal. Caching the credential (or retrying with the last good one) would fix both.

4. Empty MCP cache with an explicit palantir_mcp provider reports "domain is missing"

libs/foundry-dev-tools/src/foundry_dev_tools/config/config.py:294

With an explicit provider and no cache file yet:

[credentials]
palantir_mcp = {}

_resolve_auto_credentials returns (None, None, "palantir_mcp"), the domain check fires, and the user gets MissingFoundryHostError: A domain is missing instead of "no Palantir MCP token is cached, re-authorize the MCP token". Reproduced: MissingFoundryHostError.

nicornk and others added 2 commits November 19, 2026 18:58
- merge profile-specific [<profile>.config] sections into the returned config
- report a missing MCP token instead of a missing domain for an explicit
  palantir_mcp provider
- cache the MCP credential until shortly before the token expires, fail early
  for tokens without a decodable expiry, and return token_expires_at from the
  cache without re-reading the file
- keep `fdt info` running when the configuration cannot be loaded and print
  the token TTL for every provider that knows it
- share the origin parser between the MCP cache reader and the v1 config bridge

Co-Authored-By: Claude Code <noreply@anthropic.com>
The credentials table renders every provider attribute, so the cached
credential and its refresh deadline showed up as masked rows. They are
internal state, not credential configuration, so skip them and keep the
host and token TTL rows.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@nicornk

nicornk commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Status update — the four findings from the review above are addressed in 6ff61b0 and 64e4dc7.

1. Profile [<profile>.config] options dropped — fixed.
_resolve_profile_config already returns the inner config section, so it is now merged directly instead of profile_config.get("config", {}). Regression test: tests/unit/config/test_config.py::test_profile_config_section_is_merged.

2. fdt info traceback — fixed.
Configuration loading/parsing now runs inside the section's error handling, so an ambiguous or all-expired MCP cache (or a v1 config) renders Could not load the Foundry DevTools configuration. with the underlying error instead of aborting the diagnostic command. Test: tests/unit/cli/test_info.py::test_info_cli_reports_configuration_errors.

3. Per-request file reads — fixed with an expiry-based in-memory cache.
The credential is kept in memory and re-read only 60s before the token's decoded exp (_credential_refresh_skew), so a re-authorization is still picked up without a restart but routine API calls no longer touch the file. token_expires_at() now returns the cached expiry and never reads disk. Per the review decision, there is no last-good fallback: tokens without a decodable exp, and a missing/unreadable cache on refresh, fail immediately. Tests cover reuse, refresh timing, opaque tokens, and unreadable files.

4. Empty cache with explicit palantir_mcp — fixed.
With palantir_mcp = {} and no cached token, config loading now raises No Palantir MCP token found in <path>. Re-authorize the Palantir MCP token... instead of MissingFoundryHostError: A domain is missing. Test added.

Additional cleanups

  • _discovery_host now reuses palantir_mcp.host_from_origin, so the v1 config bridge and the MCP cache reader agree on what counts as a valid origin.
  • fdt info prints a token_ttl row for every provider that reports an expiry, and no longer shows MCP provider internals (credential, credential_stale_after) as masked rows.

Deliberately not changed

  • Scope diagnostics remain uncached: the /multipass/api/me/scope call is fast, so the extra request per failed lookup is not a concern.
  • Known non-blockers still open: the 30s expiry skew can produce an "expired at" timestamp slightly in the future, and the scope hint does not honor per-resource includeChildren. Happy to address those separately if wanted.

Verification: full unit suite green (183 passed) and ruff clean.

When a Palantir MCP token is picked up automatically, the one-time notice
now points at `fdt config init`. The command writes the minimal
configuration (domain, scheme when non-default, and the palantir_mcp
provider) to ~/.foundry-dev-tools/config.toml, refuses to overwrite an
existing configuration, and explains what is missing when no cached token
is available.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@nicornk
nicornk merged commit f60193b into main Nov 19, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants