Piggy developer guide
How to build an app that uses Piggy: connect to it, send requests, read answers, handle errors, run long jobs with tools, and offer your app’s own tools to those jobs. Written for Piggy 0.6.5.
The code samples were run against a real Piggy. The full, runnable
versions are in examples/.
Contents
- What Piggy is
- What you need from the person
- Choose a connection
- Your first request
- Calling Piggy from code
- The request
- The response
- Structured answers
- Choosing a model
- Errors and retrying
- Limits and timing
- Checking that Piggy is there
- Jobs: long work with tools
- Offering your app’s own tools
- Security checklist
- Versions and compatibility
- Troubleshooting
- All routes
1. What Piggy is
Piggy runs on a person’s Mac. It lets apps use the Claude subscription that person already pays for, instead of paying per word through an API key. Your app sends a request to Piggy; Piggy asks Claude Code, the AI command-line tool on that Mac, under the person’s own account; the answer comes back to your app.
your app --request + your key--> Piggy (on the Mac) --> Claude Code --> Claude
<------------ answer --------------------------------------
Each app has its own key. Piggy knows nothing about your app beyond that key. The model sees only what you send: none of the person’s own Claude settings, instructions or memory reach it.
Piggy suits background work: classifying, extracting, summarising, drafting, checking. Each call takes a few seconds at least, so it is not for anything a person waits on keystroke by keystroke.
2. What you need from the person
The person who installed Piggy gives your app:
| What | Where they get it |
|---|---|
| A key for your app | piggy in the menu bar, Connect an App…, type your app’s name, Connect. Piggy shows the key once. |
| The address | Shown with the key, for each connection that is on (section 3). |
| The certificate (only for the secure connection) | The Piggy window, Connections, next to the certificate: Show File (cert.pem), or Copy (the fingerprint). |
Store the key like a password: in a file only your app can read, or in the macOS Keychain. Never put it in source code, a URL or a log. Piggy keeps only a fingerprint of the key, so it cannot show it again. If your app loses it, the person removes your app and adds it again, which makes a new key; removing an app also removes its job permissions, so the person grants those again.
The person’s Mac needs macOS 13 or later (the installer checks), Claude Code, and a Claude subscription that is signed in (the Piggy window walks them through both).
3. Choose a connection
Piggy offers two connections. Both offer everything; your app picks one.
| Unencrypted | Secure | |
|---|---|---|
| Address | http://127.0.0.1:8377 |
https://127.0.0.1:8379 on the same Mac; https://<mac-name>.local:8379 from another device |
| Reachable from | the same Mac only | the same Mac and other devices on the network |
| Encryption | none | HTTPS with Piggy’s own certificate |
| Your app must | nothing extra | trust Piggy’s certificate (below) |
From another device only the secure connection works; on the same Mac
your app may use either. The person may switch either connection off in
the Piggy window (Connections); at least one is always on. Ports can be changed by the
person, so take the address from them rather than hard-coding it. Use
127.0.0.1, not localhost: Piggy listens on IPv4 only, and some
clients try localhost as the IPv6 address first and fail.
Trusting the certificate
Each Piggy makes its own certificate, so no public authority vouches for it. Your app trusts it in one of two ways:
- The certificate file. Trust exactly that file:
curl --cacert piggy-cert.pem ..., Pythonssl.create_default_context(cafile="piggy-cert.pem"), Nodehttps.request({ca: fs.readFileSync("piggy-cert.pem"), ...}). - The fingerprint. Compare the SHA-256 fingerprint of the
certificate the server presents with the one the person gave you, and
refuse the connection if they differ. The fingerprint is written as
uppercase hex pairs separated by colons, as
openssl x509 -fingerprint -sha256prints it. The Swift example does this.
The certificate covers localhost, 127.0.0.1, ::1, the Mac’s
<name>.local and the IPv4 addresses the Mac had when it was made.
It lasts 825 days. If it is renewed, the person gives you the new file
or fingerprint.
4. Your first request
Unencrypted, on the same Mac:
curl -s http://127.0.0.1:8377/infer \
-H @<(printf 'Authorization: Bearer %s\n' "$(cat piggy-key)") \
-H "Content-Type: application/json" \
-d '{"prompt": "Say hello in five words.", "model": "haiku"}'
Secure:
curl -s --cacert piggy-cert.pem https://127.0.0.1:8379/infer \
-H @<(printf 'Authorization: Bearer %s\n' "$(cat piggy-key)") \
-H "Content-Type: application/json" \
-d '{"prompt": "Say hello in five words.", "model": "haiku"}'
The -H @<(printf ...) form passes the key to curl without putting it
on curl’s command line, where other programs on the Mac could see it.
The answer:
{"request_id": "2d49f7e06989", "output": "Hello, I'm ready to help.",
"structured": false, "wall_s": 8.01, "api_ms": 6214,
"model": ["claude-haiku-4-5-20251001"], "cost_usd": 0.00319,
"usage": {"input_tokens": 10, "output_tokens": 508, "...": "..."}}
5. Calling Piggy from code
Three small clients, standard library only, each with retries (section 10), a timeout and certificate trust built in. Copy one into your app.
| Language | File | Trusts the certificate by |
|---|---|---|
| Python | examples/piggy_client.py |
its file |
| Node.js | examples/piggy-client.mjs |
its file |
| Swift | examples/swift/PiggyClient.swift (copy this file; main.swift beside it is only for trying it) |
its fingerprint |
Each one also runs on its own to try a connection:
python3 examples/piggy_client.py https://127.0.0.1:8379 piggy-key piggy-cert.pem
node examples/piggy-client.mjs https://127.0.0.1:8379 piggy-key piggy-cert.pem
cd examples/swift && swiftc -o try-piggy PiggyClient.swift main.swift && ./try-piggy https://127.0.0.1:8379 piggy-key AB:CD:...
Python:
from piggy_client import Piggy
piggy = Piggy("https://127.0.0.1:8379", key_file="~/.myapp/piggy-key",
certificate="~/.myapp/piggy-cert.pem")
label = piggy.infer(
"Classify this message: 'My invoice total is wrong.'",
model="haiku",
system="You sort customer messages. Answer with one label.",
schema={"type": "object",
"properties": {"label": {"type": "string", "enum": ["billing", "bug", "question"]}},
"required": ["label"]},
)
# {'label': 'billing'}
JavaScript (Node):
import { Piggy } from "./piggy-client.mjs";
const piggy = new Piggy({ baseUrl: "https://127.0.0.1:8379",
keyFile: "/path/piggy-key", certificate: "/path/piggy-cert.pem" });
const answer = await piggy.infer("Summarise this note in one sentence: ...", { model: "haiku" });
Swift:
let piggy = try PiggyClient(baseURL: URL(string: "https://127.0.0.1:8379")!,
key: key, fingerprint: "AB:CD:...")
let answer = try await piggy.infer("Summarise this note in one sentence: ...", model: "haiku")
6. The request
POST /infer (or /v2/infer, the same thing) with your key in
Authorization: Bearer <key> and a JSON body:
| Field | Required | Meaning |
|---|---|---|
prompt |
yes | The whole task, as text. |
model |
no, but always send it | haiku, sonnet, opus, or a full model id (section 9). |
effort |
no | How hard the model works: one of the levels health lists in efforts (for example low, medium, high, xhigh, max); anything else is refused with 400. Left out, the person’s default applies. |
system |
no | Instructions for the model, as text. Replaces Claude Code’s default instructions. |
schema |
no | A JSON Schema object. The answer comes back as an object matching it (section 8). |
timeout_s |
no | Seconds before Piggy stops the call and answers 504. Default 30 unless the person changed it, so send it every time. Over 120 is refused with 400 “timeout_s capped at 120”. |
session |
no | Leave it out for a one-off call (almost always right). true keeps the conversation and returns its session_id; send that id back as session to continue it. |
tools |
no | "" (default): the model can only answer. "Read": it may also read files on that Mac that you name in the prompt (for example an attachment your app saved). |
The body must be a JSON object sent with a Content-Length (chunked
bodies are refused), of at most 1024 KB unless the person changed it.
The model sees only your system and prompt. Send your complete
instructions, format rules and examples with every request; nothing is
remembered between calls unless you use session.
7. The response
| Field | Meaning |
|---|---|
request_id |
Quote it when reporting a problem. |
output |
The answer: an object when structured is true, otherwise text. |
structured |
True when output is the object matching your schema. |
model |
The model ids that answered (a list, normally one). |
effort |
The effort level used, or null when Claude Code’s own default applied. |
wall_s |
Seconds Piggy spent on the call. |
api_ms |
Of that, milliseconds the model took. |
cost_usd |
What the call would have cost at API prices. The person pays a subscription; this is for comparison, not a charge. |
usage |
Token counts. |
session_id |
Only when you sent session. |
model, api_ms, cost_usd, usage and session_id may be null.
8. Structured answers
Send a schema and the answer is checked against it before it reaches
you:
{"prompt": "Is the sky blue on a clear day? Answer yes or no.",
"model": "haiku",
"schema": {"type": "object",
"properties": {"answer": {"type": "string", "enum": ["yes", "no"]}},
"required": ["answer"]}}
-> "output": {"answer": "yes"}, "structured": true
- Always check
structured. If it is false,outputis the model’s text instead of an object: treat that as a failed call. - Keep schemas plain:
type,properties,required,enum,items. Put fixed choices inenum, not in the prompt.
9. Choosing a model
Name a model on every request. Without one, the person’s default applies, and if they set none, whatever Claude Code picks for their plan, which can be its largest and slowest model.
| Alias | Use it for |
|---|---|
haiku |
Classifying, extracting, short answers. Fast and light. |
sonnet |
Most writing and reasoning. |
opus |
The hardest tasks, when quality is worth the time. |
An alias means whichever model Claude Code maps it to, which changes
over time. Read model in the response for the exact model that
answered.
10. Errors and retrying
Errors are JSON with an error message and a request_id (404 for an
unknown address has no request_id). If a connection closes without
any answer, treat it like a 500 and retry.
| Status | Meaning | What your app does |
|---|---|---|
| 400 | Something in the request is wrong; the message says what | Fix the request. Do not retry. |
| 401 | Missing, wrong or removed key | Stop. Ask the person for a new key. |
| 404 | Unknown address | Fix the URL. |
| 429 | /infer: the person’s Claude usage limit is reached. A job: your key already has as many jobs as it may (section 13) |
/infer: wait minutes, not seconds; Piggy refuses calls, letting one through every 5 minutes to test. A job: wait for one to end. |
| 500 | A fault inside Piggy (on /infer) |
Retry up to twice; report it with the request_id. |
| 502 | Claude Code failed, or the person must sign in to Claude again (“claude needs sign-in”; then one call a minute is let through to test). When Claude Code ran, claude_said carries its own message, worth logging. |
Retry a few times with a growing pause. A sign-in needs the person: the Piggy menu shows it. |
| 503 | Busy: as many calls already running on that Mac as it allows (4 unless the person changed it), all apps together | Retry after a few seconds. |
| 504 | The call ran past timeout_s (if the usage limit or an expired sign-in caused it, you get 429 or 502 instead) |
Retry up to twice, or with a larger timeout_s. |
The example clients follow this table: they retry 503, 500, 504 and no answer at all up to twice, 502 with a growing pause, never retry 400 or 401, and treat 429 as “come back later”.
11. Limits and timing
- At most 4 calls run at once on a Mac (unless the person changed it), across every app. The next gets 503 at once; it is not queued.
- Each call takes a few seconds at least: Claude Code starts and the model answers. Measured: short prompts with a one-word answer, 2 to 9 s; prompts of several KB with a large schema (15,016 calls), median 15.3 s, 9 in 10 under 30.9 s, longest 98.6 s.
- Set your own HTTP timeout to the
timeout_syou send plus a few seconds (35 s for 30). A dropped network can hang a request without any error. timeout_sis at most 120. For longer work, use a job (section 13).
12. Checking that Piggy is there
GET /health needs no key:
curl -s http://127.0.0.1:8377/health
| Field | Meaning |
|---|---|
status, version |
"ok" and Piggy’s version. |
backend_status.sign_in_needed |
True: calls fail until the person signs in again. |
backend_status.usage_limited |
True: the usage limit is reached; calls get 429. |
backend_status.logged_in |
Whether Claude is signed in (null while Piggy has not yet been able to ask). |
efforts |
The effort levels you may send (with your key, or from the same Mac). |
From the same Mac, health also shows details such as the connected
apps and settings. From another device without a key, it shows only
the fields above (plus service, backend, uptime_s); send your key
to see the rest. GET /v2/health is the same plus channel
("plain" or "secure").
No answer on the address you use means that connection is off or Piggy is not running. Let your app carry on without Piggy and try again later.
13. Jobs: long work with tools
A job lets the model work for minutes and use tools: run commands from an exact list, read and write files in given folders, and use tool servers (section 14). Jobs are started and followed over these addresses, on either connection:
| Request | Does |
|---|---|
POST /v2/jobs |
Start a job. Answers 202 {"job_id", "status": "queued"} at once. |
GET /v2/jobs/<id> |
Its status and, at the end, its result (the job’s id is id here). |
GET /v2/jobs/<id>/transcript |
{"job_id", "entries"}: each entry has kind and at: call (id, tool, input), result (id of its call, error, output, first 4000 characters), tool_servers (status). |
POST /v2/jobs/<id>/cancel |
Stop it and everything it started: 202 {"job_id", "status": "cancelling"}. |
A key can do no jobs until the person allows it. In the Piggy window, Apps, your app’s permissions: which tools, which exact commands, which folders, which tool servers, how long a job may run and how many at once. Tell the person exactly what your app’s jobs need.
Starting a job
POST /v2/jobs
{"prompt": "Run date, then call the stamp tool with text 'check', and report both results.",
"model": "haiku",
"system": "You check reports. ...",
"profile": {"tools": ["Bash"], "commands": ["date"], "mcp": ["stamp"]},
"max_runtime_s": 300}
| Field | Meaning |
|---|---|
prompt |
The task. Required. |
model |
As for /infer. |
effort |
As for /infer; the job’s status reports the level it ran with. |
system |
Added to Claude Code’s own instructions for using tools (it does not replace them). |
profile.tools |
Any of Bash (run commands), Read, Write, WebSearch (search the web), WebFetch (read a web page on the internet). The web tools need no commands or folders. |
profile.commands |
With Bash: the commands it may run. Each allows that exact command, or that command followed by arguments. Shell operators (;, &, |, backquote, $(, <, >, a new line) are always refused. |
profile.dirs |
Folders it may read (with Read) and write (with Write). Full paths; each must be a folder your key may write in. |
profile.read_dirs |
Folders it may only read (with Read). |
profile.mcp |
Tool servers it may use, by the names the person gave them. |
max_runtime_s |
How long it may run, a whole number of seconds. Cut to your key’s limit; default your key’s limit, or 300 s. |
profile is checked first (400 if wrong): each field is a list of
non-empty strings, no other fields; Bash needs commands, Write
needs dirs, Read needs dirs or read_dirs. Then every entry must
be within your key’s permissions, or the job is refused with 403 naming
the entry, for example this key may not run the command 'rm'. A key
the person has given no job permissions gets this key may only do inference: it has no permission for Bash. Inside a running job, anything
the profile does not allow is refused at once; the model is told and
carries on or reports it. Nothing ever waits for a person to approve.
Research on the web
A job can search the web and read pages, for example to research a topic and cite its sources, when the person allows your app Search the web and Read web pages. Your app needs no commands or file access for this.
POST /v2/jobs
{"prompt": "What is the latest stable release of Rust and when was it released? Search the web, open the official pages you rely on, and give the URL of each page you opened.",
"model": "sonnet",
"profile": {"tools": ["WebSearch", "WebFetch"]},
"max_runtime_s": 240}
In the transcript each search is a call to WebSearch with
input.query, and each page read a call to WebFetch with
input.url, each followed by its result. To be sure the answer cites
only pages the model opened, compare its URLs with the WebFetch
calls. Pages on the person’s own Mac or local network are never read;
such a read comes back as a result with error true. Without these
tools in the profile the model has no web access at all.
Following a job
Poll GET /v2/jobs/<id> every few seconds:
| Status | Meaning |
|---|---|
queued |
Waiting for a free slot (2 jobs run at once on a Mac by default). |
running |
Working. |
succeeded |
Done; result.output is the model’s final answer. |
failed |
Ended without an answer; reason says why. |
timed_out |
Ran past its limit; it and everything it started were stopped. |
cancelled |
You cancelled it. |
tool_servers shows each tool server the job uses with its state, for
example {"stamp": "connected"} (null until the job has started, and
when it uses none). If one cannot be reached, the job stops at once and
fails with a reason naming it; it never works on without its tools. A
job that names a tool server the person removed is refused with 403,
since removing it also takes it out of every app’s permissions. A job
already queued when its server was removed, or one whose token is
missing, fails before it starts: “Piggy could not run the job: tool
server ‘stamp’ …”.
The Python client wraps all of this:
piggy = Piggy("https://127.0.0.1:8379", "~/.myapp/piggy-key", "~/.myapp/piggy-cert.pem")
job_id = piggy.start_job("Run date, then call the stamp tool with text 'check', and report both results.",
model="haiku", profile={"tools": ["Bash"], "commands": ["date"], "mcp": ["stamp"]})
job = piggy.wait_for_job(job_id) # {'status': 'succeeded', 'tool_servers': {'stamp': 'connected'}, ...}
tools = [e["tool"] for e in piggy.transcript(job_id) if e["kind"] == "call"] # ['Bash', 'mcp__stamp__stamp']
Job rules to know
- A job is visible only to your app (its name): another app’s key gets 404.
- Your key may have only so many jobs running or queued at once (1 unless the person allows more); beyond that, 429.
- Cancelling a queued job takes effect when a slot frees; until then it still counts against your key’s limit.
- Finished jobs are deleted some time after 7 days (unless the person changed it): keep what you need.
- Jobs do not get the fast 429/502 refusal of
/inferduring a usage limit or an expired sign-in. Check/healthbefore starting one. - Job errors: 400 (bad request or profile), 401, 403 (outside your permissions), 404 (no such job for your key), 409 (cancelling a job that already ended), 429.
14. Offering your app’s own tools
Sometimes a job needs something only your app has: a browser that is signed in to a site, for example. Your app then runs a tool server (MCP), and the job uses its tools. Piggy only passes the calls along; it never holds your browser, cookies or accounts.
Your tool server must:
- Use HTTPS. Piggy refuses an
http://address, even on the same Mac. Speak MCP over HTTP: JSON-RPC in each POST; a JSON reply is enough. - Have a certificate, and give its file to the person. Your own
(self-made) certificate is fine. It must name the host in your address
(for example
127.0.0.1orlocalhost). Always give the file, even for a certificate macOS trusts. - Require a token. Check
Authorization: Bearer <token>first, on every request, and refuse anything without it with 401. Give the person the token; Piggy keeps it in the macOS Keychain. Give the token only for tool servers your own app runs, and use a different token for each server. - Stay narrow. Offer only the actions jobs need. No tool that returns cookies or passwords, or runs arbitrary script: whatever a tool returns reaches the model and the job’s transcript.
examples/tool-server.mjs is a complete
tool server in about 90 lines of Node: HTTPS, the token checked first,
one example tool (stamp). Make a certificate and a token, then start it:
openssl req -x509 -newkey rsa:3072 -nodes -keyout key.pem -out cert.pem -days 825 \
-subj "/CN=my-app-tools" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1"
python3 -c "import secrets; print(secrets.token_urlsafe(32))" > token
node examples/tool-server.mjs 9555 cert.pem key.pem token log.jsonl
Then the person, in the Piggy window under Tool Servers,
clicks Add Tool Server…, enters a name (say stamp), the address
(https://127.0.0.1:9555/mcp), the token and the certificate file,
clicks Add, then Test (it should say “answers”), and allows it
for your app under Apps.
Your job names it in its profile, "mcp": ["stamp"], and the model
sees its tools as mcp__stamp__<tool>.
If your tool server uses one signed-in account, run one job at a time against it: take your own lock in your app, and leave your key’s job limit at 1.
15. Security checklist
- Keep the key in a file only your app can read, or in the Keychain. Never in source code, URLs, logs or command lines.
- Use the secure connection from another device, and trust exactly Piggy’s certificate (its file or fingerprint), never “accept any”.
- Ask the person for only the job permissions your app needs.
- Keep tool servers behind HTTPS and a token, with narrow tools.
- Treat what the model returns as untrusted input: validate it like any other input before acting on it.
16. Versions and compatibility
GET /healthgives Piggy’sversion.- Piggy’s API changes only by adding things: a field your app relies on keeps its meaning. New fields may appear in answers; ignore the ones you do not use.
/inferand/v2/inferare the same request; the/v2/addresses also name the connection in health.
17. Troubleshooting
| You see | Likely cause | What to do |
|---|---|---|
| Connection refused on 8377 from another device | The unencrypted connection answers only its own Mac | Use the secure connection. |
| Connection refused on both | Piggy is not running, or that connection is switched off | Ask the person to check piggy in the menu bar. |
| A TLS or certificate error | Your app does not trust Piggy’s certificate, or it was renewed | Trust the certificate file or fingerprint from the person. |
| 401 | Wrong or removed key | Ask for a new key. |
| 403 on a job | Outside your key’s permissions (the message names what) | Ask the person to allow it under Apps in the Piggy window, or change the job. |
| 502 “claude needs sign-in” | The person’s Claude sign-in expired | The person uses Sign In to Claude… in the Piggy menu. |
429 from /infer |
The person’s Claude usage limit | Wait; it clears by itself. |
429 from /v2/jobs |
Your key has its limit of jobs running or queued | Wait for one to end. |
structured: false |
The model did not return a matching object | Simplify the schema or the prompt; treat the call as failed. |
| A job fails “tool server ‘x’ could not be reached” | Your tool server is not running, or its certificate or token changed | Start it; if the certificate or token changed, the person adds it again. |
| A job fails “Piggy could not run the job: tool server ‘x’ …” | The job was queued when the person removed the tool server, or its token is missing | The person adds it again (and allows it for your app again). |
Connection refused on localhost |
Your client tried IPv6 first; Piggy listens on IPv4 | Use 127.0.0.1. |
18. All routes
Every route answers on both connections.
| Route | Key | Does |
|---|---|---|
GET / |
not needed | A test page for the person |
GET /health |
not needed (details need it from another device) | Is Piggy there, and its state |
GET /v2/health |
as above | The same, plus channel |
POST /infer |
yes | One request, one answer |
POST /v2/infer |
yes | The same as /infer |
POST /v2/jobs |
yes, with job permissions | Start a job |
GET /v2/jobs/<id> |
yes | A job’s status and result |
GET /v2/jobs/<id>/transcript |
yes | Its tool calls and results |
POST /v2/jobs/<id>/cancel |
yes | Stop it |