Skip to main content
Glama
README.md
# home-agent-sandbox

[![CI](https://github.com/surendrachallagundla301/home-agent-sandbox/actions/workflows/ci.yml/badge.svg)](https://github.com/surendrachallagundla301/home-agent-sandbox/actions/workflows/ci.yml)

A **sandbox and scheduler for AI agents that control a smart home**. Agents reach devices
through an **MCP server**, and every request (immediate or scheduled) goes through one
path that decides whether the agent may see the device, may take that action right now,
and whether a human has to approve it first.

The idea: a home might run several agents at once (an energy saver, a security agent, a
guest's voice assistant). None of them should be able to unlock the front door on its
own, turn the heat to 35 °C, or flip lights at 2 a.m. because a guest asked.

```
 AI agent (MCP client)
        │ control_device / schedule_action
        ▼
 ┌──────────────────────── Hub ─────────────────────────┐
 │ 1 Visibility   agents only see devices they're granted│
 │ 2 Policy       default-deny rules per agent           │
 │ 3 Quiet hours  per-agent time windows                 │
 │ 4 Safety       hard limits no agent can override      │
 │ 5 Rate limit   sliding 60-second window per agent     │
 │ 6 Approval     high-risk actions wait for a human     │
 │ 7 Audit        one entry per decision (no values)     │
 └───────────────────────────────────────────────────────┘
        │                         ▲
        ▼                         │ scheduled tasks re-enter here
 lights · plugs · thermostat · lock · camera     Scheduler (heap, retries, conflicts)
```

## What it shows

| Concern | Implementation |
| --- | --- |
| **Agent sandboxing** | `policy.py`. Default-deny allow rules with device globs (`light.*`). Agents only *see* devices they have rights on, so a guest assistant cannot even discover the front-door lock. |
| **Safety limits** | The thermostat can never be set outside 16–26 °C, by any agent, including the homeowner's. |
| **Quiet hours** | A guest assistant is denied between 22:00 and 07:00 (windows can cross midnight). |
| **Human in the loop** | `unlock` and `camera disable` create an approval request that expires after 5 minutes. Only an approver can decide, and never on their own request. On approval, the policy is checked again before running. |
| **Kill switch** | `kill(agent)` blocks the agent, cancels all of its queued tasks and rejects its pending approvals. |
| **Agent scheduling** | `scheduler.py`. One-off and recurring tasks on a min-heap. **Policy is re-checked when a task runs**, so revoking a permission or entering quiet hours also stops tasks queued earlier. |
| **Conflicts** | If two tasks hit the same device in the same tick, the higher-priority one runs and the other is marked `superseded`. |
| **Reliability** | Offline devices are retried with exponential backoff (2 s, 4 s, …) up to a limit. Idempotency keys stop duplicate tasks. Recurring tasks skip missed runs instead of bursting after a pause. Per-agent quotas cap queued work. |
| **Memory** | `__slots__` tasks, interned names, no empty-dict copies, 3-tuple heap entries, lazy cancellation with heap compaction, fixed-size history and audit buffers. See the benchmark below. |
| **MCP** | `server.py`. Built on the official MCP Python SDK (v2 `MCPServer`). One server per agent; approver tools (`list_approvals`, `decide_approval`, `kill_agent`) only appear for agents marked `approver`. A background loop runs due tasks every second. |

## Quick start

```bash
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest -q                     # 30 tests
python examples/demo.py       # walk-through with three agents and a homeowner
python examples/bench.py      # memory and throughput numbers
```

### Use it from an MCP client

```json
{
  "mcpServers": {
    "home-energy": {
      "command": "home-agent-sandbox",
      "args": ["--agent", "energy-agent"]
    }
  }
}
```

Tools: `list_devices`, `control_device`, `schedule_action`, `list_scheduled`,
`cancel_scheduled`, plus `list_approvals`, `decide_approval` and `kill_agent` for approvers.
Set `HOME_SANDBOX_AUDIT_LOG=audit.jsonl` to also write the audit trail to a file.

## Policy

```yaml
agents:
  guest-assistant:
    allow:
      - { devices: ["light.living_room"], actions: [turn_on, turn_off, set_brightness] }
    quiet_hours: { start: "22:00", end: "07:00" }
    rate_limit_per_minute: 10
    max_scheduled: 5
approval_required:
  - { devices: ["lock.*"], actions: [unlock] }
limits:
  thermostat: { min_celsius: 16, max_celsius: 26 }
```

Full example: [`src/home_agent_sandbox/policy.yaml`](src/home_agent_sandbox/policy.yaml).

## Benchmark (measured)

`python examples/bench.py --tasks 100000` on a 2-vCPU Linux machine, Python 3.13.
Memory is Python allocations measured with `tracemalloc`.

| Metric | Result |
| --- | --- |
| Memory per queued task | **313 bytes**, down from 513 in the first version (−39%) |
| Of which `__slots__` alone saves | 13% versus a plain dataclass |
| Scheduler throughput | ~470,000 due tasks executed per second (one `tick`, no conflicts) |
| Cancel 90% of 100,000 tasks | ~0.1 s; heap compacted from 100,000 to 12,499 entries |

What cut memory from 513 to 313 bytes: interning agent, device and action names (strings
parsed from each JSON request are new objects), storing empty parameters as `None`
instead of a new dict, and dropping a sequence counter from each heap entry.

## Honest limitations

- Devices are **simulated**. A real deployment would put an adapter behind `Device.apply`
  for Home Assistant, Matter or a vendor API.
- State is **in memory in one process**. Multiple servers would need a shared store
  (for example Redis or SQLite) for tasks, approvals and rate-limit windows.
- Agent identity comes from the `--agent` flag. Over a network it should come from a
  verified OAuth token, which is what my [mcp-guard](https://github.com/surendrachallagundla301/mcp-guard)
  project does.
- Approvals are polled through MCP tools. A real product would push them to the
  homeowner's phone.

## License

MIT