Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
13 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,31 @@ print(env.ready, env.problems) # False ['shop: seeded']
asked, or answers no `WebsiteReadiness`, is a problem itself. A card or child without `ready`, an MCP server's or an
older site's, isn't counted, so an env with no site serving it is ready with no problems.

## Websites with tools

A website env may also be an MCP server, so an agent can act on a site through tools as well as its pages. Give a
`WebsiteEnvironment` `@tool` (or `@resource`) methods, as an MCP env has; they need the `mcp` package. The site then
serves them at `/mcp` (streamable HTTP) beside its pages, `@api` routes and data plane, and its card declares that
endpoint as its `mcp` interface (`additionalInterfaces`) and lists the tools under `capabilities.tools`. A site without
tools serves no `/mcp` and declares no interface; `serves_mcp()` says which a site is.

```python
@environment_card(name="shop")
@website(domains=["shop.example"], static="dist")
class Shop(WebsiteEnvironment):
@tool()
def place_order(self, item: str, ctx: ToolContext) -> str:
"""Place an order for item, as the caller."""
...
```

A tool runs in the site's process, so it changes what its pages show and what `data/get` returns, and it reads the
universe's time (`self.now()`) as a page's request does. The gateway reads each site's card when it starts, and serves
the tools of a site whose card declares an `mcp` interface as it does an MCP env's: listed to agents with the rest,
called with the caller's role in `ToolContext`. The site's `/mcp` is one of the paths its card advertises, which its
browsing route (`/website/<name>/`) never reaches. `python -m agentenv_protocol.website.conformance` checks a declared
endpoint (`mcp`): it answers `initialize` and lists the tools the card does.

## Computer drivers

A computer driver is what runs inside a computer an agent uses through screenshots and input. Write
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
web/node_modules/
web/dist/
26 changes: 26 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
ARG NOTES=packages/agentenv-protocol/examples/website/notes

FROM mirror.gcr.io/library/node:22-slim@sha256:4b150b48b4116e2a22f2c39cc27025fbf4f153e2078fd3b14d159fdb5c7279da AS web
ARG NOTES
WORKDIR /web
COPY ${NOTES}/web/package.json ${NOTES}/web/package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY ${NOTES}/web/ ./
RUN npm run build

FROM mirror.gcr.io/library/python:3.12-slim@sha256:423ed6ab25b1921a477529254bfeeabf5855151dc2c3141699a1bfc852199fbf
ARG NOTES
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*
COPY packages/agentenv-protocol /tmp/agentenv-protocol
RUN pip install --no-cache-dir /tmp/agentenv-protocol "uvicorn>=0.30" && rm -rf /tmp/agentenv-protocol
COPY ${NOTES}/site.py /app/site.py
COPY ${NOTES}/data /app/data
COPY --from=web /web/dist /app/web/dist
ENV PORT=8000
EXPOSE 8000
RUN useradd --create-home --uid 10001 appuser
USER appuser
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
CMD python -c "import os, urllib.request; urllib.request.urlopen('http://127.0.0.1:%s/.well-known/agent-env.json' % os.environ.get('PORT', '8000'), timeout=2)"
CMD ["python", "site.py"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
**/node_modules
**/dist
**/__pycache__
**/.pytest_cache
**/.venv
.git
89 changes: 89 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Notes: a reference website/v1 site

Notes is a small notes app built on `agentenv_protocol.website.WebsiteEnvironment`. It is the reference site for the
`urn:agentenv:website/v1` server contract. Each user keeps their own notes and can create, edit, mark done and delete
them. The page shows the universe's time.

| File | What it is |
| --- | --- |
| `site.py` | The server: the `Notes` WebsiteEnvironment, its `@api` routes, and `serve()` on `PORT` (8000). |
| `data/seed.json` | The seed data: two users (`ann`, `ben`), their notes, and `current_user`, the acting user. |
| `web/` | A minimal Vite app (`index.html`, `src/main.js`, `src/style.css`). Its assets (`base: "./"`) and API calls are relative to the page, so it works at `/` and under the gateway's `/website/notes/` alike; opened at a path without its final slash, such as `/website/notes`, the page first reloads itself with it. |
| `Dockerfile` | The server image: Node builds `web/`, then Python installs this repo's `packages/agentenv-protocol` with uvicorn. It installs `curl`, which the gateway's compose health check runs against the card. |
| `env.toml` | The website env as a bundle entry. |

## What it exercises

- **Site declaration.** `@website(domains=["notes.test"], static="web/dist")`. The card advertises website/v1 with
the domains and every route by name.
- **Routes.** `list_users`, `sign_in`, `list_notes` (with an optional `?done=`), `create_note` (201), `get_note`,
`edit_note`, `toggle_note` and `delete_note`. Errors are raised as `NotFound`, `BadRequest` and `Unauthorized`.
- **Roles.** `all_notes` (`GET /api/admin/notes`) is declared with `roles=["admin"]`. It answers only a caller that
sends `AgentEnv-Role: admin` with `AgentEnv-Role-Key` equal to the container's `WEBSITE_ROLE_KEY`; any other caller
gets 403. The gateway passes on whatever role a browser sends, so without the key a page could claim `admin`; with no
`WEBSITE_ROLE_KEY` set, every caller is `default` and the route is closed.
- **Users.** `ApiContext.user` is the user in the signed session cookie. With no cookie, it is the acting user (the
data's `current_user`, which `acting_user()` returns), and `GET /api/session` signs that user in. `POST /api/sign-in` switches to another seeded
user. A user's notes are invisible to every other user, and another user's note answers 404.
- **State.** The site keeps its users and notes itself, starting from `data/seed.json`, and serves them through its
data hooks: `data/add` adds a part's records by id (a data part, or a file part by bytes or `file://`), `data/get`
exports them, and `data/reset` empties them. `data/get` is how agentenv reads what a task left the site with.
- **Time.** Notes are stamped with `self.now()`, which follows the gateway's clock once `clock/v1`'s `sync_time` names
it. The frontend reads `X-Universe-Now` from every API response into `universeNow()` and shows it in the header.
It uses this helper rather than `clock_patch=True`, so the page works the same against a server written without the
SDK.
- **Readiness.** website/v1's `ready`, through the card, says not ready (`@ready_check seeded`) until the site has
users, for example after a `data/reset` and before the next `data/add`. The site serves no health path.

## Run it

From this folder:

```bash
cd web && npm ci && npm run build && cd ..
PYTHONPATH=<repo>/packages/agentenv-protocol/src python site.py
```

Open http://localhost:8000. To work on the frontend, run `npm run dev` in `web/` while `site.py` runs; Vite proxies
`/api` to port 8000.

## Test it

```bash
python -m pytest packages/agentenv-protocol/tests/test_website_notes_example.py
```

The test imports `site.py`, runs the conformance checker, and checks sign-in, per-user notes, the admin-only route,
clock-synced timestamps, and the data plane's reset and seed load. It serves a stand-in page, so it needs no Vite
build.

## Build and verify the image

The build context is the repo root, because the image installs the protocol package from this repo's source:

```bash
docker build -f packages/agentenv-protocol/examples/website/notes/Dockerfile -t notes-site .
docker run -d --name notes-site -p 18080:8000 notes-site
python -m agentenv_protocol.website.conformance http://localhost:18080 --clock-host host.docker.internal
curl -s http://localhost:18080/api/notes
```

Use `--clock-host` so the container can reach the checker's clock. The clock check leaves the server following a
clock that is gone once the check ends: later timestamps start from 2031 until the server is synced again, so restart
the container before using it.

## Register it

```bash
agent-env env website put --id notes-site \
--server-dockerfile packages/agentenv-protocol/examples/website/notes/Dockerfile \
--server-docker-context .
```

Run it from the repo root. `environment_name` comes from the card (`@environment_card(name="notes")`). The stored env
has a server image and no frontend image. Pass `--skip-validation` to register without deploying.

`env.toml` describes the same env for a bundle. Its keys are `type`, `environment_name` and
`backend_image`. Domains are not one of them: they come from the card. A bundle builds `backend_image` with this
folder as the build context, but this Dockerfile needs the repo root. Until the protocol package is installed from a
published release instead, register the site with `put` as above.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"current_user": "ann",
"users": [
{"id": "ann", "name": "Ann Lee"},
{"id": "ben", "name": "Ben Ortiz"}
],
"notes": [
{"id": 1, "owner": "ann", "title": "Buy milk", "body": "Oat, two cartons.", "done": false,
"created_at": "2026-01-05T09:00:00.000Z", "updated_at": "2026-01-05T09:00:00.000Z"},
{"id": 2, "owner": "ann", "title": "Book dentist", "body": "", "done": true,
"created_at": "2026-01-04T15:30:00.000Z", "updated_at": "2026-01-06T08:10:00.000Z"},
{"id": 3, "owner": "ben", "title": "Draft the quarterly report", "body": "Due Friday.", "done": false,
"created_at": "2026-01-03T11:00:00.000Z", "updated_at": "2026-01-03T11:00:00.000Z"}
]
}
3 changes: 3 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/env.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
type = "website"
environment_name = "notes"
backend_image = { dockerfile = "Dockerfile" }
208 changes: 208 additions & 0 deletions packages/agentenv-protocol/examples/website/notes/site.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
"""Notes: the reference site of ``urn:agentenv:website/v1``, a small notes app on WebsiteEnvironment. Each user keeps
notes they create, edit, mark done and delete; a browser with no session is signed in as the acting user, the seed's
``current_user``, and can sign in as another seeded user. The site keeps its users and notes itself, behind one lock
since plain ``def`` handlers run in worker threads, starting from ``data/seed.json``, and serves them through the data plane (``data/get``, ``data/reset``, ``data/add``), as any
AgentEnvEnvironment does; it stamps each note with the universe's time. ``admin`` callers, as the gateway's
``AgentEnv-Role`` names them, can list every user's notes.

Run it with ``python site.py`` after building ``web/`` into ``web/dist``; it serves on ``PORT`` (8000)."""
from __future__ import annotations

import base64
import copy
import json
import threading
from pathlib import Path
from typing import Optional
from urllib.parse import unquote, urlparse

from pydantic import BaseModel

from agentenv_protocol import DataPart, FilePart, TextPart, add_data, environment_card, get_data, reset_data
from agentenv_protocol.website import (
ApiContext,
BadRequest,
NotFound,
Unauthorized,
WebsiteEnvironment,
api,
ready_check,
website,
)
from agentenv_protocol.website.clock import iso

NOTES = "notes"
USERS = "users"
SEED = Path(__file__).resolve().parent / "data" / "seed.json"


class NewNote(BaseModel):
title: str
body: str = ""


class NoteEdit(BaseModel):
title: Optional[str] = None
body: Optional[str] = None
done: Optional[bool] = None


class SignIn(BaseModel):
user: str


@environment_card(name="notes")
@website(domains=["notes.test"], static="web/dist")
class Notes(WebsiteEnvironment):
def __init__(self) -> None:
super().__init__()
self._lock = threading.Lock()
self.data: dict = json.loads(SEED.read_text(encoding="utf-8"))

def acting_user(self) -> Optional[str]:
with self._lock:
return self.data.get("current_user")

@ready_check
def seeded(self) -> bool:
"""The site is usable once it knows who may sign in."""
with self._lock:
return bool(self.data.get(USERS))

@reset_data
def reset(self) -> None:
with self._lock:
self.data = {}

@add_data
def add(self, parts: list) -> None:
"""Each part's JSON, its collections' records added by id and its other fields set, as the seed is."""
loaded = [_part_data(part) for part in parts]
with self._lock:
for data in loaded:
for key, value in data.items():
if isinstance(value, list):
kept = {record["id"]: record for record in self.data.get(key, [])}
kept.update({record["id"]: copy.deepcopy(record) for record in value})
self.data[key] = list(kept.values())
else:
self.data[key] = copy.deepcopy(value)

@get_data
def export(self) -> list:
with self._lock:
return [DataPart(data=copy.deepcopy(self.data))]

@api.get("/api/users", name="list_users")
def list_users(self) -> list:
"""The users a browser can sign in as."""
with self._lock:
return copy.deepcopy(self.data.get(USERS, []))

@api.post("/api/sign-in", name="sign_in")
def sign_in(self, body: SignIn, ctx: ApiContext) -> dict:
"""Sign the browser in as one of the site's users."""
with self._lock:
known = any(user["id"] == body.user for user in self.data.get(USERS, []))
if not known:
raise NotFound(f"no user {body.user!r}")
ctx.sign_in(body.user)
return {"user": ctx.user}

@api.get("/api/notes", name="list_notes")
def list_notes(self, ctx: ApiContext, done: Optional[bool] = None) -> list:
"""The signed-in user's notes, newest first; with ``done``, only those done or not."""
user = self._user(ctx)
with self._lock:
mine = [copy.deepcopy(n) for n in self.data.get(NOTES, [])
if n["owner"] == user and (done is None or n["done"] == done)]
return sorted(mine, key=lambda note: note["created_at"], reverse=True)

@api.post("/api/notes", name="create_note", status=201)
def create_note(self, note: NewNote, ctx: ApiContext) -> dict:
"""Add a note for the signed-in user, not done, created and updated now."""
owner, title, now = self._user(ctx), _title(note.title), iso(self.now())
with self._lock:
notes = self.data.setdefault(NOTES, [])
created = {"id": max((n["id"] for n in notes), default=0) + 1, "owner": owner, "title": title,
"body": note.body, "done": False, "created_at": now, "updated_at": now}
notes.append(created)
return copy.deepcopy(created)

@api.get("/api/notes/{note_id:int}", name="get_note")
def get_note(self, note_id: int, ctx: ApiContext) -> dict:
with self._lock:
return copy.deepcopy(self._note(note_id, ctx))

@api.patch("/api/notes/{note_id:int}", name="edit_note")
def edit_note(self, note_id: int, edit: NoteEdit, ctx: ApiContext) -> dict:
"""Change a note's title, body or done, and its ``updated_at``."""
fields = edit.model_dump(exclude_none=True)
if "title" in fields:
fields["title"] = _title(fields["title"])
now = iso(self.now())
with self._lock:
note = self._note(note_id, ctx)
note.update(fields, updated_at=now)
return copy.deepcopy(note)

@api.post("/api/notes/{note_id:int}/toggle", name="toggle_note")
def toggle_note(self, note_id: int, ctx: ApiContext) -> dict:
"""Mark a note done, or not done when it was."""
now = iso(self.now())
with self._lock:
note = self._note(note_id, ctx)
note.update(done=not note["done"], updated_at=now)
return copy.deepcopy(note)

@api.delete("/api/notes/{note_id:int}", name="delete_note")
def delete_note(self, note_id: int, ctx: ApiContext) -> dict:
with self._lock:
note = self._note(note_id, ctx)
self.data[NOTES] = [n for n in self.data[NOTES] if n is not note]
return {"deleted": note_id}

@api.get("/api/admin/notes", name="all_notes", roles=["admin"])
def all_notes(self) -> list:
"""Every user's notes, for an ``admin`` caller only."""
with self._lock:
return copy.deepcopy(self.data.get(NOTES, []))

def _user(self, ctx: ApiContext) -> str:
if ctx.user is None:
raise Unauthorized("sign in first")
return ctx.user

def _note(self, note_id: int, ctx: ApiContext) -> dict:
"""The signed-in user's note ``note_id``, read under the lock; another user's is as missing as one that
doesn't exist."""
note = next((n for n in self.data.get(NOTES, []) if n["id"] == note_id), None)
if note is None or note["owner"] != self._user(ctx):
raise NotFound(f"no note {note_id}")
return note


def _part_data(part) -> dict:
"""A part's JSON: a data part's data, a text part's text, or a file part's bytes or ``file://`` file."""
if isinstance(part, DataPart):
return part.data
if isinstance(part, TextPart):
return json.loads(part.text)
if isinstance(part, FilePart):
if getattr(part.file, "bytes", None) is not None:
return json.loads(base64.b64decode(part.file.bytes))
uri = urlparse(part.file.uri)
if uri.scheme == "file":
return json.loads(Path(unquote(uri.path)).read_text(encoding="utf-8"))
raise ValueError(f"Notes reads a file part by its bytes or a file:// URI, not {part.file.uri!r}")
raise ValueError(f"Notes can't read a {type(part).__name__}")


def _title(title: str) -> str:
if not title.strip():
raise BadRequest("a note needs a title", code="empty_title")
return title.strip()


if __name__ == "__main__":
Notes().serve()
Loading
Loading