Skip to content

feat: complete HTTP Ambient Platform SDK for Go and Python#623

Open
markturansky wants to merge 3 commits intoambient-code:mainfrom
markturansky:feat/ambient-sdk
Open

feat: complete HTTP Ambient Platform SDK for Go and Python#623
markturansky wants to merge 3 commits intoambient-code:mainfrom
markturansky:feat/ambient-sdk

Conversation

@markturansky
Copy link

│ - Transform SDK from Kubernetes-dependent to pure HTTP client architecture
│ - Add comprehensive Go SDK with HTTP client, types, and working examples
│ - Add comprehensive Python SDK with identical functionality and test automation
│ - Focus on AgenticSession management via REST API (/v1/sessions)
│ - Include Bearer token + X-Ambient-Project header authentication
│ - Add automated testing scripts with environment validation
│ - Update OpenAPI specification to match HTTP implementation
│ - Successfully tested against live OpenShift deployment with Vertex AI

│ 🤖 Generated with Claude Code
│ Co-Authored-By: Claude noreply@anthropic.com

Closes #556

│   - Transform SDK from Kubernetes-dependent to pure HTTP client architecture
│   - Add comprehensive Go SDK with HTTP client, types, and working examples
│   - Add comprehensive Python SDK with identical functionality and test automation
│   - Focus on AgenticSession management via REST API (/v1/sessions)
│   - Include Bearer token + X-Ambient-Project header authentication
│   - Add automated testing scripts with environment validation
│   - Update OpenAPI specification to match HTTP implementation
│   - Successfully tested against live OpenShift deployment with Vertex AI
│
│   🤖 Generated with [Claude Code](https://claude.ai/code)
│   Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions

This comment has been minimized.

@markturansky
Copy link
Author

This is the output of the test script in python-sdk:

★ mturansk:~/projects/src/github.com/ambient/platform/components/ambient-sdk/python-sdk  
$ export AMBIENT_TOKEN="$(oc whoami -t)"                    # Use current user token
export AMBIENT_PROJECT="$(oc project -q)"                 # Use current project/namespace
export AMBIENT_API_URL="$(oc get route public-api-route --template='https://{{.spec.host}}')"  # Get public API route

★ mturansk:~/projects/src/github.com/ambient/platform/components/ambient-sdk/python-sdk  
$ ./test.sh 
🐍 Ambient Platform Python SDK Test
====================================

✓ Running from correct directory: /home/mturansk/projects/src/github.com/ambient/platform/components/ambient-sdk/python-sdk
✓ All required environment variables are set
ℹ Validating environment variables...
✓ Environment variables validated

ℹ Configuration:
  API URL: https://public-api-route-myproject.apps.rosa.rh34h-8f6st-rcw.99ok.p3.openshiftapps.com
  Project: myproject
  Token length: 50 characters
  Token prefix: sha256~ulHBW...

ℹ Setting up Python virtual environment...
✓ Virtual environment already exists
ℹ Installing dependencies...
✓ Dependencies installed successfully
ℹ Testing SDK import...
✓ SDK imports working correctly

✓ Setup complete! Running example...

ℹ Running Python SDK example...

🐍 Ambient Platform SDK - Python HTTP Client Example
===================================================
✓ Created client for API: https://public-api-route-myproject.apps.rosa.rh34h-8f6st-rcw.99ok.p3.openshiftapps.com
✓ Using project: myproject

📝 Creating new session...
✓ Created session: session-1771021020

🔍 Getting session details...
   ID: session-1771021020
   Status: pending
   Task: 
   Model: None
   Created: 2026-02-13T22:17:00Z

📋 Listing all sessions...
✓ Found 3 sessions (total: 3)
  1. session-1771021020 (pending) - 
  2. session-1771019403 (pending) - 
  3. session-1771019367 (pending) - 

✅ Python HTTP Client demonstration complete!

💡 Next steps:
   • Check session status periodically
   • Use the session ID to retrieve results
   • Create additional sessions as needed

✓ Python SDK test completed successfully!

- Correct Go module path to match monorepo structure
- Add client-side validation for tokens, requests, and repository URLs
- Remove unnecessary K8s dependencies from Go SDK examples
- Update production kustomization overlay

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@markturansky
Copy link
Author

Successful run of go-sdk

$ go run examples/main.go
🌐 Ambient Platform SDK - HTTP Client Example
============================================
✓ Created client for API: https://public-api-route-myproject.apps.rosa.rh34h-8f6st-rcw.99ok.p3.openshiftapps.com
✓ Using project: myproject

📝 Creating new session...
✓ Created session: session-1771028074

🔍 Getting session details...
   ID: session-1771028074
   Status: pending
   Task: 
   Model: 
   Created: 2026-02-14T00:14:34Z

📋 Listing all sessions...
✓ Found 8 sessions (total: 8)
  1. session-1771028074 (pending) - 
  2. session-1771028060 (pending) - 
  3. session-1771028038 (pending) - 
  ... and 5 more

✅ HTTP Client demonstration complete!

💡 Next steps:
   • Check session status periodically
   • Use the session ID to retrieve results
   • Create additional sessions as needed

@github-actions
Copy link
Contributor

github-actions bot commented Feb 14, 2026

Claude Code Review

Summary

This PR introduces comprehensive HTTP-first SDKs for Go and Python, enabling external developers to interact with the Ambient Platform without Kubernetes dependencies. The implementation is well-structured with proper input validation, error handling, and automated testing. However, there are several security and code quality issues that should be addressed before merge.

Issues by Severity

🚫 Blocker Issues

None - No blocking issues that prevent merge, but critical issues below should be addressed.

🔴 Critical Issues

  1. Token Validation Insufficient (Security)

    • Location: go-sdk/client/client.go:217-231, python-sdk/ambient_platform/client.py:259-273
    • Issue: Token validation only checks length and placeholder values. Does not validate Bearer token format or prevent logging.
    • Impact: Could accept malformed tokens or fail to prevent accidental token logging.
    • Fix: Add format validation (JWT structure if applicable), ensure tokens are NEVER logged anywhere in the SDK.
    • Standards Violated: CLAUDE.md Section "Token Security and Redaction" - tokens must never be logged.
  2. Error Response Body Exposure (Security)

    • Location: go-sdk/client/client.go:95, client.go:138, client.go:177
    • Issue: Raw error response bodies are exposed in error messages: fmt.Errorf("API error (%d): %s", resp.StatusCode, string(body))
    • Impact: Could leak sensitive information from backend error messages to SDK users.
    • Standards Violated: CLAUDE.md error-handling.md - "Don't expose internal error details"
    • Fix: Return generic error messages, optionally log full details if SDK has debug mode.
  3. No RBAC Documentation (Security)

    • Location: README.md, SDK documentation
    • Issue: No documentation about RBAC requirements, permissions needed, or how user tokens are validated.
    • Impact: Users won't understand authorization model or troubleshoot permission errors.
    • Fix: Add section explaining:
      • User token authentication requirement
      • Project-scoped namespaces and RBAC
      • Common permission errors and troubleshooting

🟡 Major Issues

  1. Missing Context Timeout Handling (Performance)

    • Location: go-sdk/client/client.go:189-214 (WaitForCompletion)
    • Issue: While context cancellation is checked, there's no maximum retry limit or exponential backoff.
    • Impact: Could poll indefinitely if context has no timeout, wasting resources.
    • Fix: Add max retry count or warn in docs that callers must set context timeout.
  2. localhost URL Validation Too Strict (Usability)

    • Location: python-sdk/ambient_platform/client.py:299-300
    • Issue: Rejects https://localhost URLs, only allows http://localhost.
    • Impact: Users testing with self-signed certs or local TLS setup will fail.
    • Fix: Allow both http://localhost and https://localhost.
  3. Incomplete Model Validation (Data Quality)

    • Location: go-sdk/types/types.go:114-129, python-sdk/ambient_platform/types.py:83-92
    • Issue: Hardcoded model list doesn't match current Claude models (e.g., missing claude-opus-4-6, claude-sonnet-4-5).
    • Impact: Users cannot use latest models, validation will reject valid inputs.
    • Fix: Either:
      • Update to latest model names
      • Make validation more permissive (allow any claude-* pattern)
      • Remove client-side validation (let backend validate)
  4. Repository URL Validation Blocks Valid Use Cases (Usability)

    • Location: go-sdk/types/types.go:106-108, python-sdk/ambient_platform/types.py:44-45
    • Issue: Blocks localhost URLs, preventing local development/testing scenarios.
    • Impact: Cannot test with local git servers or mock repositories.
    • Fix: Remove localhost check or add allow_localhost option for testing.
  5. Python SDK Missing Type Hints (Code Quality)

    • Location: python-sdk/ambient_platform/client.py - several methods
    • Issue: Some methods like _handle_response return dict instead of specific types.
    • Impact: Reduces type safety, harder to catch errors at development time.
    • Fix: Return typed responses (SessionResponse, etc.) instead of raw dicts.
    • Standards Violated: Python best practices - use type hints everywhere.

🔵 Minor Issues

  1. Inconsistent Error Message Format (Code Quality)

    • Location: Throughout client.go and client.py
    • Issue: Some errors use failed to X: %w, others use Failed to X: %v.
    • Fix: Standardize on lowercase "failed to" with %w for error wrapping.
  2. Missing Integration Tests (Testing)

    • Location: No *_test.go files in go-sdk
    • Issue: No unit tests for validation logic, error handling, or client methods.
    • Impact: Validation bugs could slip through, breaking changes not caught.
    • Fix: Add tests for:
      • Token validation edge cases
      • Request validation (empty task, long task, invalid URLs)
      • Error response parsing
      • WaitForCompletion timeout behavior
  3. OpenAPI Spec Minor Issues (Documentation)

    • Location: openapi.yaml:218-220
    • Issue: minLength: 10 for task seems arbitrary (why 10 characters?).
    • Fix: Document rationale or adjust to match actual backend validation.
  4. Go Module Path Incorrect (Build)

    • Location: go-sdk/client/client.go:12
    • Issue: Import path github.com/ambient-code/platform/components/ambient-sdk/go-sdk/types assumes repository structure.
    • Impact: External users cannot import SDK from their projects.
    • Fix: Either:
      • Move SDK to separate repository with clean import path
      • Document that SDK is for reference only, not intended for external import
      • Use Go workspace or replace directives

Positive Highlights

  1. ✅ Excellent Input Validation - Comprehensive validation for tokens, URLs, task length, model names
  2. ✅ Proper Error Wrapping - Most errors use fmt.Errorf("...: %w", err) for error chains
  3. ✅ Context Support - All HTTP operations properly accept context.Context
  4. ✅ Clean Separation - Client, types, and examples well-organized
  5. ✅ Good Documentation - READMEs are comprehensive with examples
  6. ✅ Automated Testing Script - Python test.sh provides environment validation
  7. ✅ Proper Resource Cleanup - Python client implements context manager (__enter__/__exit__)
  8. ✅ No Kubernetes Dependencies - Truly HTTP-only as designed

Recommendations

High Priority (Before Merge)

  1. Fix token security issues - Never log tokens, add proper validation
  2. Remove error body exposure - Return generic error messages
  3. Add RBAC documentation - Explain authentication/authorization model
  4. Update model list - Match current Claude model names or make validation flexible
  5. Fix Go module import path - Make SDK actually importable by external users

Medium Priority (Soon After Merge)

  1. Add unit tests - Cover validation logic and error cases
  2. Add retry/backoff to polling - Prevent infinite loops in WaitForCompletion
  3. Relax localhost validation - Support local development scenarios
  4. Improve Python type hints - Return specific types instead of dict

Low Priority (Future Enhancement)

  1. Add SDK versioning - Semantic versioning for SDK releases
  2. Add debug logging mode - Controlled logging for troubleshooting (never log tokens)
  3. Add request/response tracing - OpenTelemetry instrumentation
  4. Add SDK code generation - Generate from OpenAPI spec to ensure sync

Approval Recommendation

Conditional Approve - The SDK implementation is solid, but the critical security issues (#1, #2) and usability issues (#3, #6, #12) should be fixed before merge. Once those are addressed, this is ready to ship.


Review Methodology: Reviewed against CLAUDE.md standards, security-standards.md, error-handling.md, and k8s-client-usage.md patterns. Checked for token security, error handling, type safety, and RBAC compliance.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

- Introduce SecureToken type with slog.LogValuer for automatic log redaction
- Add comprehensive token format validation (OpenShift, JWT, GitHub)
- Replace raw token strings with SecureToken throughout client
- Add slog-based structured logging with sensitive-data sanitization
- Harden error responses to avoid exposing raw API response bodies
- Expand auth documentation in Go and Python SDK READMEs

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions
Copy link
Contributor

github-actions bot commented Feb 14, 2026

Claude Code Review

Summary

This PR introduces a comprehensive HTTP-first SDK for the Ambient Platform in both Go and Python, eliminating Kubernetes dependencies for external developers. The implementation demonstrates excellent security practices, particularly around token handling and input validation. The code follows established patterns well, with strong type safety and comprehensive error handling.

Overall Assessment: APPROVE ✅ - High-quality implementation with minor suggestions for improvement.


Issues by Severity

🚫 Blocker Issues

None - No blocking issues found.

🔴 Critical Issues

None - No critical issues that must be fixed before merge.

🟡 Major Issues

1. Go SDK: Inconsistent Error Handling Pattern

  • Location: go-sdk/client/client.go:116-120
  • Issue: Returns generic error messages to users but logs full error details only at Debug level
  • Pattern Violation: Backend error handling pattern expects Error level logs before returning errors
  • Current:
    c.logger.Debug("API error details", "error", errResp.Error, "message", errResp.Message)
    return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, errResp.Error)
  • Expected (per .claude/patterns/error-handling.md):
    c.logger.Error("API error details", "status_code", resp.StatusCode, "error", errResp.Error)
    return nil, fmt.Errorf("API error (%d): %s", resp.StatusCode, errResp.Error)
  • Impact: Debugging production issues will be harder if errors only appear at Debug level

2. Python SDK: Missing Token Validation in Constructor

  • Location: python-sdk/ambient_platform/client.py:52
  • Issue: Token validation happens in _validate_token() but doesn't check for OpenShift/JWT/GitHub token formats like Go SDK does
  • Comparison: Go SDK has comprehensive format validation in types.go:118-179
  • Recommendation: Add similar format validation to match Go SDK security standards
  • Impact: Weaker security validation compared to Go SDK

3. Missing Go Module Path Correction

  • Location: go-sdk/go.mod:1, examples/go.mod:7
  • Issue: Module path is github.com/ambient-code/platform/components/ambient-sdk/go-sdk but should likely be standalone
  • Expected: github.com/ambient-code/ambient-sdk/go or similar (for external consumption)
  • Impact: External developers cannot easily import this module from their projects

🔵 Minor Issues

1. Go SDK: Redundant Token Sanitization

  • Location: go-sdk/client/client.go:248-292
  • Issue: Both sanitizeLogAttrs and SecureToken.LogValue() sanitize tokens, creating double protection
  • Observation: While defense-in-depth is good, the pattern is slightly redundant
  • Recommendation: Document why both layers exist or simplify to one canonical approach
  • Impact: Minimal - just adds maintenance overhead

2. Python SDK: Hardcoded Model List

  • Location: python-sdk/ambient_platform/types.py:85-91
  • Issue: Valid models hardcoded in two places (Python and Go)
  • Recommendation: Consider fetching from API or shared configuration
  • Impact: Requires updates in two places when new models are added

3. Missing Integration Tests

  • Observation: Only manual test scripts provided, no automated test suite
  • Recommendation: Add unit tests for validation logic and mock API tests
  • Files Needed:
    • go-sdk/client/client_test.go
    • python-sdk/tests/test_client.py
    • python-sdk/tests/test_types.py
  • Impact: Lower confidence in refactoring and maintenance

4. Go SDK: Missing Context Cancellation Check

  • Location: go-sdk/client/client.go:221-246
  • Issue: WaitForCompletion checks context cancellation only once per ticker iteration
  • Recommendation: Add immediate check before first API call:
    func (c *Client) WaitForCompletion(...) (*types.SessionResponse, error) {
        // Check context before starting
        if ctx.Err() != nil {
            return nil, ctx.Err()
        }
        // ... rest of function
    }
  • Impact: Slight delay in responding to cancellation

5. Python SDK: Missing Type Hints for from_dict Methods

  • Location: python-sdk/ambient_platform/types.py (multiple locations)
  • Issue: from_dict methods return string literals instead of proper types
  • Current: def from_dict(cls, data: dict) -> "SessionResponse":
  • Recommendation: Use from __future__ import annotations and remove quotes
  • Impact: Slightly less helpful IDE autocomplete

Positive Highlights

✨ Excellent Security Practices

  1. Token Sanitization (go-sdk/types/types.go:66-78):

    • Custom SecureToken type with slog.LogValuer interface
    • Automatic redaction in logs showing only prefix + length
    • Comprehensive validation against placeholder values
  2. Input Validation (go-sdk/types/types.go:181-229):

    • Validates all user inputs before API calls
    • Checks URL formats, model names, task length
    • Prevents injection attacks and malformed requests
  3. Structured Logging (go-sdk/client/client.go:42-44):

    • Uses slog with ReplaceAttr for global sanitization
    • Redacts tokens by key patterns, value patterns, and known formats
    • Defense-in-depth approach

🎯 Follows Repository Patterns

  1. Error Handling: Matches backend patterns from .claude/patterns/error-handling.md

    • Checks IsNotFound for 404s
    • Logs with context before returning errors
    • Returns generic messages to users
  2. Type Safety: No any types, comprehensive validation

    • Go: Strong typing with validation methods
    • Python: Dataclasses with validation
  3. Consistent Structure: Both SDKs mirror each other's API

    • Same method names (create_session, get_session, list_sessions)
    • Same validation logic
    • Same error handling patterns

📚 Comprehensive Documentation

  1. README files: Clear quick-start guides for both SDKs
  2. Examples: Working examples with environment setup
  3. Test scripts: Automated validation scripts with helpful error messages

🛡️ Defense-in-Depth Security

  • Token validation at client creation time
  • Request validation before API calls
  • Response validation after API calls
  • Comprehensive error messages without exposing sensitive data

Recommendations

Priority 1 (Before Merge)

  1. Fix Go module paths for external consumption
  2. Add Error-level logging for API errors (not just Debug)
  3. Add Python token format validation to match Go SDK

Priority 2 (Follow-up PRs)

  1. Add automated tests (unit + integration with mocks)
  2. Extract model list to shared configuration or API endpoint
  3. Add context cancellation check before first API call in WaitForCompletion

Priority 3 (Future Enhancements)

  1. Generate TypeScript SDK from OpenAPI spec (already in roadmap)
  2. Add rate limiting and retry logic with exponential backoff
  3. Add metrics/tracing support (optional Prometheus integration)

Checklist Review (Backend Standards)

Comparing against .claude/context/backend-development.md checklist:

  • Token Security: No tokens in logs (excellent implementation)
  • Error Handling: Errors logged with context
  • ⚠️ Error Logging Level: Should use Error, not Debug (see Major Issue Outcome: Reduce Refinement Time with agent System #1)
  • Type Safety: Type-safe validation throughout
  • Go Formatting: Code appears well-formatted
  • N/A K8s Client Usage: This is an HTTP-only SDK (no K8s clients)
  • N/A RBAC: Authentication happens in backend, not SDK

Final Verdict

APPROVE ✅

This is a well-crafted SDK implementation that demonstrates strong security practices and follows repository patterns. The token sanitization approach is exemplary and could serve as a reference for other projects. The few issues identified are minor and can be addressed in follow-up commits.

Suggested merge strategy:

  1. Fix Go module paths (5 min)
  2. Change Debug → Error for API error logs (2 min)
  3. Add Python token format validation (15 min)
  4. Merge with confidence
  5. Address automated testing in follow-up PR

Total estimated fixes: ~30 minutes


Great work on this implementation! 🎉 The security-first approach and comprehensive validation logic are exactly what this platform needs for external integrations.


🔍 View AI decision process (logs available for 90 days)

📋 View memory system files loaded (click to expand)

What Amber Loaded for Code Review

Amber automatically loaded these repository standards from the memory system:

  1. CLAUDE.md - Master project instructions, development standards
  2. backend-development.md - Go backend, K8s integration patterns
  3. frontend-development.md - NextJS, Shadcn UI, React Query patterns
  4. security-standards.md - Auth, RBAC, token handling
  5. k8s-client-usage.md - User token vs service account patterns
  6. error-handling.md - Consistent error patterns
  7. react-query-usage.md - Data fetching patterns

Impact: This review used your repository's specific code quality standards, security patterns, and best practices from the memory system (PRs #359, #360) - not just generic code review guidelines.

@markturansky
Copy link
Author

@jeremyeder @EmilienM PTAL the AI reviewer gave a robotic thumbs up

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.

Feature: ACP SDK

1 participant

Comments