Skip to main content
Glama
MCPET
by oliverseges
README.md
# MCPET

**Small paws. Big feelings. A virtual pet that lives in your agent chat.**

Adopt **any animal, imaginary creature, or hybrid**. Feed it, groom it, play together, and win its affection
using ordinary conversation. Keep a separate companion per agent, or release one
and adopt again. Pet actions return useful text, **action-aware ASCII art**, structured
status, and an original locally rendered PNG portrait when a pet exists.
Health, loneliness, personalities, adventures, tricks, supplies, XP, badges, and
a tiny diary give those little visits a life of their own.
No API keys, image downloads, paid services, or extra model required.

![Mochi, an original MCPET cat, with health, hunger, happiness, love, cleanliness, and energy meters](docs/mochi.png)

![Pip, an original agent-template-style dragon-axolotl with wings, horns, and pink gills](docs/pip.png)

> This is a real **Streamable HTTP MCP server**, not a chat app or custom widget.
> Your agent host must support HTTP MCP tools. Inline image display depends on
> that host's handling of native MCP image results; some hosts expose images only
> to the model, collapse tool results, or show text only. Text meters always
> accompany the image. This project cannot force a host to display it.

## Start in two minutes

Requires **Node.js 22.18+** and npm. In PowerShell:

```powershell
git clone https://github.com/oliverseges/MCPET.git
Set-Location .\MCPET
npm ci
npm run build
npm start
```

Already cloned or downloaded the project? Change to its directory and start at
`npm ci`. Keep the process running while chatting.

| Endpoint | Purpose |
| --- | --- |
| `http://127.0.0.1:3000/mcp` | Streamable HTTP MCP connection |
| `http://127.0.0.1:3000/health` | JSON readiness check |

```powershell
Invoke-RestMethod http://127.0.0.1:3000/health
```

## Connect your agent

In your host's MCP server settings, add an **HTTP / Streamable HTTP** server
named `mcpet` with URL `http://127.0.0.1:3000/mcp`. No token or custom headers
are required. Approve only the tools you want the agent to use. This project
does **not** modify your global agent configuration or register itself.

For **VS Code**, merge into `.vscode/mcp.json`:

```json
{
  "servers": {
    "mcpet": {
      "type": "http",
      "url": "http://127.0.0.1:3000/mcp"
    }
  }
}
```

For hosts that use an `mcpServers` configuration with HTTP transports:

```json
{
  "mcpServers": {
    "mcpet": {
      "type": "http",
      "url": "http://127.0.0.1:3000/mcp"
    }
  }
}
```

Configuration formats differ between hosts; use its HTTP settings if it rejects
this shape. Do not configure this as an SSE-only `/sse` server or a stdio command.
An HTTP server runs separately; adding the URL does not start Node for you.
Only a host on this computer can reach this loopback address: cloud-hosted agents
cannot connect to your machine's `127.0.0.1`.

Then say:

> Adopt a bunny named Waffles.
>
> Adopt a dragon-axolotl named Pip, with mint scales, gold wings, and pink gills.
>
> How is my pet? Show its picture and meters.
>
> Feed Waffles, groom them, and play together.
>
> Give Waffles a cuddle and a cozy nap.
>
> Teach Pip to wave, then take them stargazing.
>
> Read my pet's diary. What have we achieved together?

The host discovers the tools and the agent chooses calls from your conversation.
No background agent or model runs inside MCPET. Tools act only when called.
Choose one adoption example: an existing companion is never replaced.

## A pet per agent, and safe goodbyes

Every tool accepts an `agent_id`. Choose a stable key unique to each
agent/conversation and **reuse it on every call**, including after reconnecting:

```json
{"agent_id": "research-thread-42", "name": "Pip", "species": "dragon-axolotl"}
```

That is an `adopt_pet` call. Feed the same pet using:

```json
{"agent_id": "research-thread-42"}
```

Use the same argument for `get_pet`, `play_with_pet`, `groom_pet`, `cuddle_pet`,
`rest_pet`, `mistreat_pet`, and `apologize_to_pet`. Appearance editing adds its
`appearance` field alongside `agent_id`. Valid IDs are 1-64 lowercase letters,
digits, hyphens, or underscores, starting with a letter or digit. Paths are not
accepted or used to select save files.

Different keys mean independent pets, not different HTTP connections. All slots
survive reconnects and server restarts in the same save file. Omitted IDs retain
the **shared `default` slot** for compatibility: the existing legacy pet stays
there unchanged. Ask for `agent_id: "default"` when caring for that companion.
Two agents that omit the ID still share that slot; the server cannot infer their
identities. Hosts do not universally send stable agent identifiers, so the agent
must remember its key in the conversation or host instructions. Losing that
context does not delete the pet, but you need the original key to find it again.

To get rid of a pet, explicitly ask the agent to release it. `release_pet`
requires confirmation in its arguments:

```json
{"agent_id": "research-thread-42", "confirm": true}
```

It removes **only that slot's** saved pet, appearance, and care history, depicting
a safe move to the sanctuary. You may then call `adopt_pet` for that same ID.
Release also works for a runaway pet. Other slots, including `default`, are not
affected. The tool is marked destructive, is never called as routine care, and
has no undo; missing or false confirmation is rejected.

Agent IDs provide **logical isolation, not authentication or access control**.
A caller that knows another key can explicitly operate that slot. Use separate
server instances/data directories if you need different trust boundaries.

## Little ASCII moments

Pet actions include a fenced, monospace drawing beside the reaction and meters:

```text
* brush brush *    ||||||
  (\_/)
  (o.o)
  (")(")
```

Feeding gets a dinner caption, play a bouncing toy, cuddles hearts, and naps
sleepy eyes and `z Z z`. Adoption, redraws, apologies, warnings, releases, and
sanctuary stays have their own moments too. Cats, dogs, and bunnies have small
ASCII silhouettes; all other real or invented species use a generic creature.
It is a lightweight text illustration, not an anatomically accurate rendering of
the vector template. No extra model call is made. Even text-only MCP hosts can
read it; whether the agent echoes a tool result into its final reply is up to
that host and agent. Validation errors rejected before a tool runs use the SDK's
ordinary error response instead.

## Any creature, drawn by your agent

`species` is now a free-form, single-line description (1-80 characters), not a
fixed animal list: `octopus`, `moon-moth`, `cloud dragon`, or `owl-cat with
butterfly wings` are all valid. Care mechanics work identically for every creature.

The calling agent can fill in an optional **appearance template** during adoption,
or call `set_pet_appearance` to redraw the current companion later. It is a small
vector scene, not a prompt for an image model. MCPET rasterizes those shapes into
the same native PNG tool result as before. No image-generation capability,
external model, API key, raw SVG, or downloaded artwork is needed.

For example, the agent can call `adopt_pet` with:

```json
{
  "name": "Pip",
  "agent_id": "research-thread-42",
  "species": "mint dragon with golden wings",
  "appearance": {
    "shapes": [
      {"type": "polygon", "points": [{"x": 110, "y": 170}, {"x": 15, "y": 95}, {"x": 35, "y": 235}], "fill": "#edc984"},
      {"type": "polygon", "points": [{"x": 210, "y": 170}, {"x": 305, "y": 95}, {"x": 285, "y": 235}], "fill": "#edc984"},
      {"type": "ellipse", "cx": 160, "cy": 225, "rx": 65, "ry": 68, "fill": "#94c6b5"},
      {"type": "polygon", "points": [{"x": 119, "y": 99}, {"x": 121, "y": 31}, {"x": 151, "y": 88}], "fill": "#edc984"},
      {"type": "polygon", "points": [{"x": 169, "y": 88}, {"x": 199, "y": 31}, {"x": 201, "y": 99}], "fill": "#edc984"},
      {"type": "ellipse", "cx": 160, "cy": 139, "rx": 79, "ry": 68, "fill": "#a9d8c6"}
    ],
    "face": {"x": 160, "y": 139, "scale": 1}
  }
}
```

The template's canvas is **320 x 320**. Shapes are drawn in array order, back to
front, and clipped to that canvas. There can be 1-64 shapes:

| Shape `type` | Required geometry |
| --- | --- |
| `ellipse` | `cx`, `cy`, `rx`, `ry` |
| `rect` | `x`, `y`, `width`, `height`; optional `cornerRadius` |
| `polygon` | `points`: 3-32 objects with `x`, `y` |
| `line` | `x1`, `y1`, `x2`, `y2` |

Coordinates are 0-320; positive sizes are at most 320. Filled shapes support
`fill`, `stroke`, and `strokeWidth` (0-8). Paint is a six-digit hex color such as
`#94c6b5`, or `none`; default fill is mint, default stroke is none. Lines default
to a brown, 3-pixel stroke and accept a width of 1-8.

The optional `face` positions the automatically mood-animated eyes, cheeks,
nose, and mouth; leave space in the head for them. Defaults are the example's
center and scale. `x` may be 60-260, `y` 60-250, and `scale` 0.4-1.3.
Set `face.visible` to `false` for an eyeless creature or to draw your own face
using shapes. Status meters and mood text still update; a fully custom face's
expression is then up to the drawing rather than automatically animated.

These are stylized vector companions, not photorealistic illustrations or
unrestricted generative images. The species name is preserved in text even if
the template is only an approximation. Cat, dog, and bunny retain their built-in
portraits. Other species without a supplied template get an explicitly labeled
generic companion image, which the agent can refine later. Template validation
rejects scripts, raw SVG, URLs, extra attributes, and oversized input rather
than rendering untrusted markup. The existing 32 KiB request limit still applies.

Existing saves without an appearance keep working. Redrawing a pet changes
**only its appearance**, not its identity, adoption date, history, or care meters
(normal elapsed-time effects still apply). No pet is reset during this upgrade.
After updating a running server, reconnect/refresh the host's MCP tools so the
agent discovers the new template and `set_pet_appearance` tool.

## The tiny handbook

One pet lives in each stable agent slot. Connected clients using the same
`agent_id` care for the same pet; adopting twice will not overwrite it.

**Ask about your pet and get its full card.** `get_pet` returns the portrait PNG
with all six status meters, matching text stats, mood, and ASCII art, just like
care actions. The server instructs the agent to present the whole card rather
than only a mood summary. This works for arbitrary species and custom drawings.
Native image display still depends on the host; all six stats are included in
text even when a host cannot display the PNG.

| Tool | What happens |
| --- | --- |
| `adopt_pet` | Choose `name` (1-24 letters/numbers/spaces/apostrophes/hyphens), any `species` description (`cat` default), optional `appearance`, and `personality`: `curious` (default), `sassy`, `gentle`, or `dramatic` |
| `set_pet_appearance` | Supply an `appearance` template to redraw the current companion without replacing it |
| `release_pet` | Explicitly remove the selected slot's pet using `confirm: true`, then adopt again |
| `get_pet` | Portrait, mood, text meters, warnings, and care advice |
| `feed_pet` | Hunger -35, happiness +8, love +4; refuses if hunger is below 10 |
| `play_with_pet` | Happiness +22, love +7, energy -20, hunger +10, cleanliness -8; needs 20 energy and hunger below 85 |
| `groom_pet` | Cleanliness +35, happiness +8, love +5 |
| `cuddle_pet` | Love +12, happiness +10 |
| `rest_pet` | An immediate cozy nap restores 35 energy; does not fast-forward time |
| `mistreat_pet` | Explicit fictional teasing/scolding only: happiness -30, love -25, one boundary warning |
| `apologize_to_pet` | At home: removes one warning, love +3. Away: invites the pet home after an hour |
| `vet_pet` | Explicit rescue/healing: health +60, hunger at most 35, energy at least 55, happiness at least 40, cleanliness at least 70; clears neglect, preserves identity/history |
| `pet_activity` | One coherent activity menu: adventure, learn/perform trick, use/buy item, or journal; see below |

All tools accept `agent_id` (default: `default`). Care/status tools need no other
arguments; adoption, appearance editing, release, and activities have the fields above. All meters clamp to
0-100. **Hunger is better low; every other meter is better high.** Illustrations
reflect species, health, mood, low energy, dirt, high affection, and sanctuary stays.

### Health, starvation, loneliness, and recovery

Per real hour: hunger +3, happiness -1.5, cleanliness -1, love -0.3,
energy +4. A new pet starts with **100 health**. While hunger is at **100**,
starvation removes **6 health per hour**. The calculation integrates only time
after hunger actually reaches 100: reaching it at the end of an interval does
not charge damage for the whole interval. Feeding stops further starvation but
does not magically repair damage; visit the vet to heal.

At **health 0**, the pet explicitly **collapses** (`status: "critical"`).
The card shows zero health, a first-aid marker, and a rescue instruction.
Ordinary care and active hobbies refuse until you use `vet_pet`; there is no
silent reset, death, deletion, or automatic rescue. At collapse, biological
decay freezes safely. Status visits, diary/shop access, appearance editing, and
explicit release remain available. A vet visit is free, restores 60 health
(capped at 100), provides a meal and recovery comfort as listed above, and keeps
name, species, adoption date, appearance, XP, inventory, tricks, and diary.
It gives no farmable XP/coins. A healthy pet refuses an unnecessary vet visit.

![Simulated critical-health example card, not the user's real pet](docs/critical.png)

A newly adopted, completely untended pet reaches hunger 100 after **25 hours**
and collapses after approximately **41 hours 40 minutes**. Overnight is safe,
but a long absence has consequences. A different starting hunger/health changes
that time. Starvation collapse can happen before a neglect runaway.

After **8 hours without a successful visit**, loneliness adds another
**-0.5 happiness and -0.2 love per hour** beyond the base decay. On the next
successful visit the pet tells you how long you were away and complains in its
personality: a dramatic pet wrote an opera about your empty doorway; a sassy
one became friends with the furniture. A visit resets the absence clock, not
the lost health or affection. The complaint occurs once per absence; subsequent
immediate checks do not punish or repeat it.

Successful `get_pet`, adoption, care, vet recovery, adventures, trick practice,
performances, and item use count as visits. **Tool discovery, failed/invalid
actions, shop purchases, diary reading, and portrait editing do not.** A failed
game action can still reveal and persist elapsed biological changes, but never
marks the pet visited. Invalid arguments rejected by the SDK do neither.

Time is applied lazily on the selected slot's next tool call, including offline
time. There is no background scheduler and no unsolicited notification. Queries
and actions on one slot never age or visit another. Threshold crossings are
integrated mathematically so splitting an offline interval into repeated checks
doesn't double-count starvation; actual successful visits intentionally reset
loneliness for future time.

### Neglect and boundaries

Critical neglect starts when hunger reaches 90, happiness reaches 10, or
cleanliness reaches 5. After **48 accumulated critical hours**, the pet moves
to a safe neighborhood sanctuary **if it has not collapsed first**. Resolving
**all** critical needs clears this counter. The earliest event wins: a sanctuary
stay or critical collapse freezes subsequent biological decay. Sanctuary pets
do not continue starving while cared for there.

Three mistreatment warnings also cause a runaway. The agent is instructed never
to invoke mistreatment unless explicitly requested, and that tool is annotated
as destructive. Reactions are cartoonish, never graphic. Ordinary care never
adds boundary warnings. Adopting alone cannot replace a runaway pet; apologize
to recover it, or explicitly release that slot before adopting another companion.

After **one real hour away**, `apologize_to_pet` brings the pet home with hunger
35, happiness 45, love 30, cleanliness 70, energy 65, and reset warnings. It is
always safe at the sanctuary; this is a gentle game, not a death simulation.
An already-unwell returning pet may still need a vet visit; apology is not a
health reset.

### Adventures, tricks, supplies, and a little life story

Only two extra tools power the extension: `vet_pet` and `pet_activity`.
Keep reusing your `agent_id`. For an adventure, call `pet_activity` with:

```json
{
  "agent_id": "research-thread-42",
  "activity": {"kind": "adventure", "destination": "stargaze"}
}
```

The schema advertises distinct, validated fields for each activity:

| `activity` object | Cost and effect |
| --- | --- |
| `{"kind":"adventure","destination":"garden"}` | Destinations: `garden`, `stargaze`, `treasure_hunt`. Needs health >=30, energy >=25, hunger <80. Energy -20, hunger +10, cleanliness -5, happiness +15; +15 XP, +3 coins, +1 treat if space. Shared **2-hour cooldown** across all destinations |
| `{"kind":"learn_trick","trick":"wave"}` | Tricks: `wave`, `spin`, `bow`, expressed in any species' own style. Needs health >=30, energy >=15, hunger <85. Energy -10, hunger +5, +10 XP. Shared **30-minute learning cooldown**; cannot learn the same trick twice |
| `{"kind":"perform_trick","trick":"wave"}` | Must know the trick. Needs health >=30, energy >=5, hunger <85. Energy -5, hunger +2, happiness +8, love +3, +3 XP. Shared **10-minute performance cooldown** |
| `{"kind":"buy_item","item":"treat"}` | Treat costs **2 coins**, toy **4 coins**; one item per call. Rejects insufficient funds/full inventory; purchases are not visits |
| `{"kind":"use_item","item":"treat"}` | Consumes one treat: hunger -15, happiness +12, love +5. Needs health >=30, at home, hunger >=5; refuses full pets |
| `{"kind":"use_item","item":"toy"}` | Consumes one toy: happiness +20, love +5, energy -10, hunger +5. Needs health >=30, at home, energy >=10, hunger <85 |
| `{"kind":"journal"}` | Read the latest **20** timestamped memories alongside the full card, inventory, tricks, and achievements; not a visit, no rewards |

New pets receive **6 coins, 2 treats, and 1 toy**. Inventory is capped at
**5 treats, 3 toys, and 99 coins**. Positive ordinary care (feed/play/groom/
cuddle/rest) earns **5 XP and 1 coin at most once per 20 minutes**, shared across
those actions. Repeating other care within that interval still helps but does
not farm rewards. Status checks, shopping, journal reads, warnings, apologies,
and vet visits earn no XP/coins. Consuming items earns no XP/coins either.

**Level = 1 + floor(XP / 50)**, capped at level **20** (950 XP).
Age is real elapsed time since the original adoption; it never resets on rescue.
Cooldowns, rewards, supplies, learned tricks, and progression persist through
restarts. Adventures are deterministic, whimsical little stories, not real
travel or network calls. There are no purchases with real money.

Five achievements commemorate milestones: `first_meal` (ordinary feed),
`best_friends` (love >=90 after care/activity), `trailblazer` (first adventure),
`trickster` (first learned trick), and `rescued` (first collapse recovery).
The bounded diary remembers adoption, care, adventures, learning, shopping,
absence complaints, collapse, rescue, and sanctuary events; oldest entries roll
off after 20. It is not an unlimited audit log or a real-world health tracker.

## Persistence and local safety

- State is stored in `data\pet.json`, relative to the project, independent of
  the launch directory. Only this pet data is written during normal operation.
  The legacy/default pet remains in the root `pet` field; additional agent slots
  live under `agents` in the same JSON file. New writes use **version 2**.
  Version-1 pets are upgraded lazily **only when that slot is accessed**, retaining
  their identity, old meters, and existing care/runaway history. They receive 100
  health and fresh health/absence clock baselines at that moment, never
  retroactive starvation or an absence complaint based on unknown history.
  Old biological neglect rules still apply; other unvisited legacy slots are
  preserved unchanged even inside a version-2 file. No manual migration required.
- Updates are serialized, validated, flushed, and atomically renamed. A
  heartbeat-backed directory lock prevents two server processes writing the
  same data. The lock directory is a transient sibling of `pet.json`.
- Invalid or corrupt save data causes a clear startup failure, never an
  automatic reset. Back up `pet.json` with the server stopped.
- The server binds **only `127.0.0.1`**. SDK Host and Origin guards reject
  non-localhost values, preventing ordinary DNS rebinding and cross-origin
  browser access. Requests are capped at 32 KiB.
- There is no authentication: **other processes/users on your computer can
  operate any known pet slot**. Do not expose it through a public proxy or tunnel.
  Loopback Origin checks are not a substitute for authentication.
- Pet data, dependencies, logs, build outputs, and local environment files are
  excluded from Git. No telemetry or external service calls are made by the app.

Optional PowerShell settings:

```powershell
$env:PORT = "3001"
$env:MCPET_DATA_DIR = Join-Path $HOME "MCPET-data"
npm start
```

`MCPET_DATA_DIR` is optional; relative overrides resolve from the launch directory.
Use distinct `agent_id` values for independent pets on one server, and
`release_pet` for an explicitly requested fresh start in one slot. Different
data directories and ports provide completely separate server instances.

## Development and GitHub readiness

```powershell
npm run check
npm test
npm run build
npm run dev
```

`npm run demo` regenerates `docs\mochi.png`, `docs\pip.png`, and the simulated
`docs\critical.png` without touching your actual pet. Cards are 800 x 540 PNG.
The source is TypeScript, using the official MCP SDK v2, Zod validation,
`sharp` for SVG-to-PNG rendering, and `proper-lockfile` for process exclusion.
The pet graphics are original SVG shapes, not downloaded artwork.

Tests use isolated temporary save directories and ephemeral loopback ports.
They cover care limits, elapsed and offline neglect, runaway recovery, concurrent
updates, corrupt-save protection, process locking, and real MCP HTTP discovery
and tool calls with PNG decoding, restart persistence, and Host/Origin checks.
They also cover arbitrary/hybrid species, appearance editing without resetting
care, legacy saves, exact rendered shape pixels, and rejection of unsafe templates.
Agent tests exercise isolated care, release and re-adoption, reconnection with
stable IDs, invalid IDs, and preservation of the default pet. HTTP action tests
check the accompanying fenced ASCII moments too.
Clock-controlled cases cover threshold-crossing starvation, chunk-independent
progression, repeated checks, collapse/rescue, last-visited exclusions, loneliness
complaints, lazy migration, reward/cooldown rules, inventory bounds, and diary limits.
They do not adopt or mistreat your live pet.

A lockfile, MIT license, and GitHub Actions workflow for Node 22 on Windows and
Linux are included. The CI runs `npm ci`, type checking, tests, and a production
build. The package is marked `private` to prevent accidental npm publication;
this does not restrict cloning or running this MIT-licensed GitHub project.
Keep personal MCP/editor configuration and pet saves out of commits.

## Troubleshooting

| Symptom | Fix |
| --- | --- |
| Connection refused | Start `npm start`; check `/health` and the configured port |
| `EADDRINUSE` | Another process has port 3000; stop that specific process or choose another `PORT` |
| Lock already held | Stop the other MCPET using that data directory. After a crash, allow at least 10 seconds for the lock to become stale, then retry |
| Corrupt save | Stop the server and restore a valid backup. Do not delete the save as a first step |
| HTTP 403 | Use the literal loopback URL. Non-local Host/Origin headers, including opaque browser `null` origins, are intentionally rejected |
| No tool list | Use an HTTP MCP-capable host, the exact `/mcp` path, and refresh/reconnect after configuration |
| Text but no picture | Expand the tool response. If the host does not display MCP image blocks, text meters still work; custom inline image rendering cannot be guaranteed |
| Pet is gone | It is safe at the sanctuary; apologize after an hour away |
| Pet collapsed / health zero | Explicitly call `vet_pet` with that pet's `agent_id`; identity and memories are retained |
| Pet complains about an absence | Visit and care for it; the eight-hour loneliness grace restarts on a successful visit |
| An activity is refused | Read its health/hunger/energy/cooldown or inventory feedback; errors do not visit the pet |

`Ctrl+C` shuts down a foreground server gracefully and releases its data lock.
A forced termination leaves only a transient lock that becomes stale.

## SDK references

Implemented against the official [MCP TypeScript SDK v2](https://ts.sdk.modelcontextprotocol.io/v2/),
its [HTTP serving guide](https://ts.sdk.modelcontextprotocol.io/v2/serving/http.html),
and [HTTP client guide](https://ts.sdk.modelcontextprotocol.io/v2/clients/connect.html).
Legacy 2025-era MCP clients are handled by the SDK's compatibility layer.
Context7 was unavailable in the implementation environment, so official docs
and installed SDK types were consulted directly.

## License

[MIT](LICENSE).