> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kubiya.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Context Service

> Manage and resolve entity context with inheritance

The Context Service provides context resolution and management for entities in the Control Plane. It enables you to store, retrieve, and resolve context with inheritance across organizational hierarchies.

## Quick Start

```python theme={null}
from kubiya import ControlPlaneClient

client = ControlPlaneClient()

# Get context for an agent
context = client.context.get(
    entity_type="agent",
    entity_id="agent-uuid"
)

# Update context
updated = client.context.update(
    entity_type="agent",
    entity_id="agent-uuid",
    context_data={
        "deployment_region": "us-east-1",
        "environment": "production"
    }
)

# Resolve context with inheritance
resolved = client.context.resolve(
    entity_type="agent",
    entity_id="agent-uuid"
)
```

## Features

<CardGroup cols={2}>
  <Card title="Context Storage" icon="database">
    Store entity-specific context data
  </Card>

  <Card title="Context Retrieval" icon="magnifying-glass">
    Retrieve context for any entity
  </Card>

  <Card title="Context Inheritance" icon="diagram-project">
    Resolve context across organizational layers
  </Card>

  <Card title="Context Management" icon="pen-to-square">
    Update and delete entity context
  </Card>
</CardGroup>

## Entity Types

The Context Service supports the following entity types:

* **agent**: Individual agents
* **team**: Multi-agent teams
* **environment**: Runtime environments
* **project**: Project entities
* **organization**: Organization-level context

## Get Context

Retrieve context for a specific entity:

```python theme={null}
# Get agent context
agent_context = client.context.get(
    entity_type="agent",
    entity_id="agent-uuid"
)

print(f"Agent context: {agent_context}")

# Get team context
team_context = client.context.get(
    entity_type="team",
    entity_id="team-uuid"
)

# Get environment context
env_context = client.context.get(
    entity_type="environment",
    entity_id="env-uuid"
)
```

**Parameters:**

* `entity_type` (str, required): Type of entity ('agent', 'team', 'environment', etc.)
* `entity_id` (str, required): UUID of the entity

**Returns:** Dictionary containing entity context

## Update Context

Update context for a specific entity:

```python theme={null}
# Update agent context
updated_context = client.context.update(
    entity_type="agent",
    entity_id="agent-uuid",
    context_data={
        "region": "us-west-2",
        "tier": "premium",
        "tags": ["production", "critical"],
        "metadata": {
            "owner": "platform-team",
            "cost_center": "engineering"
        }
    }
)

print(f"Updated context: {updated_context}")

# Update team context
team_context = client.context.update(
    entity_type="team",
    entity_id="team-uuid",
    context_data={
        "max_concurrent_tasks": 10,
        "default_timeout": 3600
    }
)
```

**Parameters:**

* `entity_type` (str, required): Type of entity
* `entity_id` (str, required): UUID of the entity
* `context_data` (dict, required): Context data to store

**Returns:** Dictionary containing updated context

<Info>
  Context updates replace the entire context for the entity. To merge with existing context, retrieve it first, merge locally, then update.
</Info>

## Delete Context

Clear or delete context for a specific entity:

```python theme={null}
# Delete agent context
result = client.context.delete(
    entity_type="agent",
    entity_id="agent-uuid"
)

print(f"Context deleted: {result}")

# Delete team context
result = client.context.delete(
    entity_type="team",
    entity_id="team-uuid"
)
```

**Parameters:**

* `entity_type` (str, required): Type of entity
* `entity_id` (str, required): UUID of the entity

**Returns:** Dictionary containing deletion status

## Resolve Context

Resolve context with inheritance from all organizational layers:

```python theme={null}
# Resolve agent context with inheritance
resolved_context = client.context.resolve(
    entity_type="agent",
    entity_id="agent-uuid"
)

print(f"Resolved context: {resolved_context}")
print(f"Inherited from team: {resolved_context.get('team_context', {})}")
print(f"Inherited from environment: {resolved_context.get('environment_context', {})}")
print(f"Inherited from organization: {resolved_context.get('org_context', {})}")

# Resolve team context
team_resolved = client.context.resolve(
    entity_type="team",
    entity_id="team-uuid"
)
```

**Parameters:**

* `entity_type` (str, required): Type of entity
* `entity_id` (str, required): UUID of the entity

**Returns:** Dictionary containing resolved context with inheritance information

<Tip>
  Use `resolve()` instead of `get()` when you need the full context picture including inherited values from parent entities.
</Tip>

## Context Inheritance

Context inheritance follows organizational hierarchy:

```
Organization Context
    ↓ (inherited by)
Environment Context
    ↓ (inherited by)
Project Context
    ↓ (inherited by)
Team Context
    ↓ (inherited by)
Agent Context
```

More specific context overrides inherited values.

## Complete Example

Here's a complete example showing context management across entity types:

```python theme={null}
from kubiya import ControlPlaneClient

client = ControlPlaneClient()

# 1. Set organization-level context
org_context = client.context.update(
    entity_type="organization",
    entity_id="org-uuid",
    context_data={
        "company": "Acme Corp",
        "compliance_level": "high",
        "default_region": "us-east-1"
    }
)

# 2. Set environment context
env_context = client.context.update(
    entity_type="environment",
    entity_id="prod-env-uuid",
    context_data={
        "environment": "production",
        "region": "us-west-2",  # Overrides org default
        "monitoring_enabled": True
    }
)

# 3. Set team context
team_context = client.context.update(
    entity_type="team",
    entity_id="team-uuid",
    context_data={
        "team_name": "Platform Engineering",
        "on_call_rotation": ["alice", "bob", "charlie"],
        "max_concurrent_tasks": 5
    }
)

# 4. Set agent context
agent_context = client.context.update(
    entity_type="agent",
    entity_id="agent-uuid",
    context_data={
        "agent_name": "infrastructure-agent",
        "specialization": "kubernetes",
        "max_concurrent_tasks": 3  # Overrides team default
    }
)

# 5. Resolve agent context with full inheritance
resolved = client.context.resolve(
    entity_type="agent",
    entity_id="agent-uuid"
)

print("Resolved Agent Context:")
print(f"  Company: {resolved.get('company')}")  # From org
print(f"  Region: {resolved.get('region')}")  # From environment
print(f"  Team: {resolved.get('team_name')}")  # From team
print(f"  Agent: {resolved.get('agent_name')}")  # From agent
print(f"  Max Tasks: {resolved.get('max_concurrent_tasks')}")  # Agent override

# 6. Get just agent-specific context
agent_only = client.context.get(
    entity_type="agent",
    entity_id="agent-uuid"
)
print(f"\nAgent-only context: {agent_only}")
```

## Error Handling

Handle context-related errors:

```python theme={null}
from kubiya.resources.exceptions import ControlPlaneError

try:
    context = client.context.get(
        entity_type="agent",
        entity_id="invalid-id"
    )
except ControlPlaneError as e:
    print(f"Context error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## Use Cases

### Configuration Management

```python theme={null}
# Store environment-specific configuration
client.context.update(
    entity_type="environment",
    entity_id="prod-env-uuid",
    context_data={
        "database_host": "prod-db.example.com",
        "api_endpoint": "https://api.example.com",
        "cache_ttl": 3600
    }
)
```

### Access Control

```python theme={null}
# Store access control information
client.context.update(
    entity_type="agent",
    entity_id="agent-uuid",
    context_data={
        "allowed_resources": ["s3", "ec2", "rds"],
        "restricted_actions": ["delete", "terminate"],
        "approval_required": True
    }
)
```

### Monitoring & Observability

```python theme={null}
# Store monitoring configuration
client.context.update(
    entity_type="team",
    entity_id="team-uuid",
    context_data={
        "metrics_endpoint": "https://metrics.example.com",
        "log_level": "info",
        "tracing_enabled": True,
        "alert_email": "team@example.com"
    }
)
```

### Cost Attribution

```python theme={null}
# Store cost center information
client.context.update(
    entity_type="project",
    entity_id="project-uuid",
    context_data={
        "cost_center": "engineering-001",
        "budget_code": "ENG-2024-Q1",
        "billing_contact": "finance@example.com"
    }
)
```

## Best Practices

### Context Organization

* **Hierarchical Design**: Use inheritance to avoid duplication
* **Specific Overrides**: Place specific values at lower levels
* **Consistent Keys**: Use consistent key names across entity types
* **Avoid Deep Nesting**: Keep context structure flat when possible

### Data Management

* **Regular Updates**: Keep context data current
* **Clean Up Unused**: Delete context for deleted entities
* **Validate Data**: Validate context data before storing
* **Version Context**: Include version info in context for tracking changes

### Security

* **Sensitive Data**: Avoid storing sensitive data in context (use Secrets Service instead)
* **Access Control**: Limit who can update context
* **Audit Changes**: Log all context changes
* **Encrypt Sensitive Fields**: Use encryption for any sensitive context data

### Performance

* **Cache Resolved Context**: Cache resolved context for frequently accessed entities
* **Batch Operations**: When updating multiple entities, batch where possible
* **Lazy Resolution**: Use `get()` instead of `resolve()` when inheritance isn't needed

## API Reference

| Method      | Endpoint Pattern                               | Description              |
| ----------- | ---------------------------------------------- | ------------------------ |
| `get()`     | GET /context/{entity_type}/{entity_id}         | Get entity context       |
| `update()`  | PUT /context/{entity_type}/{entity_id}         | Update entity context    |
| `delete()`  | DELETE /context/{entity_type}/{entity_id}      | Delete entity context    |
| `resolve()` | GET /context/{entity_type}/{entity_id}/resolve | Resolve with inheritance |

## Next Steps

<CardGroup cols={2}>
  <Card title="Agents Service" icon="robot" href="/sdk/control-plane-agents">
    Manage agents with context
  </Card>

  <Card title="Teams Service" icon="users" href="/sdk/control-plane-teams">
    Configure team context
  </Card>

  <Card title="Environments Service" icon="layer-group" href="/sdk/control-plane-environments">
    Set environment context
  </Card>

  <Card title="Secrets Service" icon="key" href="/sdk/control-plane-secrets">
    Store sensitive data securely
  </Card>
</CardGroup>
