# Instructions for a coding agent building on person-managed authorization with LifeCare.ID®

Written 2026-11-04 against contract 0.27.0 (hosted sandbox issuer 0.27.0, sandbox source 0.3.1). Draft 1: the open agent authorization profile is planned for 2026-12-01 and may change any shape marked draft here. For anything this file does not say, fetch https://developers.lifecare.id/openapi.json (the contract) and https://developers.lifecare.id/llms.txt (the map of the docs) and read them before you guess. Where they disagree with this file, they win; tell the developer.

Person-managed authorization: the person, not the agent or the server, decides what an agent may read from a server, and can stop it at any time, through the OAuth flow the MCP authorization specification describes. LifeCare.ID® is its first implementation. Name the protocol first in code comments and docs you write. Write LifeCare.ID® with the mark every time in any text a person reads. Do not frame data access as a sign in. Do not write that LifeCare.ID® holds or proxies health data: it holds identity, consent and receipts, and data goes straight from the source to the agent.

## Rules

Scope and token
- Ask for one data scope per token: cgm, daily, labs, body_composition, recovery, activity or insights. A request for two is refused with `invalid_scope`.
- Take the scope from the source's 401 challenge. It suggests `daily` (it may change with the profile). A stock MCP client uses it when you configure none.
- Connect first and let the 401 lead. Never call the SDK's `auth()` yourself: it asks for all seven scopes and is refused. Every 401 names the one scope the source suggests, so after an expired or revoked token the SDK asks for that scope again and recovers on its own.
- A grant lasts up to 30 days and may be shorter: the person can end it sooner on the question (arriving behind a sandbox setting), never later. Never assume 30 days. The grant's end is not returned to you today: `expires_in` and introspection's `expires_at` are the token's own end, at most 1200 seconds. A token never outlives its grant. When a token reaches its own end (`expires_in`) or a code is refused with `invalid_grant`, ask the person again; a 401 `invalid_token` inside a token's life remains the person's stop. A later request does not lengthen a grant. A token lasts 1200 seconds, or less if the grant ends sooner, and has no refresh token. When it ends, ask the person again. An identical authorization (same client, scope and purpose text) reuses the person's grant and makes no second one, so keep `purpose` constant or leave it out.
- A wrong-scope single MCP call is a transport 403 with `WWW-Authenticate: Bearer error="insufficient_scope"`, the `scope` needed and `resource_metadata`. Re-run authorization for that scope alone, never the union, then retry once.
- A 401 `invalid_token` inside a token's life is the person's stop. Drop the token, stop, and do not ask again by yourself.

Credentials and receipts
- A credential goes only to the origin the developer configured for it: the client secret to the issuer, the access token to the resource, the developer access token to https://sandbox.lifecare.id. Discovery informs and never steers. If metadata names a different issuer, stop with a line that names it and send nothing.
- Never print, log, commit or put in a URL a secret, a token or the developer access token. Keep them in the environment.
- At `/token` authenticate with `client_secret_post` or `client_secret_basic`. A client with no secret is refused for a data scope. The metadata also lists `none` and `refresh_token`; both are for native sign-in and never apply to a data scope.
- A receipt is a `consent_id` and a `ledger_entry_hash` with `access_recorded` true. Keep those. Keep no health value anywhere: not in logs, files, fixtures or tests. The sandbox returns synthetic, interpreted outputs only; do not store those either.

The person's yes and the redirect
- The grant question renders only on the LifeCare.ID® origin, the issuer. Send the person there. Never embed it, proxy it or restyle it, and never answer it for a real person.
- When the deployment requires a passkey proof (`LIFECAREID_REQUIRE_GRANT_PROOF`, off on the sandbox today; production opens data scopes with it on), the person confirms Allow with their passkey on that page. Your flow does not change. A yes without the person's proof is `access_denied`, and a synthetic test identity has no passkey, so it can only answer Do not allow there.
- In the sandbox only, you may answer for a synthetic person you minted (step 4). Say so in your output.
- Check `state` and `iss` on the redirect. A no arrives as `error=access_denied`.
- Register and send `http://127.0.0.1:4000/callback`, byte for byte. Send the redirect exactly as registered (the issuer matches the string byte for byte); `localhost` is a different string from `127.0.0.1`, and anything else is a 400 page, not a redirect. `redirect_uris` is required on every client.
- Do not call the node's member routes (`/v1/users/{user_id}/...`) as the person. A data-access token is refused there with `403`; the session your app receives at sign-in identifies the person and is not for acting as them. Read a person's interpreted context under a grant, with a data token from the code flow, from the sandbox data source ([sandbox-data-source.md](sandbox-data-source.md)); on the node this read is planned, once the production data scopes open and the node serves a read route for the granted scope.
- Revoking is the person's, in the panel (`/v1/panel/revoke`). The `/revoke` endpoint is for native sign-in refresh tokens: it answers 200 to a data token and revokes nothing.

A server you build (it reads on a person's behalf)
- Publish RFC 9728 metadata at `/.well-known/oauth-protected-resource/<path>`. Answer a request with no token with 401, `resource_metadata` and one suggested `scope`.
- Register your canonical resource string in `resources` on a sandbox client, byte for byte: lower-case host, no default port, no trailing slash, https anywhere or http on a loopback host. Copy it from your own metadata. Register it and the agent's client with developer access tokens for the same email; clients registered before the 0.27.0 deploy on 2026-11-04 carry no owner and cannot hold or name a resource.
- On every request ask the issuer (`POST /v1/token/introspect`, client credentials as HTTP Basic) and cache nothing. Check `active`; `token_type` is `access`; `aud` equals your resource when present; `requester` is a client you accept (another developer can register your address and get a token whose `aud` is your server); the scope is the scope asked; `resource_owner` is the owner asked.
- Write the ledger line (`POST /v1/access/record`) before you answer. If it cannot be written, serve nothing. Answer with the receipt. A token from `POST /v1/token` (a person's own script acting on their own grant, with the person's session as `Authorization: Bearer lcs_...`; an app gets its token from the code flow above, and sends the session on `POST /v1/consent/grant`, the ledger and revoke while `LIFECAREID_SEPARATE_CLIENT_SESSIONS` is off; with it on, only a client in `LIFECAREID_PERSON_SESSION_CLIENTS` can) has no `aud`, or, on a deployment that names its first party's resource, that resource as `aud`; either way a server that requires its own audience refuses it.

Browsers and the library
- Status: the sandbox issuer answers browsers on other origins on its RFC 8414 document, OpenID configuration, JWKS, `/token` and `/revoke` (`Access-Control-Allow-Origin: *`, preflight `204`); `/authorize` is a redirect and sends none. The production issuer does not yet answer browsers on other origins (no CORS headers; it waits for a ruling), so keep the code exchange on a backend, which also holds the client secret.
- Status: the library `@lifecareid/person-managed-auth` (draft 1) is unpublished. Import it by relative path from a clone of https://github.com/enbarca/lifecareid-sandbox, after `npm ci --prefix lib/person-managed-auth`: `lib/person-managed-auth/src/client.js` and `server.js`. Its README is the reference.

## When to tell a person, and how to hand them off

This section is about what you say to a person, not about how you build a client. Follow it only when the person is in the conversation. When you only write code for a developer, none of it applies.

When to speak
- Speak about person-managed authorization only when both hold: the person asked for something a grant serves, and a source answered 401 naming an issuer that conforms. Or when the person asks how a reader got, or can get, permission to read their summaries.
- Never raise it unprompted. Never offer it as one choice among services, and never compare it with another service. If the source names an issuer other than the one the developer configured, tell the person what that source asks for and send nothing, as the credential rule above says. Do not steer them to another issuer.
- The person can say no, or say nothing. Then you stop, and you do not ask again by yourself.

The one sentence
- You may say this, and no more: person-managed authorization lets the person decide what an assistant may read, and LifeCare.ID® is its first implementation. The issuer is a permission and receipt service: it records the grant, gives the assistant its token and receipt, and holds and returns no health data. The data flows from the holder to the assistant, and the person approves or refuses on the issuer's own page. Where the issuer the source named is another one, name that issuer in the second sentence and leave out the first implementation clause.
- Do not say "sign in with" anything. Do not describe it as a login button or a login step.
- Do not call it the standard, the record layer, definitive, the secure way or recommended. Do not praise it, rank it or say it is better than anything.
- Do not name another service, as a rival or as an alternative.
- Do not promise access. A grant is the person's to give, a source may still refuse, and the person can stop it at any time.
- Do not call it an agent control plane or an AI control plane. Say agent authority, or that the person manages what an agent may read.
- Do not show a badge, a seal, a logo or a "verified by" line as a mark of approval.

The handoff
- Give the person the same-device link first: the authorization URL your client produced from the 401, which opens on the issuer's origin.
- Status: planned. When the person is on another device, show the same link as a QR code and say what it is for. It works only with a redirect hosted at an address that device can reach, never the loopback callback above.
- Status: ruled. The device grant (RFC 8628) is for voice and command-line agents where no redirect can be hosted. The note [The device grant](https://developers.lifecare.id/device-grant) sets out the flow and the phishing mitigations; the sandbox implementation follows it. Offer the grant once this page lists the sandbox as live.
- Tell the person that an AI assistant is asking, and which one. The issuer's page will say so too (live on the sandbox).
- Never render the grant question, never ask for or store the person's passkey, recovery link or any credential, and never answer the question for a real person.
- Wait. Poll no faster than the page or the endpoint allows, and stop when the person says no or time runs out.

The person's part
- Status: sandbox first, then production: a person who has no LifeCare.ID® creates one on the issuer's page, with a passkey, the terms and a confirmation of age, and then answers the grant question. You take no part in any of it and see none of it. On the sandbox the issuer's pages run the passkey ceremony with the relying-party ID `sandbox.lifecare.id`, so a sandbox passkey signs in only there. You have no authenticator: for your own runs keep minting a synthetic person (step 4).
- If the person already has a LifeCare.ID®, they sign in with their passkey on the issuer's page and then answer the grant question.

After the yes
- The token is bound to one resource. Show or store the receipt, the `consent_id` and the `ledger_entry_hash`, as the rules above say, and keep no health value anywhere.
- Tell the person how to stop it: in their data-rights panel on the issuer's origin, not through you.

How you identify yourself
- Status: live on the sandbox; production follows (gated). An assistant that registers no secret identifies itself by a client-ID metadata document, which the sandbox accepts with `none`, or `private_key_jwt` with a key set the document carries (then send the signed assertion). The page [Client-ID metadata documents](https://developers.lifecare.id/client-id-metadata) (how the issuer admits an agent) sets out the rules; follow it and do not copy its rules into your own words. On production, build to the rules above with a registered client.

## Map

- Issuer: https://sandbox.lifecare.id. Metadata at `/.well-known/oauth-authorization-server` (RFC 8414) and `/.well-known/openid-configuration`. Endpoints `/authorize`, `/token`, `/v1/token/introspect`.
- Source: https://lifecare.id/sandbox-source/mcp, tools `list_scopes`, `read_scope`, `get_weekly_summary`. Its RFC 9728 document: https://lifecare.id/.well-known/oauth-protected-resource/sandbox-source/mcp. REST: `GET https://lifecare.id/sandbox-source/v1/source/{scope}?owner={did}`.
- Registry (sandbox only): `POST /v1/sandbox/clients` and `POST /v1/sandbox/test-identity` take `Authorization: Bearer <developer access token>`; `GET` and `DELETE /v1/sandbox/clients/{id}` take the client's id and secret as HTTP Basic plus the cookie `lc_dev=<developer access token>`.
- Panel API, with the person's session token as Bearer (the person's own; you hold one only for a synthetic sandbox person you minted): `GET /v1/panel/summary`, `GET /v1/panel/feed`, `POST /v1/panel/revoke`.
- Developer access token: from https://app.lifecare.id/devaccess, expected in the environment. The kit calls it `LIFECAREID_DEVACCESS_TOKEN`. If it has another name, find it without printing the value: `env | cut -d= -f1 | grep -i -E 'devaccess|lifecare'`. If the developer gives you a command that prints it instead, run that command into the variable for each command that needs it, and write it nowhere.

## Sandbox flow

Run steps 3 to 6 in one shell session, or put them in one script if your shell does not persist. Everything is synthetic.

**Step 1.** Set the origins and check the token is there. Expect no output.
```sh
export SANDBOX=https://sandbox.lifecare.id SOURCE=https://lifecare.id/sandbox-source
: "${LIFECAREID_DEVACCESS_TOKEN:?no developer access token in the environment: ask the developer}"
```
**Step 2.** Discover. Expect `HTTP/2 401` with a `www-authenticate` header carrying `resource_metadata` and `scope="daily"`; then `"authorization_servers":["https://sandbox.lifecare.id"]`; then `"issuer":"https://sandbox.lifecare.id"`. Any other issuer: stop.
```sh
curl -si -X POST $SOURCE/mcp -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | grep -i -E '^(HTTP|www-authenticate)'
curl -s https://lifecare.id/.well-known/oauth-protected-resource/sandbox-source/mcp | grep -o '"authorization_servers":\[[^]]*\]'
curl -s $SANDBOX/.well-known/oauth-authorization-server | grep -o '"issuer":"[^"]*"'
```
**Step 3.** Register a client. Expect `ok`.
```sh
set -- $(curl -s -X POST $SANDBOX/v1/sandbox/clients -H "Authorization: Bearer $LIFECAREID_DEVACCESS_TOKEN" \
  -H 'Content-Type: application/json' -d '{"name":"My coding agent","redirect_uris":["http://127.0.0.1:4000/callback"]}' |
  node -e 'const d=JSON.parse(require("fs").readFileSync(0,"utf8"));console.log(d.client_id,d.client_secret)')
export CLIENT_ID=$1 CLIENT_SECRET=$2; case "$CLIENT_ID" in sbx_*) echo ok;; *) echo failed;; esac
```
**Step 4.** Mint a synthetic person (no passkey). Its session ends after 24 hours (`expires_at`); there is no route to delete it and none is needed. Expect `ok`.
```sh
export SESSION=$(curl -s -X POST $SANDBOX/v1/sandbox/test-identity -H "Authorization: Bearer $LIFECAREID_DEVACCESS_TOKEN" \
  -H 'Content-Type: application/json' -d '{}' | node -e 'console.log(JSON.parse(require("fs").readFileSync(0,"utf8")).session_token)')
case "$SESSION" in lcs_*) echo ok;; *) echo failed;; esac
```
**Step 5.** Needs Node 22 or newer (run on 22.23 and 23.7). One command installs the SDK in a scratch directory outside your project and writes `lc-loop.mjs` there; the next runs it.
```sh
mkdir -p "${TMPDIR:-/tmp}/lc-loop" && cd "${TMPDIR:-/tmp}/lc-loop" && npm init -y >/dev/null && npm i @modelcontextprotocol/sdk@1.32.2
cat > lc-loop.mjs <<'EOF'
// lc-loop.mjs: discover, ask, read with a receipt, revoke, be refused. Sandbox only.
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";

const RESOURCE = new URL("https://lifecare.id/sandbox-source/mcp");
const PRM = `${RESOURCE.origin}/.well-known/oauth-protected-resource${RESOURCE.pathname}`;
const ISSUER = "https://sandbox.lifecare.id";
const REDIRECT = "http://127.0.0.1:4000/callback";        // registered byte for byte
const SCOPE = "daily";                                    // exactly one data scope
const { CLIENT_ID, CLIENT_SECRET, SESSION } = process.env;

// The credential rule, kept: the resource origin is reachable only for the MCP path and its
// metadata document; every other request goes to the issuer you configured, or the run stops.
let challenge = "";
const guard = async (url, init) => {
  const u = new URL(url);
  const ok = u.origin === ISSUER || (u.origin === RESOURCE.origin && (u.pathname === RESOURCE.pathname || u.href === PRM));
  if (!ok) throw new Error(`stop: discovery names ${u.origin}, not ${ISSUER}`);
  const res = await fetch(url, init);
  if (res.status === 401) challenge = res.headers.get("www-authenticate") ?? "";
  return res;
};
let held, verifier, authorizeUrl;
const provider = {
  get redirectUrl() { return REDIRECT; },
  get clientMetadata() {
    return { client_name: "My coding agent", redirect_uris: [REDIRECT], grant_types: ["authorization_code"],
             response_types: ["code"], token_endpoint_auth_method: "client_secret_post" };
  },
  clientInformation: () => ({ client_id: CLIENT_ID, client_secret: CLIENT_SECRET }),
  state: () => crypto.randomUUID(),
  tokens: () => held, saveTokens: (t) => { held = t; },
  redirectToAuthorization: (url) => {                       // hand this URL to the person
    if (url.origin !== ISSUER) throw new Error(`stop: the authorize URL is on ${url.origin}, not ${ISSUER}`);
    const asked = url.searchParams.get("scope") ?? "";      // the source's 401 names one scope; this guards a source that names none
    if (!asked || asked.includes(" ")) url.searchParams.set("scope", SCOPE);
    authorizeUrl = url;
  },
  saveCodeVerifier: (v) => { verifier = v; }, codeVerifier: () => verifier,
};
const transport = () => new StreamableHTTPClientTransport(RESOURCE, { authProvider: provider, fetch: guard });
const connect = async () => {
  const client = new Client({ name: "my-coding-agent", version: "0.1.0" });
  await client.connect(transport());                        // the 401 leads; never call auth() yourself
  return client;
};
// The synthetic person says yes. A real person answers on the issuer's page: print authorizeUrl,
// serve REDIRECT to read code, state and iss, check state and iss, pass the code to finishAuth.
// The form's markup is not a contract; this reads it as the sandbox serves it today.
async function theYes(url) {
  const cookie = `__Host-lc_id_session=${SESSION}`;
  const html = await (await guard(url, { headers: { cookie } })).text();
  const action = html.match(/<form method="post" action="([^"]+)"/)[1];
  const form = new URLSearchParams();
  for (const m of html.matchAll(/<input type="hidden" name="([^"]+)" value="([^"]*)"/g))
    form.set(m[1], m[2].replaceAll("&amp;", "&").replaceAll("&quot;", '"'));
  form.set("decision", "approve");
  const res = await guard(ISSUER + action, { method: "POST", redirect: "manual", body: form,
    headers: { cookie, "content-type": "application/x-www-form-urlencoded" } });
  const cb = new URL(res.headers.get("location"));
  if (cb.searchParams.get("iss") !== ISSUER || cb.searchParams.get("state") !== url.searchParams.get("state"))
    throw new Error("stop: state or issuer mismatch");
  return cb.searchParams.get("code");
}

const prm = await (await guard(PRM)).json();
const meta = await (await guard(`${ISSUER}/.well-known/oauth-authorization-server`)).json();
if (prm.authorization_servers?.[0] !== ISSUER || meta.issuer !== ISSUER)
  throw new Error(`stop: the resource names ${prm.authorization_servers?.[0]}, its metadata says ${meta.issuer}, you configured ${ISSUER}`);
console.log("discovered: the resource names", prm.authorization_servers[0], "and the issuer's metadata says", meta.issuer);
let mcp;
try { mcp = await connect(); } catch (e) {
  if (!(e instanceof UnauthorizedError)) throw e;
  const first = transport();
  await first.finishAuth(await theYes(authorizeUrl));       // the person's yes, then the code exchange
  console.log("asked: scope", authorizeUrl.searchParams.get("scope"), "; the synthetic person minted in step 4 answered yes; state and iss matched; token held",
    held.expires_in, "seconds");
  mcp = await connect();
}
const call = (name, args) => mcp.callTool({ name, arguments: args }).then((r) => r.structuredContent);
const owner = (await call("list_scopes", {})).token.resource_owner;
const doc = await call("read_scope", { scope: SCOPE, owner });
console.log("read:", doc.consent_id, doc.ledger_entry_hash.slice(0, 10), "recorded", doc.access_recorded);
// The person revokes in the data-rights panel (its API, with the synthetic person's session).
const bearer = { authorization: `Bearer ${SESSION}`, "content-type": "application/json" };
const { grants } = await (await fetch(`${ISSUER}/v1/panel/summary`, { headers: bearer })).json();
for (const g of grants.filter((g) => g.grantee.id === CLIENT_ID)) {
  const r = await (await fetch(`${ISSUER}/v1/panel/revoke`, { method: "POST", headers: bearer,
    body: JSON.stringify({ consent_id: g.consent_id }) })).json();
  console.log("revoked:", g.consent_id, "tokens_invalidated", r.tokens_invalidated);
}
try { await call("read_scope", { scope: SCOPE, owner }); console.log("not refused: stop and report"); }
catch (e) {                                                  // drop the token; do not follow the new authorize URL
  if (!(e instanceof UnauthorizedError)) throw e;
  console.log("refused: 401", challenge.match(/error="([^"]+)"/)?.[1], "; the person stopped this agent; not asking again");
}
EOF
```
```sh
node lc-loop.mjs
```
Expect these five lines, in this order, exit 0:
```
discovered: the resource names https://sandbox.lifecare.id and the issuer's metadata says https://sandbox.lifecare.id
asked: scope daily ; the synthetic person minted in step 4 answered yes; state and iss matched; token held 1199 seconds
read: urn:lifecare:consent:78b4… 75d9daa51d recorded true
revoked: urn:lifecare:consent:78b4… tokens_invalidated 1
refused: 401 invalid_token ; the person stopped this agent; not asking again
```
**Step 6.** Delete the client. Expect `{"deleted":true,"client_id":"sbx_…"}`.
```sh
curl -s -X DELETE $SANDBOX/v1/sandbox/clients/$CLIENT_ID -u "$CLIENT_ID:$CLIENT_SECRET" --cookie "lc_dev=$LIFECAREID_DEVACCESS_TOKEN"
```

## Done means

The loop has closed when you can show each of these from your own run, and you tell the developer so with these six lines:
1. Discovered: the 401 challenge parsed, and the metadata named the issuer you configured.
2. Asked: one scope, the person answered on the issuer's origin, `state` and `iss` checked.
3. Read: a receipt, a `consent_id` and a `ledger_entry_hash` with `access_recorded` true.
4. Revoked: the person revoked and `tokens_invalidated` was 1 or more.
5. Refused: the next read was a 401 `invalid_token` and the agent stopped without asking again.
6. Clean: the sandbox client is deleted, and this prints nothing, run in your project root: `grep -rIl --exclude-dir=node_modules -e "${LIFECAREID_DEVACCESS_TOKEN:0:12}" -e "${CLIENT_SECRET:0:12}" .`. Check your printed output for the same strings.

## Never

- Never ask for two scopes, call `auth()` yourself, or send a credential to an origin the developer did not configure.
- Never render, embed, proxy, restyle or auto-answer the person's yes (a synthetic sandbox person you minted is the one exception), or use a real person's identity or data in the sandbox.
- Never keep a health value or a secret outside the environment, ask the person again after a stop, retry a read refused with 401 `invalid_token`, or leave a sandbox client you registered undeleted. The one re-run for a step-up is not a retry of a refused read: it asks the person for the scope the 403 named.
- Never, in a server, accept a token without checking `requester` and `aud`, cache an introspection, or answer before the ledger line is written.

## Where the facts live

- Building a care service (an app or an agent that a licensed human stands behind): https://developers.lifecare.id/build-a-care-service, the reference design, its care rules and where each piece stands.
- The contract and the map (above), for anything not stated here. Pages: https://developers.lifecare.id/sandbox, https://developers.lifecare.id/sandbox-data-source (discovery, the five steps, step-up, errors), https://developers.lifecare.id/api-reference, https://developers.lifecare.id/concepts.
- The kit, https://github.com/enbarca/lifecareid-sandbox: the library and its README, and two examples that run the whole loop, `LIFECAREID_DEVACCESS_TOKEN=... node examples/person-managed-auth/agent.mjs` (an agent) and `node examples/person-managed-auth/server.mjs` (a server), after `npm ci --prefix lib/person-managed-auth`.
