Claude Code skill pack for Palantir (24 skills)
Installation
Open Claude Code and run this command:
/plugin install palantir-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
Skills (24)
Configure Palantir CI/CD integration with GitHub Actions and testing.
Palantir CI Integration
Overview
Set up CI/CD pipelines for Palantir integrations with automated testing.
Prerequisites
- GitHub repository with Actions enabled
- Palantir test API key
- npm/pnpm project configured
Instructions
Step 1: Create GitHub Actions Workflow
Create .github/workflows/palantir-integration.yml:
name: Palantir Integration Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
PALANTIR_API_KEY: ${{ secrets.PALANTIR_API_KEY }}
jobs:
test:
runs-on: ubuntu-latest
env:
PALANTIR_API_KEY: ${{ secrets.PALANTIR_API_KEY }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run test:integration
Step 2: Configure Secrets
gh secret set PALANTIR_API_KEY --body "sk_test_***"
Step 3: Add Integration Tests
describe('Palantir Integration', () => {
it.skipIf(!process.env.PALANTIR_API_KEY)('should connect', async () => {
const client = getPalantirClient();
const result = await client.healthCheck();
expect(result.status).toBe('ok');
});
});
Output
- Automated test pipeline
- PR checks configured
- Coverage reports uploaded
- Release workflow ready
Error Handling
| Issue | Cause | Solution |
|---|---|---|
| Secret not found | Missing configuration | Add secret via gh secret set |
| Tests timeout | Network issues | Increase timeout or mock |
| Auth failures | Invalid key | Check secret value |
Examples
Release Workflow
on:
push:
tags: ['v*']
jobs:
release:
runs-on: ubuntu-latest
env:
PALANTIR_API_KEY: ${{ secrets.PALANTIR_API_KEY_PROD }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- name: Verify Palantir production readiness
run: npm run test:integration
- run: npm run build
- run: npm publish
Branch Protection
required_status_checks:
- "test"
- "palantir-integration"
Resources
Next Steps
For deployment patterns, s
Diagnose and fix Palantir common errors and exceptions.
Palantir Common Errors
Overview
Quick reference for the top 10 most common Palantir errors and their solutions.
Prerequisites
- Palantir SDK installed
- API credentials configured
- Access to error logs
Instructions
Step 1: Identify the Error
Check error message and code in your logs or console.
Step 2: Find Matching Error Below
Match your error to one of the documented cases.
Step 3: Apply Solution
Follow the solution steps for your specific error.
Output
- Identified error cause
- Applied fix
- Verified resolution
Error Handling
Authentication Failed
Error Message:
Authentication error: Invalid API key
Cause: API key is missing, expired, or invalid.
Solution:
# Verify API key is set
echo $PALANTIR_API_KEY
Rate Limit Exceeded
Error Message:
Rate limit exceeded. Please retry after X seconds.
Cause: Too many requests in a short period.
Solution:
Implement exponential backoff. See palantir-rate-limits skill.
Network Timeout
Error Message:
Request timeout after 30000ms
Cause: Network connectivity or server latency issues.
Solution:
// Increase timeout
const client = new Client({ timeout: 60000 });
Examples
Quick Diagnostic Commands
# Check Palantir status
curl -s https://status.palantir.com
# Verify API connectivity
curl -I https://api.palantir.com
# Check local configuration
env | grep PALANTIR
Escalation Path
- Collect evidence with
palantir-debug-bundle - Check Palantir status page
- Contact support with request ID
Resources
Next Steps
For comprehensive debugging, see palantir-debug-bundle.
Execute Palantir primary workflow: Core Workflow A.
Palantir Core Workflow A
Overview
Primary money-path workflow for Palantir. This is the most common use case.
Prerequisites
- Completed
palantir-install-authsetup - Understanding of Palantir core concepts
- Valid API credentials configured
Instructions
Step 1: Initialize
// Step 1 implementation
Step 2: Execute
// Step 2 implementation
Step 3: Finalize
// Step 3 implementation
Output
- Completed Core Workflow A execution
- Expected results from Palantir API
- Success confirmation or error details
Error Handling
| Error | Cause | Solution |
|---|---|---|
| Error 1 | Cause | Solution |
| Error 2 | Cause | Solution |
Examples
Complete Workflow
// Complete workflow example
Common Variations
- Variation 1: Description
- Variation 2: Description
Resources
Next Steps
For secondary workflow, see palantir-core-workflow-b.
Execute Palantir secondary workflow: Core Workflow B.
Palantir Core Workflow B
Overview
Secondary workflow for Palantir. Complements the primary workflow.
Prerequisites
- Completed
palantir-install-authsetup - Familiarity with
palantir-core-workflow-a - Valid API credentials configured
Instructions
Step 1: Setup
// Step 1 implementation
Step 2: Process
// Step 2 implementation
Step 3: Complete
// Step 3 implementation
Output
- Completed Core Workflow B execution
- Results from Palantir API
- Success confirmation or error details
Error Handling
| Aspect | Workflow A | Workflow B |
|---|---|---|
| Use Case | Primary | Secondary |
| Complexity | Medium | Lower |
| Performance | Standard | Optimized |
Examples
Complete Workflow
// Complete workflow example
Error Recovery
// Error handling code
Resources
Next Steps
For common errors, see palantir-common-errors.
Optimize Palantir costs through tier selection, sampling, and usage monitoring.
Palantir Cost Tuning
Overview
Optimize Palantir costs through smart tier selection, sampling, and usage monitoring.
Prerequisites
- Access to Palantir billing dashboard
- Understanding of current usage patterns
- Database for usage tracking (optional)
- Alerting system configured (optional)
Pricing Tiers
| Tier | Monthly Cost | Included | Overage |
|---|---|---|---|
| Free | $0 | 1,000 requests | N/A |
| Pro | $99 | 100,000 requests | $0.001/request |
| Enterprise | Custom | Unlimited | Volume discounts |
Cost Estimation
interface UsageEstimate {
requestsPerMonth: number;
tier: string;
estimatedCost: number;
recommendation?: string;
}
function estimatePalantirCost(requestsPerMonth: number): UsageEstimate {
if (requestsPerMonth <= 1000) {
return { requestsPerMonth, tier: 'Free', estimatedCost: 0 };
}
if (requestsPerMonth <= 100000) {
return { requestsPerMonth, tier: 'Pro', estimatedCost: 99 };
}
const proOverage = (requestsPerMonth - 100000) * 0.001;
const proCost = 99 + proOverage;
return {
requestsPerMonth,
tier: 'Pro (with overage)',
estimatedCost: proCost,
recommendation: proCost > 500
? 'Consider Enterprise tier for volume discounts'
: undefined,
};
}
Usage Monitoring
class PalantirUsageMonitor {
private requestCount = 0;
private bytesTransferred = 0;
private alertThreshold: number;
constructor(monthlyBudget: number) {
this.alertThreshold = monthlyBudget * 0.8; // 80% warning
}
track(request: { bytes: number }) {
this.requestCount++;
this.bytesTransferred += request.bytes;
if (this.estimatedCost() > this.alertThreshold) {
this.sendAlert('Approaching Palantir budget limit');
}
}
estimatedCost(): number {
return estimatePalantirCost(this.requestCount).estimatedCost;
}
private sendAlert(message: string) {
// Send to Slack, email, PagerDuty, etc.
}
}
Cost Reduction Strategies
Step 1: Request Sampling
function shouldSample(samplingRate = 0.1): boolean {
return Math.random() < samplingRate;
}
// Use for non-critical telemetry
if (shouldSample(0.1)) { // 10% sample
await palantirClient.trackEvent(event);
}
Step 2: Batching Requests
// Instead of N individual calls
await Promise.all(ids.map(id => palantirClient.get(id)));
// Use batch endpoint (1 call)
await palantirClient.batchGet(ids);
Step 3: Caching (from P16)
- Cache frequently accessed data
- Use
Implement Palantir PII handling, data retention, and GDPR/CCPA compliance patterns.
Palantir Data Handling
Overview
Handle sensitive data correctly when integrating with Palantir.
Prerequisites
- Understanding of GDPR/CCPA requirements
- Palantir SDK with data export capabilities
- Database for audit logging
- Scheduled job infrastructure for cleanup
Data Classification
| Category | Examples | Handling |
|---|---|---|
| PII | Email, name, phone | Encrypt, minimize |
| Sensitive | API keys, tokens | Never log, rotate |
| Business | Usage metrics | Aggregate when possible |
| Public | Product names | Standard handling |
PII Detection
const PII_PATTERNS = [
{ type: 'email', regex: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g },
{ type: 'phone', regex: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g },
{ type: 'ssn', regex: /\b\d{3}-\d{2}-\d{4}\b/g },
{ type: 'credit_card', regex: /\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g },
];
function detectPII(text: string): { type: string; match: string }[] {
const findings: { type: string; match: string }[] = [];
for (const pattern of PII_PATTERNS) {
const matches = text.matchAll(pattern.regex);
for (const match of matches) {
findings.push({ type: pattern.type, match: match[0] });
}
}
return findings;
}
Data Redaction
function redactPII(data: Record<string, any>): Record<string, any> {
const sensitiveFields = ['email', 'phone', 'ssn', 'password', 'apiKey'];
const redacted = { ...data };
for (const field of sensitiveFields) {
if (redacted[field]) {
redacted[field] = '[REDACTED]';
}
}
return redacted;
}
// Use in logging
console.log('Palantir request:', redactPII(requestData));
Data Retention Policy
Retention Periods
| Data Type | Retention | Reason |
|---|---|---|
| API logs | 30 days | Debugging |
| Error logs | 90 days | Root cause analysis |
| Audit logs | 7 years | Compliance |
| PII | Until deletion request | GDPR/CCPA |
Automatic Cleanup
async function cleanupPalantirData(retentionDays: number): Promise<void> {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - retentionDays);
await db.palantirLogs.deleteMany({
createdAt: { $lt: cutoff },
type: { $nin: ['audit', 'compliance'] },
});
}
// Schedule daily cleanup
cron.schedule('0 3 * * *', () => cleanupPalantirData(30)Collect Palantir debug evidence for support tickets and troubleshooting.
Palantir Debug Bundle
Overview
Collect all necessary diagnostic information for Palantir support tickets.
Prerequisites
- Palantir SDK installed
- Access to application logs
- Permission to collect environment info
Instructions
Step 1: Create Debug Bundle Script
#!/bin/bash
# palantir-debug-bundle.sh
BUNDLE_DIR="palantir-debug-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BUNDLE_DIR"
echo "=== Palantir Debug Bundle ===" > "$BUNDLE_DIR/summary.txt"
echo "Generated: $(date)" >> "$BUNDLE_DIR/summary.txt"
Step 2: Collect Environment Info
# Environment info
echo "--- Environment ---" >> "$BUNDLE_DIR/summary.txt"
node --version >> "$BUNDLE_DIR/summary.txt" 2>&1
npm --version >> "$BUNDLE_DIR/summary.txt" 2>&1
echo "PALANTIR_API_KEY: ${PALANTIR_API_KEY:+[SET]}" >> "$BUNDLE_DIR/summary.txt"
Step 3: Gather SDK and Logs
# SDK version
npm list @palantir/sdk 2>/dev/null >> "$BUNDLE_DIR/summary.txt"
# Recent logs (redacted)
grep -i "palantir" ~/.npm/_logs/*.log 2>/dev/null | tail -50 >> "$BUNDLE_DIR/logs.txt"
# Configuration (redacted - secrets masked)
echo "--- Config (redacted) ---" >> "$BUNDLE_DIR/summary.txt"
cat .env 2>/dev/null | sed 's/=.*/=***REDACTED***/' >> "$BUNDLE_DIR/config-redacted.txt"
# Network connectivity test
echo "--- Network Test ---" >> "$BUNDLE_DIR/summary.txt"
echo -n "API Health: " >> "$BUNDLE_DIR/summary.txt"
curl -s -o /dev/null -w "%{http_code}" https://api.palantir.com/health >> "$BUNDLE_DIR/summary.txt"
echo "" >> "$BUNDLE_DIR/summary.txt"
Step 4: Package Bundle
tar -czf "$BUNDLE_DIR.tar.gz" "$BUNDLE_DIR"
echo "Bundle created: $BUNDLE_DIR.tar.gz"
Output
palantir-debug-YYYYMMDD-HHMMSS.tar.gzarchive containing:summary.txt- Environment and SDK infologs.txt- Recent redacted logsconfig-redacted.txt- Configuration (secrets removed)
Error Handling
| Item | Purpose | Included | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Environment versions | Compatibility check | ✓ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| SDK version | Version-specific bugs | ✓ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Error logs (redacted) | Root cause analysis | ✓ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Config (redacted) | Configuration issues | ✓ | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Role | Permissions | Use Case |
|---|---|---|
| Admin | Full access | Platform administrators |
| Developer | Read/write, no delete | Active development |
| Viewer | Read-only | Stakeholders, auditors |
| Service | API access only | Automated systems |
Role Implementation
enum PalantirRole {
Admin = 'admin',
Developer = 'developer',
Viewer = 'viewer',
Service = 'service',
}
interface PalantirPermissions {
read: boolean;
write: boolean;
delete: boolean;
admin: boolean;
}
const ROLE_PERMISSIONS: Record<PalantirRole, PalantirPermissions> = {
admin: { read: true, write: true, delete: true, admin: true },
developer: { read: true, write: true, delete: false, admin: false },
viewer: { read: true, write: false, delete: false, admin: false },
service: { read: true, write: true, delete: false, admin: false },
};
function checkPermission(
role: PalantirRole,
action: keyof PalantirPermissions
): boolean {
return ROLE_PERMISSIONS[role][action];
}
SSO Integration
SAML Configuration
// Palantir SAML setup
const samlConfig = {
entryPoint: 'https://idp.company.com/saml/sso',
issuer: 'https://palantir.com/saml/metadata',
cert: process.env.SAML_CERT,
callbackUrl: 'https://app.yourcompany.com/auth/palantir/callback',
};
// Map IdP groups to Palantir roles
const groupRoleMapping: Record<string, PalantirRole> = {
'Engineering': PalantirRole.Developer,
'Platform-Admins': PalantirRole.Admin,
'Data-Team': PalantirRole.Viewer,
};
OAuth2/OIDC Integration
import { OAuth2Client } from '@palantir/sdk';
const oauthClient = new OAuth2Client({
clientId: process.env.PALANTIR_OAUTH_CLIENT_ID!,
clientSecret: process.env.PALANTIR_OAUTH_CLIENT_SECRET!,
redirectUri: 'https://app.yourcompany.com/auth/palantir/callback',
scopes: ['read', 'write'],
});
Organization Management
interface PalantirOrganization {
id: string;
name: string;
ssoEnabled: boolean;
enforceSso: boolean;
allowedDomains: string[];
defaultRole: PalantirRole;
}
async function createOrganization(
config: PalantirOrganization
): Promise<void> {
Create a minimal working Palantir example.
Palantir Hello World
Overview
Minimal working example demonstrating core Palantir functionality.
Prerequisites
- Completed
palantir-install-authsetup - Valid API credentials configured
- Development environment ready
Instructions
Step 1: Create Entry File
Create a new file for your hello world example.
Step 2: Import and Initialize Client
import { PalantirClient } from '@palantir/sdk';
const client = new PalantirClient({
apiKey: process.env.PALANTIR_API_KEY,
});
Step 3: Make Your First API Call
async function main() {
// Your first API call here
}
main().catch(console.error);
Output
- Working code file with Palantir client initialization
- Successful API response confirming connection
- Console output showing:
Success! Your Palantir connection is working.
Error Handling
| Error | Cause | Solution |
|---|---|---|
| Import Error | SDK not installed | Verify with npm list or pip show |
| Auth Error | Invalid credentials | Check environment variable is set |
| Timeout | Network issues | Increase timeout or check connectivity |
| Rate Limit | Too many requests | Wait and retry with exponential backoff |
Examples
TypeScript Example
import { PalantirClient } from '@palantir/sdk';
const client = new PalantirClient({
apiKey: process.env.PALANTIR_API_KEY,
});
async function main() {
// Your first API call here
}
main().catch(console.error);
Python Example
from palantir import PalantirClient
client = PalantirClient()
# Your first API call here
Resources
Next Steps
Proceed to palantir-local-dev-loop for development workflow setup.
Execute Palantir incident response procedures with triage, mitigation, and postmortem.
Palantir Incident Runbook
Overview
Rapid incident response procedures for Palantir-related outages.
Prerequisites
- Access to Palantir dashboard and status page
- kubectl access to production cluster
- Prometheus/Grafana access
- Communication channels (Slack, PagerDuty)
Severity Levels
| Level | Definition | Response Time | Examples |
|---|---|---|---|
| P1 | Complete outage | < 15 min | Palantir API unreachable |
| P2 | Degraded service | < 1 hour | High latency, partial failures |
| P3 | Minor impact | < 4 hours | Webhook delays, non-critical errors |
| P4 | No user impact | Next business day | Monitoring gaps |
Quick Triage
# 1. Check Palantir status
curl -s https://status.palantir.com | jq
# 2. Check our integration health
curl -s https://api.yourapp.com/health | jq '.services.palantir'
# 3. Check error rate (last 5 min)
curl -s localhost:9090/api/v1/query?query=rate(palantir_errors_total[5m])
# 4. Recent error logs
kubectl logs -l app=palantir-integration --since=5m | grep -i error | tail -20
Decision Tree
Palantir API returning errors?
├─ YES: Is status.palantir.com showing incident?
│ ├─ YES → Wait for Palantir to resolve. Enable fallback.
│ └─ NO → Our integration issue. Check credentials, config.
└─ NO: Is our service healthy?
├─ YES → Likely resolved or intermittent. Monitor.
└─ NO → Our infrastructure issue. Check pods, memory, network.
Immediate Actions by Error Type
401/403 - Authentication
# Verify API key is set
kubectl get secret palantir-secrets -o jsonpath='{.data.api-key}' | base64 -d
# Check if key was rotated
# → Verify in Palantir dashboard
# Remediation: Update secret and restart pods
kubectl create secret generic palantir-secrets --from-literal=api-key=NEW_KEY --dry-run=client -o yaml | kubectl apply -f -
kubectl rollout restart deployment/palantir-integration
429 - Rate Limited
# Check rate limit headers
curl -v https://api.palantir.com 2>&1 | grep -i rate
# Enable request queuing
kubectl set env deployment/palantir-integration RATE_LIMIT_MODE=queue
# Long-term: Contact Palantir for limit increase
500/503 - Palantir Errors
# Enable graceful degradation
kubectl set env deployment/palantir-integration PALANTIR_FALLBACK=true
# Notify users of degraded service
# Update status page
# Monitor Palantir status for resolution
Communication Templates
Internal (Slack)
🔴 P1 INCIDENT: Palantir Integration
Status: INVESTIGATInstall and configure Palantir SDK/CLI authentication.
Palantir Install & Auth
Overview
Set up Palantir SDK/CLI and configure authentication credentials.
Prerequisites
- Node.js 18+ or Python 3.10+
- Package manager (npm, pnpm, or pip)
- Palantir account with API access
- API key from Palantir dashboard
Instructions
Step 1: Install SDK
# Node.js
npm install @palantir/sdk
# Python
pip install palantir
Step 2: Configure Authentication
# Set environment variable
export PALANTIR_API_KEY="your-api-key"
# Or create .env file
echo 'PALANTIR_API_KEY=your-api-key' >> .env
Step 3: Verify Connection
// Test connection code here
Output
- Installed SDK package in node_modules or site-packages
- Environment variable or .env file with API key
- Successful connection verification output
Error Handling
| Error | Cause | Solution |
|---|---|---|
| Invalid API Key | Incorrect or expired key | Verify key in Palantir dashboard |
| Rate Limited | Exceeded quota | Check quota at https://docs.palantir.com |
| Network Error | Firewall blocking | Ensure outbound HTTPS allowed |
| Module Not Found | Installation failed | Run npm install or pip install again |
Examples
TypeScript Setup
import { PalantirClient } from '@palantir/sdk';
const client = new PalantirClient({
apiKey: process.env.PALANTIR_API_KEY,
});
Python Setup
from palantir import PalantirClient
client = PalantirClient(
api_key=os.environ.get('PALANTIR_API_KEY')
)
Resources
Next Steps
After successful auth, proceed to palantir-hello-world for your first API call.
Configure Palantir local development with hot reload and testing.
Palantir Local Dev Loop
Overview
Set up a fast, reproducible local development workflow for Palantir.
Prerequisites
- Completed
palantir-install-authsetup - Node.js 18+ with npm/pnpm
- Code editor with TypeScript support
- Git for version control
Instructions
Step 1: Create Project Structure
my-palantir-project/
├── src/
│ ├── palantir/
│ │ ├── client.ts # Palantir client wrapper
│ │ ├── config.ts # Configuration management
│ │ └── utils.ts # Helper functions
│ └── index.ts
├── tests/
│ └── palantir.test.ts
├── .env.local # Local secrets (git-ignored)
├── .env.example # Template for team
└── package.json
Step 2: Configure Environment
# Copy environment template
cp .env.example .env.local
# Install dependencies
npm install
# Start development server
npm run dev
Step 3: Setup Hot Reload
{
"scripts": {
"dev": "tsx watch src/index.ts",
"test": "vitest",
"test:watch": "vitest --watch"
}
}
Step 4: Configure Testing
import { describe, it, expect, vi } from 'vitest';
import { PalantirClient } from '../src/palantir/client';
describe('Palantir Client', () => {
it('should initialize with API key', () => {
const client = new PalantirClient({ apiKey: 'test-key' });
expect(client).toBeDefined();
});
});
Output
- Working development environment with hot reload
- Configured test suite with mocking
- Environment variable management
- Fast iteration cycle for Palantir development
Error Handling
| Error | Cause | Solution |
|---|---|---|
| Module not found | Missing dependency | Run npm install |
| Port in use | Another process | Kill process or change port |
| Env not loaded | Missing .env.local | Copy from .env.example |
| Test timeout | Slow network | Increase test timeout |
Examples
Mock Palantir Responses
vi.mock('@palantir/sdk', () => ({
PalantirClient: vi.fn().mockImplementation(() => ({
// Mock methods here
})),
}));
Debug Mode
# Enable verbose logging
DEBUG=PALANTIR=* npm run dev
Resources
- Palantir SDK Reference
- Vitest Documentation
-
Execute Palantir major re-architecture and migration strategies with strangler fig pattern.
ReadWriteEditBash(npm:*)Bash(node:*)Bash(kubectl:*)Palantir Migration Deep Dive
Overview
Comprehensive guide for migrating to or from Palantir, or major version upgrades.
Prerequisites
- Current system documentation
- Palantir SDK installed
- Feature flag infrastructure
- Rollback strategy tested
Migration Types
Type Complexity Duration Risk Fresh install Low Days Low From competitor Medium Weeks Medium Major version Medium Weeks Medium Full replatform High Months High Pre-Migration Assessment
Step 1: Current State Analysis
# Document current implementation find . -name "*.ts" -o -name "*.py" | xargs grep -l "palantir" > palantir-files.txt # Count integration points wc -l palantir-files.txt # Identify dependencies npm list | grep palantir pip freeze | grep palantirStep 2: Data Inventory
interface MigrationInventory { dataTypes: string[]; recordCounts: Record<string, number>; dependencies: string[]; integrationPoints: string[]; customizations: string[]; } async function assessPalantirMigration(): Promise<MigrationInventory> { return { dataTypes: await getDataTypes(), recordCounts: await getRecordCounts(), dependencies: await analyzeDependencies(), integrationPoints: await findIntegrationPoints(), customizations: await documentCustomizations(), }; }Migration Strategy: Strangler Fig Pattern
Phase 1: Parallel Run ┌─────────────┐ ┌─────────────┐ │ Old │ │ New │ │ System │ ──▶ │ Palantir │ │ (100%) │ │ (0%) │ └─────────────┘ └─────────────┘ Phase 2: Gradual Shift ┌─────────────┐ ┌─────────────┐ │ Old │ │ New │ │ (50%) │ ──▶ │ (50%) │ └─────────────┘ └─────────────┘ Phase 3: Complete ┌─────────────┐ ┌─────────────┐ │ Old │ │ New │ │ (0%) │ ──▶ │ (100%) │ └─────────────┘ └─────────────┘Implementation Plan
Phase 1: Setup (Week 1-2)
# Install Palantir SDK npm install @palantir/sdk # Configure credentials cp .env.example .env.palantir # Edit with new credentials # Verify connectivity node -e "require('@palantir/sdk').ping()"Phase 2: Adapter Layer (Week 3-4)
// src/adapters/palantir.ts interface ServiceAdapter { create(data: CreateInput): Promise<Resource>; read(id: string): Promise<Resource>; update(id: string, data: UpdateInput): Promise<Re
Configure Palantir across development, staging, and production environments.
Palantir Multi-Environment Setup
Overview
Configure Palantir across development, staging, and production environments.
Prerequisites
- Separate Palantir accounts or API keys per environment
- Secret management solution (Vault, AWS Secrets Manager, etc.)
- CI/CD pipeline with environment variables
- Environment detection in application
Environment Strategy
| Environment | Purpose | API Keys | Data |
|---|---|---|---|
| Development | Local dev | Test keys | Sandbox |
| Staging | Pre-prod validation | Staging keys | Test data |
| Production | Live traffic | Production keys | Real data |
Configuration Structure
config/
├── palantir/
│ ├── base.json # Shared config
│ ├── development.json # Dev overrides
│ ├── staging.json # Staging overrides
│ └── production.json # Prod overrides
base.json
{
"timeout": 30000,
"retries": 3,
"cache": {
"enabled": true,
"ttlSeconds": 60
}
}
development.json
{
"apiKey": "${PALANTIR_API_KEY}",
"baseUrl": "https://api-sandbox.palantir.com",
"debug": true,
"cache": {
"enabled": false
}
}
staging.json
{
"apiKey": "${PALANTIR_API_KEY_STAGING}",
"baseUrl": "https://api-staging.palantir.com",
"debug": false
}
production.json
{
"apiKey": "${PALANTIR_API_KEY_PROD}",
"baseUrl": "https://api.palantir.com",
"debug": false,
"retries": 5
}
Environment Detection
// src/palantir/config.ts
import baseConfig from '../../config/palantir/base.json';
type Environment = 'development' | 'staging' | 'production';
function detectEnvironment(): Environment {
const env = process.env.NODE_ENV || 'development';
const validEnvs: Environment[] = ['development', 'staging', 'production'];
return validEnvs.includes(env as Environment)
? (env as Environment)
: 'development';
}
export function getPalantirConfig() {
const env = detectEnvironment();
const envConfig = require(`../../config/palantir/${env}.json`);
return {
...baseConfig,
...envConfig,
environment: env,
};
}
Secret Management by Environment
Local Development
# .env.local (git-ignored)
PALANTIRSet up comprehensive observability for Palantir integrations with metrics, traces, and alerts.
Palantir Observability
Overview
Set up comprehensive observability for Palantir integrations.
Prerequisites
- Prometheus or compatible metrics backend
- OpenTelemetry SDK installed
- Grafana or similar dashboarding tool
- AlertManager configured
Metrics Collection
Key Metrics
| Metric | Type | Description |
|---|---|---|
palantirrequeststotal |
Counter | Total API requests |
palantirrequestduration_seconds |
Histogram | Request latency |
palantirerrorstotal |
Counter | Error count by type |
palantirratelimit_remaining |
Gauge | Rate limit headroom |
Prometheus Metrics
import { Registry, Counter, Histogram, Gauge } from 'prom-client';
const registry = new Registry();
const requestCounter = new Counter({
name: 'palantir_requests_total',
help: 'Total Palantir API requests',
labelNames: ['method', 'status'],
registers: [registry],
});
const requestDuration = new Histogram({
name: 'palantir_request_duration_seconds',
help: 'Palantir request duration',
labelNames: ['method'],
buckets: [0.05, 0.1, 0.25, 0.5, 1, 2.5, 5],
registers: [registry],
});
const errorCounter = new Counter({
name: 'palantir_errors_total',
help: 'Palantir errors by type',
labelNames: ['error_type'],
registers: [registry],
});
Instrumented Client
async function instrumentedRequest<T>(
method: string,
operation: () => Promise<T>
): Promise<T> {
const timer = requestDuration.startTimer({ method });
try {
const result = await operation();
requestCounter.inc({ method, status: 'success' });
return result;
} catch (error: any) {
requestCounter.inc({ method, status: 'error' });
errorCounter.inc({ error_type: error.code || 'unknown' });
throw error;
} finally {
timer();
}
}
Distributed Tracing
OpenTelemetry Setup
import { trace, SpanStatusCode } from '@opentelemetry/api';
const tracer = trace.getTracer('palantir-client');
async function tracedPalantirCall<T>(
operationName: string,
operation: () => Promise<T>
): Promise<T> {
return tracer.startActiveSpan(`palantir.${operationName}`, async (span) => {
try {
const result = await operation();
span.setStatus({ code: SpanStatusCode.OK });
return result;
} catch (error: any) {
span.setStatus({ code: SpanStatusCode.ERROR, message: error.meOptimize Palantir API performance with caching, batching, and connection pooling.
Palantir Performance Tuning
Overview
Optimize Palantir API performance with caching, batching, and connection pooling.
Prerequisites
- Palantir SDK installed
- Understanding of async patterns
- Redis or in-memory cache available (optional)
- Performance monitoring in place
Latency Benchmarks
| Operation | P50 | P95 | P99 |
|---|---|---|---|
| Read | 50ms | 150ms | 300ms |
| Write | 100ms | 250ms | 500ms |
| List | 75ms | 200ms | 400ms |
Caching Strategy
Response Caching
import { LRUCache } from 'lru-cache';
const cache = new LRUCache<string, any>({
max: 1000,
ttl: 60000, // 1 minute
updateAgeOnGet: true,
});
async function cachedPalantirRequest<T>(
key: string,
fetcher: () => Promise<T>,
ttl?: number
): Promise<T> {
const cached = cache.get(key);
if (cached) return cached as T;
const result = await fetcher();
cache.set(key, result, { ttl });
return result;
}
Redis Caching (Distributed)
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
async function cachedWithRedis<T>(
key: string,
fetcher: () => Promise<T>,
ttlSeconds = 60
): Promise<T> {
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const result = await fetcher();
await redis.setex(key, ttlSeconds, JSON.stringify(result));
return result;
}
Request Batching
import DataLoader from 'dataloader';
const palantirLoader = new DataLoader<string, any>(
async (ids) => {
// Batch fetch from Palantir
const results = await palantirClient.batchGet(ids);
return ids.map(id => results.find(r => r.id === id) || null);
},
{
maxBatchSize: 100,
batchScheduleFn: callback => setTimeout(callback, 10),
}
);
// Usage - automatically batched
const [item1, item2, item3] = await Promise.all([
palantirLoader.load('id-1'),
palantirLoader.load('id-2'),
palantirLoader.load('id-3'),
]);
Connection Optimization
import { Agent } from 'https';
// Keep-alive connection pooling
const agent = new Agent({
keepAlive: true,
maxSockets: 10,
maxFreeSockets: 5,
timeout: 30000,
});
const client = new PalantirClient({
apiKey: process.env.PALANTIR_API_KEY!,
httpAgent: agent,
});
Pagination Optimization
async function* paginatedPalantirList<T>(
fetcher: (cursor?: string) => Promise<{ data: T[]; nextCursor?: string }>
): AsyncGExecute Palantir production deployment checklist and rollback procedures.
Palantir Production Checklist
Overview
Complete checklist for deploying Palantir integrations to production.
Prerequisites
- Staging environment tested and verified
- Production API keys available
- Deployment pipeline configured
- Monitoring and alerting ready
Instructions
Step 1: Pre-Deployment Configuration
- [ ] Production API keys in secure vault
- [ ] Environment variables set in deployment platform
- [ ] API key scopes are minimal (least privilege)
- [ ] Webhook endpoints configured with HTTPS
- [ ] Webhook secrets stored securely
Step 2: Code Quality Verification
- [ ] All tests passing (
npm test) - [ ] No hardcoded credentials
- [ ] Error handling covers all Palantir error types
- [ ] Rate limiting/backoff implemented
- [ ] Logging is production-appropriate
Step 3: Infrastructure Setup
- [ ] Health check endpoint includes Palantir connectivity
- [ ] Monitoring/alerting configured
- [ ] Circuit breaker pattern implemented
- [ ] Graceful degradation configured
Step 4: Documentation Requirements
- [ ] Incident runbook created
- [ ] Key rotation procedure documented
- [ ] Rollback procedure documented
- [ ] On-call escalation path defined
Step 5: Deploy with Gradual Rollout
# Pre-flight checks
curl -f https://staging.example.com/health
curl -s https://status.palantir.com
# Gradual rollout - start with canary (10%)
kubectl apply -f k8s/production.yaml
kubectl set image deployment/palantir-integration app=image:new --record
kubectl rollout pause deployment/palantir-integration
# Monitor canary traffic for 10 minutes
sleep 600
# Check error rates and latency before continuing
# If healthy, continue rollout to 50%
kubectl rollout resume deployment/palantir-integration
kubectl rollout pause deployment/palantir-integration
sleep 300
# Complete rollout to 100%
kubectl rollout resume deployment/palantir-integration
kubectl rollout status deployment/palantir-integration
Output
- Deployed Palantir integration
- Health checks passing
- Monitoring active
- Rollback procedure documented
Error Handling
| Alert | Condition | Severity |
|---|---|---|
| API Down | 5xx errors > 10/min | P1 |
| High Latency | p99 > 5000ms | P2 |
| Rate Limited | 429 errors > 5/min | P2 |
| Auth Failures | 401/403 errors > 0 | P1 |
Examples
Health Check Implementation
async function healthCheck(): Promise<{ status: string; palantir: any }Implement Palantir rate limiting, backoff, and idempotency patterns.
Palantir Rate Limits
Overview
Handle Palantir rate limits gracefully with exponential backoff and idempotency.
Prerequisites
- Palantir SDK installed
- Understanding of async/await patterns
- Access to rate limit headers
Instructions
Step 1: Understand Rate Limit Tiers
| Tier | Requests/min | Requests/day | Burst |
|---|---|---|---|
| Free | 60 | 1,000 | 10 |
| Pro | 300 | 10,000 | 50 |
| Enterprise | 1,000 | 100,000 | 200 |
Step 2: Implement Exponential Backoff with Jitter
async function withExponentialBackoff<T>(
operation: () => Promise<T>,
config = { maxRetries: 5, baseDelayMs: 1000, maxDelayMs: 32000, jitterMs: 500 }
): Promise<T> {
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (error: any) {
if (attempt === config.maxRetries) throw error;
const status = error.status || error.response?.status;
if (status !== 429 && (status < 500 || status >= 600)) throw error;
// Exponential delay with jitter to prevent thundering herd
const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);
const jitter = Math.random() * config.jitterMs;
const delay = Math.min(exponentialDelay + jitter, config.maxDelayMs);
console.log(`Rate limited. Retrying in ${delay.toFixed(0)}ms...`);
await new Promise(r => setTimeout(r, delay));
}
}
throw new Error('Unreachable');
}
Step 3: Add Idempotency Keys
import { v4 as uuidv4 } from 'uuid';
import crypto from 'crypto';
// Generate deterministic key from operation params (for safe retries)
function generateIdempotencyKey(operation: string, params: Record<string, any>): string {
const data = JSON.stringify({ operation, params });
return crypto.createHash('sha256').update(data).digest('hex');
}
async function idempotentRequest<T>(
client: PalantirClient,
params: Record<string, any>,
idempotencyKey?: string // Pass existing key for retries
): Promise<T> {
// Use provided key (for retries) or generate deterministic key from params
const key = idempotencyKey || generateIdempotencyKey(params.method || 'POST', params);
return client.request({
...params,
headers: { 'Idempotency-Key': key, ...params.headers },
});
}
Output
- Reliable API calls with automatic retry
- Idempotent requests preventing duplicates
- Rate limit headers properly handled
Error Handling
| Header | Description | Acti
Implement Palantir reference architecture with best-practice project layout.
ReadGrep
Palantir Reference ArchitectureOverviewProduction-ready architecture patterns for Palantir integrations. Prerequisites
Project Structure
Layer Architecture
Key ComponentsStep 1: Client Wrapper
Step 2: Error BoundaryApply production-ready Palantir SDK patterns for TypeScript and Python.
ReadWriteEdit
Palantir SDK PatternsOverviewProduction-ready patterns for Palantir SDK usage in TypeScript and Python. Prerequisites
InstructionsStep 1: Implement Singleton Pattern (Recommended)
Step 2: Add Error Handling Wrapper
Step 3: Implement Retry Logic
Output
Error Handling
ExamplesFactory Pattern (Multi-tenant)Apply Palantir security best practices for secrets and access control.
ReadWriteGrep
Palantir Security BasicsOverviewSecurity best practices for Palantir API keys, tokens, and access control. Prerequisites
InstructionsStep 1: Configure Environment Variables
Step 2: Implement Secret Rotation
Step 3: Apply Least Privilege
Output
Error Handling
ExamplesService Account Pattern
Webhook Signature Verification
Security Checklist
Audit LoggingAnalyze, plan, and execute Palantir SDK upgrades with breaking change detection.
ReadWriteEditBash(npm:*)Bash(git:*)
Palantir Upgrade & MigrationOverviewGuide for upgrading Palantir SDK versions and handling breaking changes. Prerequisites
InstructionsStep 1: Check Current Version
Step 2: Review Changelog
Step 3: Create Upgrade Branch
Step 4: Handle Breaking ChangesUpdate import statements, configuration, and method signatures as needed. Output
Error Handling
ExamplesImport Changes
Configuration Changes
Rollback Procedure
Deprecation Handling
ResourcesNext StepsFor CI integration during upgrades, see Implement Palantir webhook signature validation and event handling.
ReadWriteEditBash(curl:*)
Palantir Webhooks & EventsOverviewSecurely handle Palantir webhooks with signature validation and replay protection. Prerequisites
Webhook Endpoint SetupExpress.js
Signature Verification
Event Handler PatternReady to use palantir-pack?Related Plugins000-jeremy-content-consistency-validatorRead-only validator that generates comprehensive discrepancy reports comparing messaging consistency across ANY HTML-based website (WordPress, Hugo, Next.js, React, Vue, static HTML, etc.), GitHub repositories, and local documentation. Detects mixed messaging without making changes. 002-jeremy-yaml-master-agentIntelligent YAML validation, generation, and transformation agent with schema inference, linting, and format conversion capabilities 003-jeremy-vertex-ai-media-masterComprehensive Google Vertex AI multimodal mastery for Jeremy - video processing (6+ hours), audio generation, image creation with Gemini 2.0/2.5 and Imagen 4. Marketing campaign automation, content generation, and media asset production. 004-jeremy-google-cloud-agent-sdkGoogle Cloud Agent Development Kit (ADK) and Agent Starter Pack mastery - build containerized multi-agent systems with production-ready templates, deploy to Cloud Run/GKE/Agent Engine, RAG agents, ReAct agents, and multi-agent orchestration. agent-context-managerAutomatically detects and loads AGENTS.md files to provide agent-specific instructions ai-commit-genAI-powered commit message generator - analyzes your git diff and creates conventional commit messages instantly
Tags
palantirsaassdkintegration
|
|---|