Integrate your app in an afternoon
This guide builds Orders, a small app with a list of a shop's orders, into a complete APC app: Direct first (an agent connects to the app's own MCP URL), then Dock (an agent dragged from a dock). Every Orders sample on this page comes from one of three real files in the repo: orders-app.ts (the server, in excerpts), orders-page.ts (the page, in excerpts) and orders-connect.ts (the dock_connect page's client, shown whole); the conformance test orders-conformance.ts is excerpted on Conformance. Each name an excerpt uses is imported from a package (the imports are shown first) or defined in another excerpt on this page; the server's excerpts from step 3 through step 12's dock region form one class, OrdersApp (closed at the end of dock), so this. names a member shown in the app object, and dockConnectPage in step 12 sits outside the class at module scope. They type-check against the current packages on every build, and the conformance suite passes against them on both profiles.
Want one file to copy instead? A complete Direct app is shown whole below: a server, its page and its conformance test, with nothing left out, whose agents use a bearer token. The minimum for the Dock profile lists what a Dock app adds.
The server is plain Web standard Request and Response, so it runs on Node, Deno, Bun or a Cloudflare Worker; the page is plain DOM, so it fits React, Vue or none. State is kept in memory, for one person, so the APC parts stay in sight: your app keeps grants, pins and the view in its own database, per person, and puts the person's routes behind its own sign-in.
1. Install#
The packages are released together at the standard's version (APC_STANDARD_VERSION, which the banner above names). A patch never changes the contract. Install all four at the same version; these commands select 1.1.1 explicitly, independently of npm dist-tags.
npm i @tineira/apc-server@1.1.1 @modelcontextprotocol/sdk zod # the server (the SDK and zod are peers)
npm i @tineira/apc-protocol@1.1.1 @tineira/apc-web@1.1.1 # the page
npm i -D @tineira/apc-conformance@1.1.1 # the tests
Use these commands for the 1.1.1 release. The sources are also in the repo: packages/protocol, packages/server, packages/web and packages/conformance, small enough to add to your workspace or copy.
They are ESM with type declarations. @tineira/apc-protocol and @tineira/apc-web have no Node imports (@tineira/apc-web is browser code for any bundler); @tineira/apc-server runs wherever there are fetch and Web Crypto (Workers, Node 20+); @tineira/apc-conformance needs Node 22.15+.
| Package | Gives you |
|---|---|
@tineira/apc-protocol | the types, the target grammar (parseTarget), focusAttrs, apc.json |
@tineira/apc-server | the two APC tools, attention and then, presence, grants, revoke, consent, apc_link, apc.json |
@tineira/apc-web | pinning (drag and tap), the agent bar <apc-agents>, the Direct agent list, presence, the view reporter, the agent pet (createPet, <apc-pets>, petState) and the wait helpers (waitOpen, agentWaitOpen) |
@tineira/apc-conformance | the suite that checks your app |
The server's imports:
import {
APC_SECRET_RE,
LONG_DORMANCY_RECOMMENDED_MS,
PAIRING_CODE_TTL_MS,
T_ACK_MAX_MS,
T_CONNECT_MAX_MS,
T_IDLE_RECOMMENDED_MS,
dockGrantStateOf,
parseParams,
parseTarget,
type ApcProfile,
type DockGrantState,
type FocusPayload,
type FocusRow,
type PresenceMessage,
type ViewPayload,
} from "@tineira/apc-protocol";
import {
APC_INSTRUCTIONS,
ApcLinks,
CONSENT_REQUIRED,
DockConsent,
confirmWithHub,
directGrantGate,
dockGrantGate,
handleDockGiveBack,
pairWithHub,
requestConnect,
parseDockDrop,
InflightCalls,
MemoryWaitSlots,
apcJsonResponse,
apcManifest,
attachApcLink,
attachAttention,
attachThen,
attentionFor,
badContentLength,
initializeOf,
isUnread,
linkClient,
memoryKv,
newDirectGrant,
presenceEvent,
registerApcLinkTool,
registerApcTools,
revokedResponse,
revokedToolResult,
secretHash,
thenApplies,
toolError,
toolResult,
type ApcKv,
type DockDropOptions,
type ToolResult,
} from "@tineira/apc-server";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { z } from "zod";2. Decide what can be pointed at#
Pick the things a person would ask about: here, an order, and its total as a part of it. A target is { kind, id, part, params }, ids and keys only (the focus format). Never put amounts or free text in a target: the agent reads those through your tools.
export interface Order {
id: string;
customer: string;
status: "open" | "shipped";
total_eur: number;
}
export const ORDERS: Order[] = [
{ id: "ord_1001", customer: "Acme", status: "open", total_eur: 1200 },
{ id: "ord_1002", customer: "Globex", status: "shipped", total_eur: 640 },
{ id: "ord_1003", customer: "Initech", status: "open", total_eur: 89 },
];In the page, every pointable element carries data-focus, made by focusAttrs. The page's imports, and post, the JSON POST every later page excerpt sends:
import { T_IDLE_RECOMMENDED_MS, focusAttrs, formatPairingCode, type FocusTarget } from "@tineira/apc-protocol";
import {
createViewReporter,
defineAgentBar,
defineDirectAgents,
enablePinning,
flashTargets,
initials,
loadApcProfiles,
type AgentDrag,
type ApcAgentsElement,
type ApcDirectAgentsElement,
type PinningStrings,
formatPageTime,
agentBadge,
defineHeaderPets,
petState,
agentWaitOpen,
dropExpiredWaits,
foldWaitEvent,
nextWaitExpiry,
NO_OPEN_WAITS,
type ApcPetsElement,
type OpenWaits,
} from "@tineira/apc-web";
import type { AgentRow, Order } from "./orders-app.ts";
const post = async (path: string, body: unknown = {}): Promise<Record<string, unknown>> =>
(await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })).json();/** Anything the person may point at carries data-focus: here, a row per order, and its total as a part. */
export function orderRow(order: Order): HTMLTableRowElement {
const row = document.createElement("tr");
for (const [name, value] of Object.entries(focusAttrs({ kind: "order", id: order.id }))) row.setAttribute(name, value);
const total = document.createElement("td");
for (const [name, value] of Object.entries(focusAttrs({ kind: "order", id: order.id, part: "total" }))) total.setAttribute(name, value);
total.textContent = `€${order.total_eur}`;
row.append(Object.assign(document.createElement("td"), { textContent: order.customer }), Object.assign(document.createElement("td"), { textContent: order.status }), total);
return row;
}3. Grants, and apc.json#
Each agent gets its own grant: an id, and a secret that is the last segment of its MCP URL.
/** One agent's access to Orders: a grant, with its own MCP URL, pin and name. */
export interface Grant {
/** What pins and the agent bar name. Not secret. */
id: string;
/** 128 random bits, the last segment of the MCP URL: whoever holds the URL holds the grant. */
secret: string;
/** SHA-256 of the secret: what a revoked grant leaves behind, and what a dock's give-back is looked up by. */
hash: string;
/** How the agent came: directly, or through a dock's hub. */
path: ApcProfile;
name: string;
/** The agent has connected (sent `initialize`), with this MCP client. */
client: string | null;
/** Dock: the hub's origin and the agent's public handle there. */
hub: string | null;
agent: string | null;
/**
* Dock (APC 0.10): where the grant is on its way to the dock. `in_flight` from the person's Allow to the hub's
* acknowledgement, `handoff` until the hub's first `initialize`, then `live`. A Direct grant is always `live`.
* A grant that ended is deleted (its URL answers 404); a revoked one leaves its hash in `revoked` (403).
*/
state: "in_flight" | "handoff" | "live";
/** Dock: when the person allowed it, when the hub acknowledged it, and the person's last wake action (ms). */
allowedAt: number;
ackedAt: number;
lastWake: number;
/** Dock: the pairing code the person types in their dock, while the grant is in handoff. Shown only on the person's page. */
pairing: { code: string; expires_at: string } | null;
/**
* Dock (APC 0.12): the binding, written with the move to handoff and never changed: the hub's `pairing_id` from its
* acknowledgement, and whether that acknowledgement declared `binding: "pairing_id"`. The hub's `initialize` must
* name this pairing and this agent, or it gets 404.
*/
pairingId: string | null;
declared: boolean;
}
/** What Orders keeps: in a real app, tables in its database. It outlives the process (`OrdersAppOptions.store`). */
export interface OrdersStore {
/** Live grants, by secret. */
grants: Map<string, Grant>;
/** Revoked grants: the SHA-256 of the secret (never the secret) and when. */
revoked: Map<string, string>;
/** Orders implements Dock: revoked Direct grant hashes let a hub's introduction get 404 before the revoked answer (APC 0.12, M12). */
revokedDirect: Set<string>;
/** One pin per grant, by grant id. */
pins: Map<string, FocusRow>;
/** Consent nonces and `apc_link` codes (`DockConsent`, `ApcLinks`). */
kv: ApcKv;
}
export const newOrdersStore = (): OrdersStore => ({ grants: new Map(), revoked: new Map(), revokedDirect: new Set(), pins: new Map(), kv: memoryKv() });The app object: what the page is told about each agent (AgentRow), the options, the messages the page's stream carries (PageMessage), the cap on an MCP request's body (MCP_BODY_MAX_BYTES, read by cappedText), and the members every later excerpt uses: this.hubs (the hub allowlist), this.send (the fetch the server calls hubs with), this.pages (the person's open pages) and the rest.
/** What the person's page shows of each agent, for the agent bar and the Direct agent list. */
export interface AgentRow {
id: string;
name: string;
/** "direct", "dock", or both for one agent linked across the two paths (`apc_link`). */
paths: ApcProfile[];
/** The grants behind the row: two for a linked agent. */
grants: string[];
/** A Direct agent's MCP URL, for the person to paste into their agent. */
url: string | null;
client: string | null;
pin: { label: string; seen: boolean } | null;
/** Dock, before the dock connected: `"code"` (waiting for the person to type `pairing.code` in their dock) or `"connecting"` (the dock took the code and has not connected yet). */
waiting: "code" | "connecting" | null;
pairing: { code: string; expires_at: string } | null;
}
export interface OrdersAppOptions {
/** The app's public origin as you configure it, e.g. "https://orders.example": never read from a request. */
origin: string;
/** How agents reach it: ["direct"], ["dock"] or both. */
profiles: ApcProfile[];
/** Dock: the hubs this app pairs with, its constant allowlist: bare https origins, e.g. ["https://apc.tineira.com"]. */
hubs?: string[];
/** Dock, local development only: loopback hubs allowed over http, e.g. ["http://localhost:5200"]. Leave it out in production. */
localDevHubs?: string[];
/** The account shown on the consent card; set this from your own sign-in. */
account?: string;
/** Build orders-connect.ts as this same-origin asset, alongside orders-page.ts. */
connectScript?: string;
/** Whether a request carries the person's session: your own sign-in. Orders has one person, so by default every request does. */
signedIn?: (request: Request) => boolean;
/** How the server calls a hub; the global fetch by default. */
fetch?: typeof fetch;
/** Milliseconds since the epoch; Date.now by default. Every time limit of a dock grant is read through it. */
now?: () => number;
/** Dock: how long a live grant stays awake after the person's last wake action (T_idle); 30 minutes by default. */
idleMs?: number;
/** Where Orders keeps its grants; a new, empty store by default. */
store?: OrdersStore;
}
type PageMessage = { type: "presence"; event: PresenceMessage } | { type: "agents" };
/**
* A Connect visit answers `consent_required` with its nonce and code; a drop requests Connect or returns
* the grant, with `status: "pending"` and the code to wait on (`pairing`) while the dock has not taken the code,
* `"connecting"` once it has and until it connects, and `"paired"` for a live grant, pinned.
*/
export interface DropAnswer {
ok: boolean;
error?: string;
consent?: string;
pairing_code?: string;
replaces?: boolean;
grant_id?: string;
status?: string;
pairing?: { code: string; expires_at: string };
pin_error?: string;
}
/** The most of an MCP request Orders reads: 1 MiB, far more than any call it serves. Past it: HTTP 413. */
export const MCP_BODY_MAX_BYTES = 1_048_576;
/** A request's body as text, read up to `cap` bytes; null past it, or when its `content-length` already says so. */
async function cappedText(request: Request, cap: number): Promise<string | null> {
if (badContentLength(request.headers, cap)) return null;
const reader = request.body?.getReader();
if (!reader) return "";
const decoder = new TextDecoder();
let text = "";
for (let size = 0; ; ) {
const { done, value } = await reader.read();
if (done) return text + decoder.decode();
size += value.byteLength;
if (size > cap) {
void reader.cancel().catch(() => {});
return null;
}
text += decoder.decode(value, { stream: true });
}
}
export class OrdersApp {
readonly origin: string;
/** What `apc.json` and the page list: `dock` only while the app can pair, with a hub on its allowlist (M8). */
readonly profiles: ApcProfile[];
private readonly account: string;
private readonly connectScript: string;
private readonly host: string;
private readonly hubs: DockDropOptions;
private readonly signedIn: (request: Request) => boolean;
private readonly send: typeof fetch;
private readonly store: OrdersStore;
/** One wait_for_focus per grant: every request runs in this one object, so the places live in memory. */
private readonly waitSlots = new MemoryWaitSlots();
/** MCP's notifications/cancelled comes in a POST of its own: the calls in flight, to find the one it names. */
private readonly calls = new InflightCalls();
private view: { screen: string; params: Record<string, string | string[]>; selection: { kind: string; id: string } | null; updated_at: string } | null = null;
/** The person's open pages: each is a stream of messages (server-sent events). */
private readonly pages = new Set<(message: PageMessage) => void>();
/** Drops being answered now, by hub and agent: one at a time, and never a lock held across the hub call (M5). */
private readonly pairing = new Set<string>();
private readonly consent: DockConsent;
private readonly links: ApcLinks;
private readonly now: () => number;
private readonly idleMs: number;
constructor(options: OrdersAppOptions) {
this.origin = options.origin;
this.account = options.account ?? "Orders example account";
this.connectScript = options.connectScript ?? "/assets/dock-connect.js";
this.host = new URL(options.origin).host;
this.hubs = { hubs: options.hubs ?? [], localDevHubs: options.localDevHubs ?? [] };
// A mistyped allowlist fails here, at start, not on the first drop: parseDockDrop throws on an entry that is not a bare origin.
parseDockDrop(null, this.hubs);
const canPair = this.hubs.hubs.length + (this.hubs.localDevHubs?.length ?? 0) > 0;
this.profiles = options.profiles.filter((p) => p !== "dock" || canPair);
this.signedIn = options.signedIn ?? (() => true);
this.send = options.fetch ?? ((...args) => fetch(...args));
this.store = options.store ?? newOrdersStore();
const now = options.now ?? Date.now;
this.now = now;
this.idleMs = options.idleMs ?? T_IDLE_RECOMMENDED_MS;
this.consent = new DockConsent(this.store.kv, { now });
// apc_link sees the grants an agent can read with: a Direct one, or a Dock one its hub connected.
this.links = new ApcLinks(this.store.kv, { appName: "Orders", now, grants: () => this.live().filter((g) => g.state === "live").map((g) => ({ id: g.id, path: g.path })) });
}The app's routes: apc.json, the MCP URLs, the hub's give-back (Dock), and the person's own routes. apcManifest builds the apc.json from what the app offers; apcJsonResponse serves it as public JSON.
async fetch(request: Request): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === "/connect/dock" && request.method === "GET") {
if (!this.profiles.includes("dock")) return Response.json({ error: "not_found" }, { status: 404 });
return dockConnectPage("Orders", { session: false, signedIn: this.signedIn(request), account: this.signedIn(request) ? this.account : "No account signed in. Open Orders to sign in, then return to this link.", script: this.connectScript });
}
// What Orders is, for hubs, the browser extension and any tool (apc.json). Its one MCP endpoint (APC 0.11) is
// exact: a grant's secret under /mcp/, on both profiles; /mcp/ stays for readers before 0.11.
if (path === "/.well-known/apc.json") {
const endpoints = [{ path: "/mcp/{secret}", profiles: ["direct", "dock"] }] as const;
return apcJsonResponse(apcManifest({ name: "Orders", origin: this.origin, profiles: this.profiles, connect: "/agents", ...(this.profiles.includes("dock") ? { dockConnect: "/connect/dock" } : {}), mcpPath: "/mcp/", endpoints }));
}
// Each grant's MCP URL: the agent itself (Direct) or a dock's hub (Dock) calls it.
const mcp = path.match(/^\/mcp\/([0-9a-f]{32})$/);
if (mcp) return this.mcp(request, mcp[1]!);
// apc.json's "/mcp/{secret}" claims every child of /mcp/ that fits a secret (APC 0.11): one that names no grant is
// an unknown grant, and answers 404 like one, never this app's other answers (a 401 for no session, say).
if (path.startsWith("/mcp/") && APC_SECRET_RE.test(path.slice("/mcp/".length))) return Response.json({ error: "unknown_grant" }, { status: 404 });
// A dock's hub gives a grant back (Dock): public, so it answers the same 200 to anything (handleDockGiveBack).
if (path === "/apc/revoke") return handleDockGiveBack(request, { origin: this.origin, endGrantBySecretHash: (hash) => this.givenBack(hash) });
// The person's own routes: their session, and for every change the rule on the owner's endpoints.
const refused = this.refuseOwner(request);
if (refused) return refused;
if (path === "/api/events") return this.events();
if (path === "/api/agents/list") return Response.json(this.agents());
if (request.method !== "POST") return Response.json({ error: "not_found" }, { status: 404 });
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
if (path === "/api/view") return Response.json(this.reportView(body));
if (path === "/api/agents") return Response.json(await this.addAgent());
if (path === "/api/connect/dock") return Response.json(await this.drop(body, true));
if (path === "/api/drop") return Response.json(await this.drop(body));
if (path === "/api/cancel") return Response.json(this.cancel(body?.grant_id));
if (path === "/api/heartbeat") return Response.json(this.heartbeat());
const agent = path.match(/^\/api\/agents\/(g_[0-9a-f]{8})\/(pin|unpin|revoke|unlink)$/);
if (agent) {
const id = agent[1]!;
const action = agent[2];
if (action === "pin") return Response.json(this.pin(id, body?.target));
if (action === "unpin") return Response.json(this.unpin(id));
if (action === "revoke") return Response.json(this.revoke(id));
return Response.json(this.unlink(id));
}
return Response.json({ error: "not_found" }, { status: 404 });
}mcp.pathstarts and ends with/. It is a prefix: every grant's MCP URL starts with your origin plus it (/mcp/here, each grant at/mcp/{secret}). An app whose grants share one URL,/mcpwith a bearer token, still declaresmcpPath: "/mcp/"; the shared URL is covered asmcp.pathwithout its last/, and since 0.11 as an exact entry ofmcp.endpoints({ path: "/mcp", profiles: ["direct"] }).apcManifestthrows on any othermcpPath, and says how to fix it.- Build
apc.jsononce, when the app starts, not per request, as the complete Direct app does: a mistake then fails at start instead of answering every reader with HTTP 500.
The person's routes need their session, and every change is a JSON POST checked against the origin you configured, never one read from the request (M6): another site's page cannot drop, allow or cancel for them, and a client that is not a browser is taken on its session.
/**
* The person's routes (M6, APC 0.10): their session, and every change is a POST of `application/json`. A
* request that carries `Origin` must name this app's configured origin; one a browser marks `cross-site` or
* `same-site` is refused; one with neither header is not a browser (a desktop client, a script) and is taken
* on its session. A browser always sends `Origin` on a cross-origin POST, and a cross-origin JSON POST needs a
* CORS preflight this app never grants, so another site's page cannot drop, allow or cancel for the person.
*/
private refuseOwner(request: Request): Response | null {
const no = (error: string, status: number) => Response.json({ error }, { status });
if (!this.signedIn(request)) return no("unauthorized", 401);
if (request.method !== "POST") return null;
const origin = request.headers.get("origin");
if (origin !== null && origin !== this.origin) return no("origin_not_allowed", 403);
const site = request.headers.get("sec-fetch-site");
if (site === "cross-site" || site === "same-site") return no("cross_site_request", 403);
const media = (request.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase();
return media === "application/json" ? null : no("json_required", 415);
}The small helpers on OrdersApp that the later routes use (mcpUrl, live, byId and publish to open page streams):
/** A grant's MCP URL: the origin, apc.json's endpoint "/mcp/{secret}", with the secret. */
mcpUrl(secret: string): string {
return `${this.origin}/mcp/${secret}`;
}
private live(): Grant[] {
return [...this.store.grants.values()];
}
private byId(id: string): Grant | undefined {
return this.live().find((g) => g.id === id);
}
/** To every open page. A page whose stream closed without telling us is dropped: it never fails the tool call that published. */
private publish(message: PageMessage): void {
for (const send of this.pages) {
try {
send(message);
} catch {
this.pages.delete(send);
}
}
}4. Direct: an agent per grant#
The person makes an agent on the page, and copies its URL into their agent as a remote MCP server (Streamable HTTP, no OAuth: the access is in the URL). An app whose agents authenticate with a bearer token on one shared URL instead is the complete Direct app below.
/** Direct: the person makes an agent on the page. It gets its own grant, and the URL to paste into the agent. */
async addAgent(): Promise<{ ok: boolean; id?: string; url?: string; error?: string }> {
if (!this.profiles.includes("direct")) return { ok: false, error: "direct_not_offered" };
const { id, secret } = newDirectGrant();
this.store.grants.set(secret, { id, secret, hash: await secretHash(secret), path: "direct", name: "New agent", client: null, hub: null, agent: null, state: "live", allowedAt: 0, ackedAt: 0, lastWake: 0, pairing: null, pairingId: null, declared: false });
this.publish({ type: "agents" });
return { ok: true, id, url: this.mcpUrl(secret) };
}In the page, <apc-direct-agents> is that list, with the URL and a prompt the person can paste to their agent, which asks it to add the server itself:
/** Direct: the list where the person makes an agent and copies its URL (and a prompt) into their agent. */
defineDirectAgents();
const direct = document.querySelector("apc-direct-agents") as ApcDirectAgentsElement;
direct.appName = "Orders";
direct.addEventListener("apc-add", () => void post("/api/agents").then(refresh));5. The view#
The page reports the screen as identifiers whenever it changes, and the server keeps it, checked:
/** The screen as identifiers: sent when it changes (debounced, and only while the tab is visible). */
const reportView = createViewReporter((view) => void post("/api/view", view));
export function showOrders(status: "open" | "shipped" | null, selected: string | null): void {
reportView({ screen: "orders", params: status ? { status } : {}, selection: selected ? { kind: "order", id: selected } : null });
}/** The page reports the screen as identifiers: a screen name, key-only params, at most one selected row. */
reportView(raw: Record<string, unknown> | null): { ok: boolean } {
const screen = typeof raw?.screen === "string" && /^[a-z][a-z0-9_]{0,31}$/.test(raw.screen) ? raw.screen : null;
const params = parseParams(raw?.params ?? {});
const s = raw?.selection as { kind?: unknown; id?: unknown } | null | undefined;
const selection = s && s.kind === "order" && typeof s.id === "string" && ORDERS.some((o) => o.id === s.id) ? { kind: "order", id: s.id } : null;
if (!screen || !params) return { ok: false };
this.view = { screen, params, selection, updated_at: new Date().toISOString() };
return { ok: true };
}
private viewPayload(): ViewPayload | null {
if (!this.view) return null;
const age = Math.max(0, Math.round((Date.now() - Date.parse(this.view.updated_at)) / 1000));
return { ...this.view, app_url: `${this.origin}/${this.view.screen}`, age_seconds: age, stale: age > 300, next: this.view.selection ? "get_order" : "list_orders" };
}6. The pin#
The person drops an agent's mark on a target. The server keeps one pin per grant, and turns it into the focus the agent receives, with next and next_args: the exact call that reads it.
/** The person drops an agent's mark on a target. One pin per grant: a new one replaces it, unread. */
pin(grantId: string, raw: unknown): { ok: boolean; error?: string } {
if (!this.byId(grantId)) return { ok: false, error: "unknown_grant" };
const target = raw && typeof raw === "object" ? parseTarget(raw) : null;
if (!target || target.kind !== "order" || !ORDERS.some((o) => o.id === target.id)) return { ok: false, error: "invalid_target" };
this.store.pins.set(grantId, { ...target, grant_id: grantId, pinned_at: new Date().toISOString(), seen_at: null });
this.publish({ type: "agents" });
return { ok: true };
}
unpin(grantId: string): { ok: boolean } {
const had = this.store.pins.delete(grantId);
this.publish({ type: "agents" });
return { ok: had };
}
/** What the agent receives: the target, where it is, and the exact call that reads it. */
private focusPayload(grantId: string): FocusPayload | null {
const pin = this.store.pins.get(grantId);
if (!pin?.id) return null;
return { kind: pin.kind, id: pin.id, part: pin.part, params: pin.params, app_url: `${this.origin}/orders/${pin.id}`, pinned_at: pin.pinned_at, next: "get_order", next_args: { id: pin.id } };
}7. The MCP endpoint#
One MCP server per request, for the grant in the URL. registerApcTools adds get_current_view and wait_for_focus, reading through the functions you give it; your own tools sit next to them. A revoked grant is answered 403 before anything else, whatever the method.
Three of those functions keep the core's promises (APC 0.8). markSeen(pinnedAt) marks that exact pin seen, never a newer one: the tools call it only once the result is final, so a pin is never lost. waitSlot is the grant's one place for a wait: MemoryWaitSlots keeps it in memory, which is right when every request of the person runs in one process (as here, or in a Durable Object); on stateless functions keep a row per grant with the holder's token and when it claimed. signal ends a wait the client gave up on: the request's own, and InflightCalls', since a server that is new for every POST sees MCP's notifications/cancelled only in a POST of its own.
private async mcp(request: Request, secret: string): Promise<Response> {
// The hash first: it is what tells "revoked" from "unknown", now and for the calls this request runs.
const hash = await secretHash(secret);
// The message is read before the grant is looked up (so nothing is awaited between the lookup and the gate), and
// whoever sends it need not hold a grant: so it is read up to a cap, and the same 413 answers any secret past it.
const text = request.method === "POST" ? await cappedText(request, MCP_BODY_MAX_BYTES).catch(() => null) : "";
if (text === null) return Response.json({ error: "too_large" }, { status: 413 });
let body: unknown = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
// not JSON: the gate takes it as "another method", and the transport answers the parse error
}
// Nothing is awaited from here to the gate and the commit below: the grant's state cannot change in between.
this.sweep();
const grant = this.store.grants.get(secret);
// Orders implements Dock: a hub introducing itself to a non-Dock grant (APC 0.12, M12) gets 404 before anything else, a revoked
// Direct grant included, and nothing changes. Whether it is a Dock grant is Orders' own record, never the URL:
// here both profiles share /mcp/{secret}.
if (grant ? grant.path === "direct" : this.store.revokedDirect.has(hash)) {
const refused = directGrantGate(body);
if (refused) return refused;
}
if (!grant) {
const revokedAt = this.store.revoked.get(hash);
// Revoked in the app: 403 with who and when, whatever the method. Unknown, ended or given back: 404.
return revokedAt ? revokedResponse(this.host, revokedAt) : Response.json({ error: "unknown_grant" }, { status: 404 });
}
// Dock (APC 0.10): the grant's state decides the answer, before the transport and before anything that
// notes the client, publishes presence or attaches attention, then or apc_link. In flight: 404. Handoff:
// only initialize, ping and tools/list are served, a tool call gets the `pairing` error. Dormant: the idle shapes.
if (grant.path === "dock") {
// The binding (APC 0.12, M11): the hub's initialize must name this grant's own pairing and agent.
const gate = dockGrantGate(this.stateOf(grant), body, { host: this.host, binding: { pairing_id: grant.pairingId, agent: grant.agent ?? "", declared: grant.declared } });
if (!gate.serve) return gate.response;
// The hub's first initialize is the dock owner's yes: it makes the grant live, or it gets no result (it fails closed).
if (gate.commits) {
let committed: boolean;
try {
committed = this.commitConnection(grant);
} catch {
return Response.json({ error: "storage_failed" }, { status: 500 });
}
// Cancel, a give-back or a time limit got there first: answered by the state that won.
if (!committed) return this.store.revoked.has(hash) ? revokedResponse(this.host, this.store.revoked.get(hash)!) : Response.json({ error: "unknown_grant" }, { status: 404 });
}
}
if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } });
// A cancel in this POST ends the call it names; the calls this POST carries can be cancelled the same way.
this.calls.cancel(grant.id, body);
const inflight = this.calls.track(grant.id, body);
// A connection arrives: note its client (for the bar, and for apc_link).
const arriving = initializeOf(body);
if (arriving) {
grant.client = linkClient(arriving, grant.path);
if (grant.path === "direct" && grant.name === "New agent" && arriving.name) grant.name = arriving.name;
this.links.arrived(grant.id, grant.client);
this.publish({ type: "agents" });
}
const server = new McpServer({ name: "orders", version: "1.0.0" }, { instructions: `${APC_INSTRUCTIONS} Orders lists a shop's orders: customer, status and total.` });
this.aroundEveryTool(server, grant, hash);
registerApcTools(server, {
readView: async () => this.viewPayload(),
readFocus: async () => this.focusPayload(grant.id),
focusUnread: async () => isUnread(this.store.pins.get(grant.id) ?? null),
// Seen once delivered: the exact pin the result carried, never a newer one dropped since.
markSeen: async (pinnedAt) => {
const pin = this.store.pins.get(grant.id);
if (pin?.pinned_at === pinnedAt) pin.seen_at = new Date().toISOString();
this.publish({ type: "agents" });
},
// A wait ends when the person has no page open, and when its grant is revoked meanwhile.
pageOpen: async () => this.store.grants.get(secret) === grant && this.pages.size > 0,
// One wait per grant: a newer wait takes over, a cancelled one frees its place.
waitSlot: this.waitSlots.for(grant.id),
// Wait events (APC 0.11): the page knows the agent is listening while a wait holds its place.
waitPresence: { grantId: grant.id, publish: (event) => this.publish({ type: "presence", event }) },
signal: AbortSignal.any([request.signal, inflight.signal]),
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
pollMs: 500,
});
server.registerTool(
"list_orders",
{ title: "List the orders", description: "Every order: id, customer and status.", inputSchema: {}, annotations: { readOnlyHint: true } },
async () => toolResult({ orders: ORDERS.map(({ id, customer, status }) => ({ id, customer, status })) }),
);
server.registerTool(
"get_order",
{ title: "Read one order", description: "One order by id (ord_NNNN): customer, status and total. Usually called with the next_args of a focus.", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true } },
async ({ id }) => {
const order = ORDERS.find((o) => o.id === id);
return order ? toolResult({ order }) : toolError("unknown_order", `No order ${id}.`);
},
);
// apc_link: with both profiles, the same agent on both paths shows as one.
if (this.profiles.includes("direct") && this.profiles.includes("dock")) {
registerApcLinkTool(server, { appName: "Orders", redeem: (code) => this.links.redeem(grant.id, code) });
}
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
await server.connect(transport);
// The transport wants a client that takes both JSON and an event stream; some clients send less.
const headers = new Headers(request.headers);
headers.set("accept", "application/json, text/event-stream");
try {
// The body was read above: the transport gets it back as it came.
return await transport.handleRequest(new Request(request.url, { method: "POST", headers, body: text, signal: request.signal }));
} finally {
inflight.done();
}
}On Cloudflare Workers, give the server jsonSchemaValidator: new CfWorkerJsonSchemaValidator() (from @modelcontextprotocol/sdk/validation/cfworker), and keep the state in a Durable Object: sqlKv(ctx.storage.sql) gives DockConsent and ApcLinks their table.
8. Around every tool#
This is where APC rides on your results. Every tool, the two APC tools included, runs inside one wrapper that:
- ends the call
revokedif its grant was revoked, before or while it ran; - puts
attentionon the result while the grant's pin is unread; - publishes presence to the person's page, naming what a read touched (and, since APC 0.11,
registerApcToolssends a wait'sopenandclosedthere itself when you give itwaitPresence); - puts
thenon the result while a page of the person's is open and the grant was pinned in the last 30 minutes (thenApplies), but never on a wait that came back empty; - carries an
apc_linkoffer, once per session, when the same agent is connected both ways.
/**
* Around every tool, the two core tools included (registerApcTools registers through
* server.registerTool too): the grant is checked before and after the tool, `attention` rides while the
* pin is unread, presence goes to the person's pages, `then` rides while a page is open and the grant
* was pinned in the last 30 minutes, and an `apc_link` offer once per session.
*/
private aroundEveryTool(server: McpServer, grant: Grant, hash: string): void {
const register = server.registerTool.bind(server) as (...args: unknown[]) => unknown;
// Revoked meanwhile? Told by this grant's own secret, never by an id a later grant may reuse.
const cut = (): ToolResult | null => {
if (this.store.grants.get(grant.secret) === grant) return null;
const revokedAt = this.store.revoked.get(hash);
return revokedAt ? revokedToolResult(this.host, revokedAt) : toolError("unknown_grant", "This grant no longer exists.");
};
(server as unknown as { registerTool: (...args: unknown[]) => unknown }).registerTool = (name: unknown, config: unknown, run: unknown) =>
register(name, config, async (args: Record<string, unknown>, extra: unknown): Promise<ToolResult> => {
const tool = String(name);
const before = cut();
if (before) return before;
let result = await (run as (args: unknown, extra: unknown) => Promise<ToolResult>)(args, extra);
const after = cut();
if (after) return after;
const focus = this.focusPayload(grant.id);
if (focus && isUnread(this.store.pins.get(grant.id) ?? null)) result = attachAttention(result, attentionFor(focus));
if (!result.isError) {
const targets = tool === "get_order" && typeof args.id === "string" ? [{ kind: "order", id: args.id }] : [];
this.publish({ type: "presence", event: presenceEvent({ grantId: grant.id, tool, kind: "read", targets }) });
}
// A wait that came back with no pin ends the loop: no `then` on it.
const emptyWait = tool === "wait_for_focus" && result.structuredContent?.focus == null;
result = attachThen(result, !emptyWait && thenApplies(this.pages.size > 0, this.store.pins.get(grant.id)?.pinned_at));
const offer = result.isError ? null : await this.links.offer(grant.id, tool);
return offer ? attachApcLink(result, offer) : result;
});
}9. The agent bar and pinning#
In the page, <apc-agents> is the agent bar: each agent's mark (drag it onto a target), its pin (× to unpin), ⊘ to revoke (a second click confirms), and the path it came by. enablePinning makes marks draggable onto anything with data-focus, and on a phone lets a finger tap a mark and then a target.
/** The agent bar, top right: every agent's mark (drag it onto a row), its pin, × to unpin, ⊘ to revoke. */
defineAgentBar();
const bar = document.querySelector("apc-agents") as ApcAgentsElement;
const marks = new Map<string, string>(); // grant id -> initials, for presence
const onAgent = (event: string, run: (id: string) => Promise<unknown>) => bar.addEventListener(event, (e) => void run((e as CustomEvent<{ id: string }>).detail.id).then(refresh));
onAgent("apc-revoke", (id) => post(`/api/agents/${id}/revoke`));
onAgent("apc-unpin", (id) => post(`/api/agents/${id}/unpin`));
onAgent("apc-unlink", (id) => post(`/api/agents/${id}/unlink`));
/** The agents, from the server: into the bar, Direct agent list, and any optional panels (pets, Dock waiting). */
const onRefresh: Array<(rows: AgentRow[]) => void> = [];
async function refresh(): Promise<void> {
const rows = (await (await fetch("/api/agents/list")).json()) as AgentRow[];
marks.clear();
for (const row of rows) marks.set(row.id, initials(row.name, new Set(marks.values())));
bar.agents = rows.map((a) => ({ id: a.id, name: a.name, state: "idle", paths: a.paths, pin: a.pin ? { ...a.pin, here: true } : null }));
direct.agents = rows.filter((a) => a.url).map((a) => ({ id: a.id, name: a.name, url: a.url!, connected: a.client !== null, client: a.client, linked: a.paths.length === 2 }));
for (const after of onRefresh) after(rows);
}The page's event stream is how the server knows a page is open, and how presence reaches the page:
/** The page's stream: an open page (what `then` and wait_for_focus look at), presence, and changes. flashTargets ignores a wait event (APC 0.11). */
const events = new EventSource("/api/events");
events.onmessage = (message) => {
const data = JSON.parse(message.data as string) as { type: string; event?: Parameters<typeof flashTargets>[0] };
if (data.type === "presence" && data.event) flashTargets(data.event, marks.get(data.event.grant_id) ?? "?");
else void refresh();
};
/**
* The heartbeat (Dock, APC 0.10): while the page is open it tells the server the person is here, at least every
* T_idle / 2. A dock agent's grant sleeps T_idle after the last one, and wakes with the next. The server's answer
* carries the T_idle it runs with (`idle_ms`), so the page follows it; until one arrives it assumes the recommended one.
*/
let idleMs = T_IDLE_RECOMMENDED_MS;
async function heartbeat(): Promise<void> {
const answer = await post("/api/heartbeat").catch(() => null);
if (typeof answer?.idle_ms === "number" && answer.idle_ms > 0) idleMs = answer.idle_ms;
// Every quarter of T_idle: one beat that fails still leaves the next inside T_idle / 2.
setTimeout(() => void heartbeat(), Math.max(1000, idleMs / 4));
}
void heartbeat();/** The agents as the person's page shows them: a linked agent once, with both paths. */
agents(): AgentRow[] {
const rows: AgentRow[] = [];
this.sweep();
for (const g of this.live()) {
if (g.state === "in_flight") continue; // the hub has not acknowledged it yet
const partner = this.links.partnerOf(g.id);
if (partner && g.path === "dock") continue; // shown with its Direct grant
const pin = this.store.pins.get(g.id);
rows.push({
id: g.id,
name: g.name,
paths: partner ? ["direct", "dock"] : [g.path],
grants: partner ? [g.id, partner] : [g.id],
url: g.path === "direct" ? this.mcpUrl(g.secret) : null,
client: g.client,
pin: pin ? { label: `order ${pin.id}`, seen: !isUnread(pin) } : null,
waiting: g.state === "handoff" ? (g.pairing ? "code" : "connecting") : null,
pairing: g.pairing,
});
}
return rows;
}
/** The person's page: a stream of messages (presence, and "agents changed"). An open stream is an open page. */
events(): Response {
const encoder = new TextEncoder();
let send: ((message: PageMessage) => void) | null = null;
const stream = new ReadableStream<Uint8Array>({
start: (controller) => {
// Throws once the stream is closed; publish() then drops this page.
send = (message) => controller.enqueue(encoder.encode(`data: ${JSON.stringify(message)}\n\n`));
this.pages.add(send);
},
cancel: () => {
if (send) this.pages.delete(send);
},
});
return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
}/**
* Pinning: a mark dragged (or, on a phone, tapped then a row tapped) onto anything with data-focus pins that
* agent there. Agents dropped from a dock come with a hub and a ticket, and always go to the server (wired
* in Step 12 for Dock; omitted in Direct-only apps).
*/
let onDockDrop: ((drag: AgentDrag & { hub: string; ticket: string }, target: FocusTarget) => void) | undefined;
enablePinning({
onPin: (grantId, target) => void post(`/api/agents/${grantId}/pin`, { target }).then(refresh),
acceptNativeDrops: true,
resolveAgent: () => null, // every dock drop goes to the server, which decides
onUnknownAgent: (drag, target) => onDockDrop?.(drag, target),
profiles: () => loadApcProfiles(),
direct: { name: "Orders", connect: `${location.origin}/agents` },
});The isTrusted guard and automating drops in tests. enablePinning defaults trusted to (event) => event.isTrusted === true (and <apc-agents>, <apc-pets> and <apc-pin> check event.isTrusted on their unpin, unlink, revoke and open buttons), so a script running inside the page (element.click(), or a synthetic PointerEvent or KeyboardEvent from dispatchEvent) cannot arm, drag or point an agent at data without the person acting. Because of that guard, synthetic DOM events from page.evaluate(...) are ignored in browser tests:
- In Chromium / Playwright, drive real browser input so Chromium sets
isTrusted: true: in-page marks use pointer events (not HTML5draggable), so move the real pointer from the mark's centre to the target's centre (page.mouse.move/down/move/up, orInput.dispatchMouseEventover CDP;Input.dispatchTouchEventfor touch taps on mobile); for a cross-window dock drop, sendInput.dispatchDragEvent(dragEnter,dragOver,drop) over CDP withapplication/x-apc-agent. Automating drops in Chromium shows both helpers. - In a unit or DOM test without real browser input, pass
trusted: () => truetoenablePinning(in test harnesses only, never in production — page scripts cannot reachenablePinning's options) or drivecreateTapPindirectly asorders-conformance.tsdoes forpage.mobile.
On a phone, @tineira/apc-web already keeps the bar in the page, uncollapsed, at the bottom of the viewport, with finger-sized marks, and turns a tap on a mark into "tap to pin". Check your own layout at 375 × 812 (mobile, and phones in the UX guide).
The agent in the page#
To show your agents as the dock does, put <apc-pets> in your header: each agent a pet, up to 3, then a "+N" (or list) button that opens a popover of every agent (the agent in the page holds the rules, the UX guide the pattern). Each pet is a mark and only a mark, so enablePinning drags it like the bar's, and a tap or Enter on it arms the agent. Feed petState only what your page knows; a field you leave out stays at its default, so a pet never shows a wait your page cannot see. Pass waiting once your page reads the wait signal.
/**
* The agent in the page: each agent a pet in the header, up to 3 and then "+N", the same character the dock draws.
* A pet is a mark too: drag it onto a row to point the agent. Its state comes only from what the page knows: an
* unread pin, a call presence just reported, a wait open (APC 0.11, from the wait events), a pairing waiting on the
* person. Never a guess from timing.
*/
defineHeaderPets();
const pets = document.querySelector("apc-pets") as ApcPetsElement;
pets.scheme = "auto"; // follow the page's prefers-color-scheme; an app with a theme switch passes "light" or "dark"
const heard = new Map<string, number>(); // grant id -> when presence last reported a call
let openWaits: OpenWaits = NO_OPEN_WAITS; // the waits open now, from the wait events (APC 0.11)
let expiry: ReturnType<typeof setTimeout> | undefined;
events.addEventListener("message", (message) => {
const data = JSON.parse(message.data as string) as { type: string; event?: { grant_id: string; kind?: string } };
if (data.type !== "presence" || !data.event) return;
if (data.event.kind === "wait") {
openWaits = foldWaitEvent(openWaits, data.event);
// A closed that never came runs out at the ceiling plus the margin: look again then.
clearTimeout(expiry);
const at = nextWaitExpiry(openWaits);
if (at !== null) expiry = setTimeout(() => ((openWaits = dropExpiredWaits(openWaits)), showPets()), Math.max(0, at - Date.now()) + 50);
} else heard.set(data.event.grant_id, Date.now());
showPets();
setTimeout(() => showPets(), 4000);
});
let petRows: AgentRow[] = [];
function showPets(rows: AgentRow[] = petRows): void {
petRows = rows;
pets.agents = rows.map((a) => ({
id: a.id,
name: a.name,
badge: agentBadge({ clientName: a.client, key: a.id }),
pin: a.pin ? { ...a.pin, here: true } : null,
// An open wait_for_focus shows as `waiting` only from the wait events, and only on a Direct grant: a dock agent waits on the hub.
state: petState({
connected: a.client !== null,
waiting: agentWaitOpen(openWaits, a.grants.map((id, i) => ({ id, path: a.paths[i] ?? a.paths[0]! }))),
busy: Date.now() - (heard.get(a.id) ?? 0) < 4000,
pin: a.pin && !a.pin.seen ? "unread" : "none",
requests: a.waiting === "code" ? 1 : 0,
}),
}));
}
onRefresh.push(showPets);If you stop at Step 10 for Direct only, call void refresh(); once after this block; the full app calls it at the end of Step 12 after #waiting so the bar, Direct list, header pets and waiting rows populate on initial load.
- Colours.
scheme = "auto"followsprefers-color-scheme. With your own theme switch, setschemeto"light"or"dark"when it changes. To tint the pet to a strict palette, settint({ body, line }, hex) or the custom properties--apc-pet-bodyand--apc-pet-line. - Size.
--apc-pets-size(36 px by default) sizes the pets; each stays a 44 px target. A lone pet anywhere else iscreatePet({ state, badge, label })(or<apc-pet>), sized bysizeor--apc-pet-size. - Logos.
agentBadge({ clientName, key })gives the brand's logo, else the client's icon, else a neutral mark in the agent's own colour.<apc-pin>wears the same badge when you setbadgeon its agent;pinStackIndexplaces several badges on one element. - Words.
<apc-pets>takesstrings(PetsStrings) like the other components.
10. Revoke#
Revoke holds in the app alone, at once, and calls nobody. The app keeps a hash of the secret, so the URL answers revoked from then on, and a call already running ends the same way.
/** Revoke from the app: at once, calling nobody, in any state. A linked agent is one agent: both its grants go. */
revoke(grantId: string): { ok: boolean } {
const partner = this.links.partnerOf(grantId);
const cut = this.live().filter((g) => g.id === grantId || g.id === partner);
if (!cut.length) return { ok: false };
for (const g of cut) this.revokeNow(g);
this.publish({ type: "agents" });
return { ok: true };
}
/** The grant's URL answers `revoked` from now on: its hash is kept, never its secret. Nothing is awaited (the hash is on the grant). */
private revokeNow(g: Grant): void {
this.store.revoked.set(g.hash, new Date().toISOString());
if (g.path === "direct") this.store.revokedDirect.add(g.hash);
this.forget(g);
}
private forget(g: Grant): void {
this.links.forget(g.id);
this.waitSlots.forget(g.id);
this.store.pins.delete(g.id);
this.store.grants.delete(g.secret);
}With both profiles, unlink separates a linked agent again while keeping both grants:
/** Unlink: a linked agent shows as two again. Both grants stay. */
unlink(grantId: string): { ok: boolean } {
const ok = this.links.unlink(grantId) !== null;
this.publish({ type: "agents" });
return { ok };
}11. Try it with your agent#
Run the app on a public HTTPS origin (a tunnel works for a test), make an agent on the page, and add its URL to your agent (Claude, ChatGPT, Cursor, Grok: any client that takes a remote MCP server). Drag its mark onto an order and ask "what is this?". The agent sees attention on its next call, or calls get_current_view, then get_order with the focus's next_args.
12. Dock: agents dragged from a dock#
Add "dock" to the profiles and list the hubs you pair with. A dock's agent arrives as a drag with a hub, a public handle and a single-use ticket. The page sends every such drop to the server (resolveAgent: () => null and onUnknownAgent above); the server decides:
/**
* Dock: the person dropped an agent from a dock on the page. Every such drop comes here, whatever the
* page thinks it knows. The Connect page's Allow enters with `connect = true` and its nonce. `parseDockDrop`
* checks the drag's hub against the allowlist both times (M1) and gives back its origin, which is where the
* hub calls go (M9). An agent with no grant gets one only with the person's yes on this page, proven by the
* nonce; the consent shows a pairing code, which the hub gets with the grant and the person types in their dock.
*/
async drop(raw: Record<string, unknown> | null, connect = false): Promise<DropAnswer> {
if (!this.profiles.includes("dock")) return { ok: false, error: "dock_not_offered" };
const parsed = parseDockDrop(raw, this.hubs);
if (!parsed.ok) return { ok: false, error: parsed.error };
const { hub, agent, ticket } = parsed;
// One drop, Allow or confirm of an agent at a time: a double-clicked Allow changes nothing.
const key = `${hub} ${agent}`;
if (this.pairing.has(key)) return { ok: false, error: "pairing_in_progress" };
this.pairing.add(key);
try {
return await this.dropOnce(hub, agent, ticket, raw?.target, raw?.consent, connect);
} finally {
this.pairing.delete(key);
}
}
private async dropOnce(hub: string, agent: string, ticket: string, target: unknown, consent: unknown, connect: boolean): Promise<DropAnswer> {
const scope = `${agent} ${ticket} connect`;
// This store belongs to one person. Keep their drop across the hub's fragment-only Connect handoff,
// for at most six minutes (the request plus ticket lifetimes), including across a server restart.
const targetKey = `connect-target:${hub} ${agent}`;
for (const [key, value] of this.store.kv.list("connect-target:")) {
const saved = JSON.parse(value) as { target?: unknown; expiresAt: number };
if (saved.expiresAt <= this.now()) this.store.kv.delete(key);
}
if (connect && target === undefined) {
const saved = this.store.kv.get(targetKey);
if (saved) target = (JSON.parse(saved) as { target?: unknown }).target;
}
const requestFirst = async (): Promise<DropAnswer> => {
const answer = await requestConnect(hub, { ticket, agent, app: { origin: this.origin } }, { fetch: this.send });
if (answer.ok) this.store.kv.put(targetKey, JSON.stringify({ target, expiresAt: this.now() + 360_000 }));
return answer.ok ? answer : { ok: false, error: answer.error };
};
// The newest consent asked for this agent: a new drop replaces the one before it.
const newest = `asked:${hub} ${agent}`;
const askFirst = (): DropAnswer => {
const asked = this.consent.ask(hub, scope);
this.store.kv.put(newest, asked.nonce);
return { ok: false, error: CONSENT_REQUIRED, consent: asked.nonce, pairing_code: asked.pairing_code, ...(held ? { replaces: true } : {}) };
};
this.sweep();
const held = this.live().find((g) => g.hub === hub && g.agent === agent);
if (held && !connect) {
// Its Allow still waits on the hub (in another request, or in a process that died): T_ack ends it within 30 s.
if (held.state === "in_flight") return { ok: false, error: "pairing_in_progress" };
// Its code ran out (the stored expiry): the grant ends before the hub is asked, so /apc/confirm does not spend
// the drag's ticket and the person is asked again with it (from 0.13, through the hub's Connect).
if (held.state === "handoff" && held.pairing && Date.parse(held.pairing.expires_at) <= this.now()) {
this.forget(held);
this.publish({ type: "agents" });
return requestFirst();
}
// A grant already: the hub must still say it pairs them, on every drop.
const check = await confirmWithHub(hub, { ticket, agent, mcp_url: this.mcpUrl(held.secret) }, { fetch: this.send });
// Cancel, Revoke, a give-back or a time limit may have taken the grant while the hub answered.
this.sweep();
if (this.store.grants.get(held.secret) !== held) return { ok: false, error: "pairing_ended" };
if (!check.ok && check.error !== "not_paired") return { ok: false, error: check.error };
const expired = !held.pairing || Date.parse(held.pairing.expires_at) <= this.now();
// The dock no longer pairs it, or it did not take the code in time: the grant ends, and the person is asked again.
if (!check.ok || (held.state === "handoff" && check.status === "pending" && expired)) {
this.forget(held);
this.publish({ type: "agents" });
return requestFirst();
}
const pinned = this.pin(held.id, target);
const pinError = pinned.ok ? {} : { pin_error: pinned.error };
if (held.state === "handoff") {
// Still waiting for the code in the dock: the same code, never a new one. The drop's target replaces the pin.
if (check.status === "pending") return { ok: true, grant_id: held.id, status: "pending", pairing: held.pairing!, ...pinError };
// The dock took the code and has not connected yet. Only its initialize makes the grant live, never this answer.
held.pairing = null;
this.publish({ type: "agents" });
return { ok: true, grant_id: held.id, status: "connecting", ...pinError };
}
// A live grant: the confirmed drop is a wake action of the person's.
held.lastWake = this.now();
return { ...pinned, grant_id: held.id, status: check.status };
}
// A drop only requests Connect; only its page can take consent and make the grant.
if (!connect) return requestFirst();
if (consent === undefined || consent === null) return askFirst();
const { id, secret } = newDirectGrant(); // any grant's id and secret
const hash = await secretHash(secret);
// From the nonce to the grant in flight, nothing is awaited.
if (this.store.kv.get(newest) !== consent) return { ok: false, error: "consent_expired" };
const taken = this.consent.takeConsent(consent, hub, scope);
if (!taken.ok) return { ok: false, error: "consent_expired" };
this.store.kv.delete(newest);
const now = this.now();
// In flight: stored before the hub is called, so its URL answers 404 until the hub acknowledges it.
// On re-Connect, the previous grant stays active until the hub acknowledges the new pairing.
const grant: Grant = { id, secret, hash, path: "dock", name: "Agent via dock", client: null, hub, agent, state: "in_flight", allowedAt: now, ackedAt: 0, lastWake: now, pairing: null, pairingId: null, declared: false };
this.store.grants.set(secret, grant);
// pairWithHub refuses redirects, has one 10 s deadline and reads 8 KiB at most (M2 to M4). The hub must say
// it keeps the code: on any other answer the grant ends, before the page hears back.
const answer = await pairWithHub(hub, { ticket, agent, app: { name: "Orders", origin: this.origin }, mcp_url: this.mcpUrl(secret), pairing_code: taken.pairing_code }, { fetch: this.send });
this.sweep();
const still = this.store.grants.get(secret) === grant && grant.state === "in_flight";
if (!answer.ok) {
if (still) this.forget(grant);
return { ok: false, error: answer.error };
}
// The acknowledgement moves the grant to handoff only if it is still in flight: a give-back, a Revoke or
// T_ack that came first wins. In a database: UPDATE ... SET state = 'handoff' WHERE state = 'in_flight'.
if (!still) return { ok: false, error: "pairing_ended" };
if (connect && held && this.store.grants.get(held.secret) === held) this.forget(held);
grant.state = "handoff";
// The binding, in the same step (APC 0.12, M10): in a database, the same UPDATE.
grant.pairingId = answer.pairing_id;
grant.declared = answer.binding !== null;
grant.ackedAt = this.now();
grant.pairing = { code: taken.pairing_code, expires_at: new Date(grant.ackedAt + PAIRING_CODE_TTL_MS).toISOString() };
if (answer.agent.name) grant.name = answer.agent.name.replace(/[\p{C}]/gu, "").slice(0, 60);
this.publish({ type: "agents" });
const pinned = target === undefined ? { ok: true } : this.pin(id, target);
this.store.kv.delete(targetKey);
return { ok: true, grant_id: id, status: "pending", pairing: grant.pairing, ...(pinned.ok ? {} : { pin_error: pinned.error }) };
}
/**
* A dock grant's state now (APC 0.10), from what is stored and the clock. In flight more than T_ack (30 s)
* after the Allow, or in handoff more than T_connect (10 minutes) after the acknowledgement, it has ended. A
* live grant sleeps T_idle after the person's last wake action (`dormant`: it returns no data until they are
* back), and ends after 30 days asleep. `dockGrantStateOf` picks the first state that applies.
*/
private stateOf(g: Grant): DockGrantState {
const now = this.now();
const asleep = g.state === "live" ? now - g.lastWake : 0;
return dockGrantStateOf({
ended: (g.state === "in_flight" && now - g.allowedAt >= T_ACK_MAX_MS) || (g.state === "handoff" && now - g.ackedAt >= T_CONNECT_MAX_MS) || asleep >= this.idleMs + LONG_DORMANCY_RECOMMENDED_MS,
in_flight: g.state === "in_flight",
handoff: g.state === "handoff",
dormant: asleep >= this.idleMs,
});
}
/** Dock grants whose time ran out go: an ended grant's URL answers 404. Run before every read of a dock grant. */
private sweep(): void {
for (const g of this.live()) if (g.path === "dock" && this.stateOf(g) === "ended") this.forget(g);
}
/**
* The hub's first `initialize` commits the connection: handoff to live, only if the grant is still there and in
* handoff (in a database: UPDATE ... SET state = 'live' WHERE state = 'handoff', and whether a row changed).
* False: it was not. If it throws, `initialize` answers HTTP 500 and the grant stays in handoff.
*/
private commitConnection(grant: Grant): boolean {
if (this.store.grants.get(grant.secret) !== grant || grant.state !== "handoff") return false;
grant.state = "live";
grant.pairing = null;
this.publish({ type: "agents" });
return true;
}
/** Cancel on the waiting card: a revoke, and only while the grant is in handoff. The check and the revoke are one step. */
cancel(grantId: unknown): { ok: boolean; error?: string } {
this.sweep();
const g = this.live().find((x) => x.id === grantId);
if (!g) return { ok: false, error: "unknown_grant" };
if (g.path !== "dock" || this.stateOf(g) !== "handoff") return { ok: false, error: "not_cancellable" };
this.revokeNow(g);
this.publish({ type: "agents" });
return { ok: true };
}
/** The page's heartbeat, while it is open: a wake action. Agent traffic never wakes a grant; only the person does. */
heartbeat(): { ok: boolean; idle_ms: number } {
this.sweep();
for (const g of this.live()) if (g.path === "dock" && g.state === "live") g.lastWake = this.now();
// The T_idle in effect, so the page beats at least every half of it (a MUST while the page is open).
return { ok: true, idle_ms: this.idleMs };
}
/** The hub gives a grant back (the person unpaired it in the dock): it ends, in any state. Not "revoked": its URL then answers 404. */
private givenBack(hash: string): void {
const grant = this.live().find((g) => g.path === "dock" && g.hash === hash);
if (!grant) return; // unknown, ended or revoked: nothing to do, and the hub is told nothing
this.forget(grant);
this.publish({ type: "agents" });
}
}- The hub is checked first, twice:
parseDockDroptakes the drag's hub only if it is exactly one of the origins on your allowlist, on the drop and again on the Allow (hub_not_allowedotherwise), and every hub call goes to the origin it returns. - No grant for that agent yet: on a first drop, the server calls
POST {hub}/apc/connect(requestConnect) and answersconnect_requested; the person approves in their dock, which opens yourdock_connectpage with#apc_connect=…(a missing/apc/connect, an HTTP 404, is a refusal: the drop never falls back to asking on the page). Ondock_connect, the server always answersconsent_requiredwith a nonce and a pairing code; the page asks the person and either shows the code in the consent prompt itself or holds it to show after the Allow in<apc-handoff>(as Pulse, Signals andorders-connect.tsdo); only the Allow that brings the newest nonce back makes a grant (a newer drop replaces the consent, and the older Allow getsconsent_expired). The grant is stored in flight and handed to the hub (POST {hub}/apc/pair, with the connect ticket and the code).pairWithHubrefuses redirects, ends at 10 s and reads 8 KiB at most; the grant is kept only if the hub acknowledges the code (pairing_code: "required"on a plain 200), and ends otherwise, before the server answers the page. No lock is held across that call; a second Allow meanwhile getspairing_in_progress. - Waiting for the dock (handoff): the acknowledgement moves the grant to handoff, if nothing ended it meanwhile. The person then allows it in their dock too, typing the code, and the hub's first
initializemakes the grant live. Until then the page shows the code with Cancel, which revokes the grant and works only before the dock connected: if the person's own dock never asks for that code, the agent was someone else's. - A grant already: the server asks the hub whether the pairing still stands (
confirmWithHub,POST {hub}/apc/confirm). Still pending: the page shows the same code, never a new one. Paired but not connected yet: it says so. Live: the drop pins it.not_paired, or the code's time is up: the grant ends and the person is asked again. - The person unpairs in the dock (or denies, types five wrong codes, or lets the request expire): the hub calls your
POST /apc/revokewith the grant's MCP URL, and the grant ends.handleDockGiveBackanswers the same 200 whatever it was sent.
Connect first (since 0.13). A drop with no grant behind it never pairs by itself: the server sends it to the hub's POST {hub}/apc/connect (requestConnect), the person approves it in their dock, and the dock opens your dock_connect page with an #apc_connect fragment. Orders serves that page itself (dockConnectPage, a top-level helper outside OrdersApp), and lists dock_connect in apc.json only while it offers Dock. A Connect for an agent that already has a grant says it replaces the current connection, and the old grant ends only once the hub acknowledges the new pairing. A missing /apc/connect (an HTTP 404) is a refusal, not a cue to ask on the drop page: the one-release rollback fallback for pre-0.13 hubs ended at 1.0.0.
Where the grant lands. Orders' store belongs to one person, so its consent nonce is keyed by the agent and the connect ticket alone (${agent} ${ticket} connect in dropOnce). On a store shared by more than one person — a real per-person database, one row or one tenant per account — that key knows nothing about the scope the grant is for, and a hole opens: Alice loads dock_connect, Bob signs in on the shared cookie in another tab, and Alice's Allow writes the grant in Bob's scope. There, key the consent by the immutable scope identity as well: the account, signed-out sandbox or device instance the grant is for, named by an identifier that does not change while it exists and by its owner, never a session id, an address, a slug or an "active scope" pointer. Record it with the nonce before the page shows the consent, and verify that scope and its owner again in the same step that writes the grant — a check at the top of the Allow handler is not enough, since M5 forbids holding a lock across the hub call. Where one person can hold more than one scope, it helps to say on the consent which scope will hold the grant. If you carry a pairing on to another of your own scopes (a native client, another window, another device), have the receiving scope show only to itself a fresh code made as a pairing code is made (newPairingCode, single-use, at most two minutes, refused after five wrong entries), bound to that scope and that one pairing, which the person enters on dock_connect: possession of the carried ticket is no proof of where the person is, and the code should not appear on dock_connect before it is entered. None of this is in the standard and the conformance suite does not check it, so your own tests do.
/**
* The page a dock opens at `dock_connect` (APC 0.13): 200 only, no redirect, no referrer, same-origin scripts only.
* Its head script runs first and moves the `#apc_connect` fragment into sessionStorage, then removes it from the
* URL; orders-connect.ts (built as `script`) validates it and asks the person on this page.
*/
export const CONNECT_HEAD = `(function () {
if (!location.hash.startsWith("#apc_connect=")) return;
var hash = location.hash;
history.replaceState(history.state, "", location.pathname + location.search);
try {
sessionStorage.removeItem("apc_connect");
var raw = hash.slice(13).replace(/-/g, "+").replace(/_/g, "/");
while (raw.length % 4) raw += "=";
var bytes = Uint8Array.from(atob(raw), function (c) { return c.charCodeAt(0); });
sessionStorage.setItem("apc_connect", new TextDecoder("utf-8", {fatal:true}).decode(bytes));
} catch (_) { /* The client reports an invalid or missing link without sending it. */ }
})();`;
const escapeHtml = (value: string) => value.replace(/&/g, "&").replace(/</g, "<").replace(/"/g, """);
function dockConnectPage(name: string, options: { session?: boolean; signedIn?: boolean; account?: string; script?: string } = {}): Response {
const script = options.script ?? "/assets/dock-connect.js";
if (!script.startsWith("/") || script.startsWith("//") || /[?#\\]/.test(script)) throw new Error("connect script must be a same-origin path");
return new Response(`<!doctype html><html lang="en"><head><meta charset="utf-8"><script>${CONNECT_HEAD}</script>
<meta name="referrer" content="no-referrer"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Connect ${escapeHtml(name)}</title><style>
body{font:16px system-ui,sans-serif;background:#f4f5f7;color:#20242b;margin:0;padding:24px}main{max-width:520px;margin:8vh auto;background:white;border:1px solid #d4d7dc;border-radius:16px;padding:28px}button,select{font:inherit;padding:10px 16px;margin:8px 8px 8px 0}button{cursor:pointer}button:focus-visible,a:focus-visible{outline:3px solid #3468d4}h1{font-size:24px}#account{overflow-wrap:anywhere}
</style></head><body><main data-app="${escapeHtml(name)}" data-session="${options.session === false ? "false" : "true"}" data-signed-in="${options.signedIn === false ? "false" : "true"}" data-account="${escapeHtml(options.account ?? "")}">
<h1>Connect ${escapeHtml(name)} to your dock</h1><p id="account"></p><p id="message" role="status">Preparing your connection…</p><div id="consent"></div><apc-handoff hidden></apc-handoff><p><a href="/">Open ${escapeHtml(name)}</a></p>
</main><script type="module" src="${escapeHtml(script)}"></script></body></html>`, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8", "cache-control": "no-store", "referrer-policy": "no-referrer",
"content-security-policy": "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
},
});
}The dock_connect page's client (orders-connect.ts, built as /assets/dock-connect.js), which reads the fragment cleared into sessionStorage by the <head> script, asks the person, posts to /api/connect/dock and shows <apc-handoff>:
/**
* Orders' Connect page client (APC 0.13): build this entry as the same-origin asset `connectScript` names
* (/assets/dock-connect.js by default). Self-contained: it needs only @tineira/apc-web. The page's head script
* (`dockConnectPage` in orders-app.ts) has already removed the `#apc_connect` fragment before this runs.
*/
import { clearApcConnect, defineHandoff, takeApcConnect, type ApcHandoffElement } from "@tineira/apc-web";
const EXPIRED = "This link expired. Drop the agent again, or use Connect an app in your dock.";
const SIGN_IN = "Sign in first, then return here to finish connecting.";
type Pairing = { code: string; expires_at: string };
type Answer = { ok?: boolean; error?: string; consent?: string; replaces?: boolean; grant_id?: string; pairing?: Pairing; pin_error?: string; unauthorized?: boolean };
export async function mountOrdersConnect(): Promise<void> {
const main = document.querySelector("main")!;
const message = document.querySelector<HTMLElement>("#message")!;
const account = document.querySelector<HTMLElement>("#account")!;
const card = document.querySelector<HTMLElement>("#consent")!;
const handoff = document.querySelector("apc-handoff") as ApcHandoffElement;
let poll: ReturnType<typeof setTimeout> | undefined;
const end = (text: string) => { message.textContent = text; card.replaceChildren(); clearApcConnect(); };
const post = async (path: string, body: unknown): Promise<Answer> => {
const response = await fetch(path, { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: JSON.stringify(body), referrerPolicy: "no-referrer" });
if (response.status === 401) return { unauthorized: true };
if (![200, 400].includes(response.status)) throw new Error(`Orders did not answer (${response.status}). Open Orders and try connecting again.`);
return response.json() as Promise<Answer>;
};
const refused = (error?: string) => error === "ticket_expired" || error === "dock_expired" || error === "consent_expired" ? EXPIRED
: error === "not_found" ? "Your dock did not accept the connection request and may be too old for Connect. Update your dock, then try connecting again."
: error === "ticket_not_for_pairing" ? "Drop the agent again, then confirm in your dock."
: `Could not connect: ${error ?? "Orders did not answer"}.`;
try {
// The stored handoff is validated before any request. Nothing is kept in localStorage.
const connect = takeApcConnect();
if (!connect) return end(EXPIRED);
const host = new URL(connect.hub).host;
if (main.dataset.signedIn === "false") {
account.textContent = main.dataset.account || "No account signed in.";
message.textContent = SIGN_IN;
return;
}
account.textContent = `Signed in: ${main.dataset.account}`;
const asked = await post("/api/connect/dock", connect);
if (asked.unauthorized) return void (message.textContent = SIGN_IN);
if (asked.error !== "consent_required" || !asked.consent) return end(refused(asked.error));
message.textContent = `Let your agent from the dock at ${host} read Orders?${asked.replaces ? " This replaces the current connection." : ""} After Allow, your dock will ask for a code.`;
const allow = Object.assign(document.createElement("button"), { type: "button", textContent: "Allow" });
const deny = Object.assign(document.createElement("button"), { type: "button", textContent: "Not now" });
deny.onclick = () => end("Connection cancelled.");
allow.onclick = () => {
allow.disabled = deny.disabled = true;
void (async () => {
const paired = await post("/api/connect/dock", { ...connect, consent: asked.consent });
if (paired.unauthorized) {
card.replaceChildren();
message.textContent = SIGN_IN;
return;
}
clearApcConnect();
if (!paired.ok || !paired.grant_id || !paired.pairing) return end(refused(paired.error));
const grant = paired.grant_id;
card.replaceChildren();
message.textContent = paired.pin_error ? `Connected, but not pinned (${paired.pin_error}). Drop the agent again after your dock connects.` : "Type this code only in your own dock.";
defineHandoff();
handoff.hidden = false;
handoff.host = host;
handoff.pairing = paired.pairing;
handoff.autoFocus = true;
handoff.addEventListener("apc-cancel", () => {
void post("/api/cancel", { grant_id: grant })
.then((r) => {
clearTimeout(poll);
if (r.ok) { handoff.hidden = true; end("Connection cancelled."); return; }
if (r.error === "not_cancellable") { handoff.hidden = true; end("The dock has connected already. To take its access back, revoke the agent."); return; }
message.textContent = refused(r.error);
})
.catch((e: unknown) => { message.textContent = String(e); });
});
// Follow Orders' agent list, so a code the dock took disappears without a second drop.
const follow = async () => {
const response = await fetch("/api/agents/list", { credentials: "same-origin", referrerPolicy: "no-referrer" });
if (!response.ok) return;
const row = ((await response.json()) as Array<{ id: string; waiting: string | null; pairing: Pairing | null }>).find((r) => r.id === grant);
handoff.pairing = row?.pairing ?? null;
if (!row?.waiting) { handoff.hidden = true; message.textContent = "The connection finished. Open Orders to check your agent."; return; }
poll = setTimeout(() => void follow().catch(() => {}), 1500);
};
poll = setTimeout(() => void follow().catch(() => {}), 1500);
})().catch((error: unknown) => end(String(error)));
};
card.append(deny, allow);
deny.focus();
} catch (error) { end(String(error)); }
}
if (typeof document !== "undefined") void mountOrdersConnect();What a dock grant answers follows its state, and dockGrantGate decides it before the MCP transport and the wrapper of step 8 (in mcp above): 404 in flight, the pairing error to a tool call in handoff, the app's data only once live. A grant with no acknowledgement 30 s after the Allow, or no initialize 10 minutes after the acknowledgement, ends (404). Orders also sleeps: 30 minutes after the person's last wake action (the page's heartbeat, a drop) a live grant goes dormant and returns no data, only idle, until they are back; agent traffic never wakes it.
The binding (since 0.12). Store with the grant, in the same statement that moves it to handoff, what the acknowledgement gave you: its pairing_id, whether it declared binding: "pairing_id" (pairWithHub returns binding), the agent and the hub. Pass them to dockGrantGate as binding: { pairing_id, agent, declared }: an initialize that names another pairing or agent then gets 404, and a declared grant commits only on its own. At an app implementing Dock or still serving any Dock grant, whether a grant is a Dock grant is your own record, never its URL: on every grant that is not a Dock grant, call directGrantGate(body) first and return its 404 when it gives one, even for a revoked grant. Apply this regardless of current pairability or the profiles advertised in apc.json. Only an app that does not implement Dock and holds no Dock grant owes no M12 refusal; it MAY refuse anyway. Read the _meta keys from the body you gate on, never from an SDK handler or a second parse; if you validate params._meta, accept apc.tineira.com/pairing_id and apc.tineira.com/agent. An app that allows more than one hub passes multiHub: true. When pairWithHub refuses an acknowledgement over its binding (hub_refused), end the grant as on any refusal: the hub's request for it then ends at the person's approval (pairing_ended) or after two minutes. In the conformance suite, an app that offers both profiles and claims 0.12 gives dock.lifecycle.directGrant(), a new Direct agent made its own way: the suite hands its URL to the stand-in hub's /apc/pair and checks it never goes live. The suite's stand-in hub sends the binding keys to every app, whatever standard it claims, so an app must keep unknown params._meta keys. See the binding.
When the page displays the pairing code is the app's choice, not a rule. The server's consent_required answer always carries pairing_code. An app may show the code inside the consent prompt itself (the page's choice), or hold it and show it only after the Allow inside <apc-handoff> (as Pulse, Signals and orders-connect.ts do); both shapes conform. What the spec requires is a new code with every consent, shown only on the owner's page, and that same code sent raw in pairing_code of /apc/pair. Here is Orders' waiting panel, <apc-handoff>'s counterpart (<apc-handoff> shows the code large with a copy button, the time left and Cancel), and the drop handler, which only confirms in the dock:
/**
* Dock: an agent the person allowed here waits until they type its pairing code in their dock. Its row shows
* the code while it is good, and Cancel, which takes the access back (only before the dock connected; after
* that it is Revoke in the bar): if their dock never asks for that code, the agent was someone else's. The row
* believes the server's expiry: past it, it shows no code and says the dock did not finish in time. Once the
* dock took the code, the row says it is connecting.
*/
const waiting = document.querySelector<HTMLElement>("#waiting") ?? document.body.appendChild(document.createElement("div"));
// Keep the latest drop's outcome outside the waiting rows: refresh and the countdown redraw those rows.
const dropMessage = document.createElement("p");
dropMessage.setAttribute("role", "status");
waiting.before(dropMessage);
/** A drop that paired but could not pin its target (the server's `pin_error`), by grant: its row says so. */
const pinErrors = new Map<string, string>();
let waitingRows: AgentRow[] = [];
function showWaiting(rows: AgentRow[] = waitingRows): void {
waitingRows = rows;
waiting.replaceChildren(
...rows.flatMap((a) => {
if (!a.waiting) return [];
const line = document.createElement("p");
const pinError = pinErrors.get(a.id);
const left = a.pairing ? Math.max(0, Math.ceil((Date.parse(a.pairing.expires_at) - Date.now()) / 1000)) : 0;
const says =
a.waiting === "connecting"
? "Your dock took the code and is connecting."
: left > 0
? `Waiting for your dock — code ${formatPairingCode(a.pairing!.code)} (${left} s left). If your dock doesn't ask for this code, the agent wasn't yours: Cancel.`
: "Your dock didn't finish in time. Drop the agent here again for a new code.";
line.textContent = `${says} ${pinError ? `Not pinned where you dropped it (${pinError}). ` : ""}`;
const cancel = Object.assign(document.createElement("button"), { type: "button", textContent: "Cancel" });
cancel.addEventListener("click", () => void post("/api/cancel", { grant_id: a.id }).then(refresh));
line.append(cancel);
return [line];
}),
);
}
// The countdown, and the code going away at its expiry.
setInterval(() => waitingRows.some((a) => a.waiting === "code") && showWaiting(), 1000);
onRefresh.push(showWaiting);
/**
* The server requests Connect in the dock for an unlinked agent; consent runs only on /connect/dock.
* Existing pairings confirm and pin. A refusal never opens a consent card on the drop page.
*/
async function dropFromDock(drag: AgentDrag & { hub: string; ticket: string }, target: FocusTarget): Promise<void> {
const answer = await post("/api/drop", { hub: drag.hub, agent: drag.agent, ticket: drag.ticket, target });
if (answer.ok === true && answer.status === "connect_requested") { dropMessage.textContent = "Confirm in your dock"; return; }
if (answer.ok !== true) {
const messages: Record<string, string> = {
not_found: "Your dock cannot take a connection request and may be too old for Connect. Update your dock, then drop the agent again.",
ticket_not_for_pairing: "Drop the agent again, then confirm in your dock.",
hub_refused: "Your dock refused the connection request. Check your dock, then try again.",
too_many_requests: "Your dock has too many pending requests. Answer one in your dock, then drop the agent again.",
hub_not_allowed: "Orders does not pair with that dock. Use a dock allowed by Orders.",
};
dropMessage.textContent = messages[String(answer.error)] ?? "Orders could not connect to your dock. Check your dock, then drop the agent again.";
return;
}
dropMessage.textContent = "";
// Paired, but the pin on the drop's target failed: the waiting row says so.
if (answer.ok === true && typeof answer.grant_id === "string" && typeof answer.pin_error === "string") pinErrors.set(answer.grant_id, answer.pin_error);
await refresh();
}
onDockDrop = (drag, target) => void dropFromDock(drag, target);Call void refresh(); once at the end of the page script after all elements and panels are wired:
void refresh();The hub reads your apc.json before it pairs: it must list "dock", name your origin, and cover the MCP URL you send. The reference dock at apc.tineira.com pairs with any app that passes its checks, as Not verified until it is on its list: the person sees a warning with your domain first (the hub's trust model), and your results reach the agent marked untrusted.
With both profiles, the same agent connected both ways is offered apc_link and shows once in your bar: the ApcLinks calls above (arrived on initialize, offer around every tool, registerApcLinkTool) are all it takes.
The minimum for the Dock profile#
What an app that offers only Dock must have, and nothing more. Orders has all of it (the regions above); the conformance suite checks each route.
| Route | Who calls it | What it does | Helper |
|---|---|---|---|
GET /.well-known/apc.json | the hub, before it pairs | lists "dock" and dock_connect while you can pair (M8, M13), names your origin, covers /{secret} MCP URLs (mcp.path, or an mcp.endpoints entry ending in /{secret} that lists dock) | apcManifest, apcJsonResponse |
the drop (/api/drop in Orders) | the person's page | checks the hub (parseDockDrop); if the agent has no grant yet (or an expired handoff grant was ended), calls POST {hub}/apc/connect (requestConnect; a missing /apc/connect is a refusal, never a drop-time consent); if the agent has a grant already, asks the hub (confirmWithHub) and pins | parseDockDrop, requestConnect, confirmWithHub |
GET {dock_connect} (/connect/dock in Orders) | the person's browser (opened by the dock with #apc_connect=…) | answers HTTP 200 (never 3xx, even when signed out) with Referrer-Policy: no-referrer and no third-party scripts; its synchronous <head> script moves #apc_connect into sessionStorage and clears the URL with history.replaceState, and the body's client script validates the stored handoff and asks consent | takeApcConnect, clearApcConnect |
the Connect consent and Allow (/api/connect/dock in Orders) | the dock_connect page | checks the hub (parseDockDrop), asks for consent with a pairing code (DockConsent), and on the Allow pairs with the connect ticket (pairWithHub), replacing any prior grant for that agent only once the hub acknowledges | parseDockDrop, DockConsent, pairWithHub |
POST {mcp.path}{secret} (and any other method) | the hub, for the agent | the grant's MCP endpoint: dockGrantGate answers by the grant's state first; the hub's first initialize makes it live; only then your wrapper and tools | dockGrantGate, registerApcTools |
Cancel (/api/cancel in Orders) | the person's page | revokes a grant still in handoff | |
the heartbeat (/api/heartbeat in Orders) | the person's page, every T_idle / 4 | the person is here: wakes a dormant grant. An app that never sleeps still serves it (it then changes nothing) | |
POST /apc/revoke | the hub, when the person unpairs | ends the grant whose MCP URL it names; the same 200 to anything | handleDockGiveBack |
In APC 1.0, the drop (/api/drop) and the Connect consent and Allow (/api/connect/dock, the Allow carrying the consent's nonce back) are separate owner POST routes; GET {dock_connect} answers HTTP 200 even when signed out (telling the person to sign in first) so it never redirects with the #apc_connect link. The four owner POST routes (the drop, the Allow, the heartbeat, Cancel) take the person's session and the M6 checks (refuseOwner above). What the app keeps per Dock grant: its state (in flight, handoff, live), when it was allowed, acknowledged and last woken, the pairing code and its expiry, and the hash of every revoked secret; all of it in storage that outlives the process, every time limit read through one clock (now). That is what lets the conformance adapter's dock.lifecycle move time, fail a write and restart the app (how to wire it).
A Dock grant on localhost#
Two ways to pair while you build, with no public hub:
- In your tests, with no network:
standInHubfrom@tineira/apc-conformanceis a hub in your own process. Give it anhttps:origin that is never resolved (https://dock.test), put that origin in your app'shubs, and give your apphub.fetchas thefetchit calls hubs with (pairWithHub(…, { fetch: hub.fetch }),this.sendin Orders).hub.ticket(agent)makes a drag's ticket,hub.decide(pairing.id, "approve", code)is the person typing the code in their dock, and itsinitializethen makes the grant live atpairing.mcp_url. Conformance shows it wired into Orders. - With a real dock, on your machine: run the reference dock from the repo (
pnpm install, thenpnpm devinapps/dock: it serveshttp://localhost:5200). Under its dev server it pairs with apps onhttp://localhost:<port>. Allow it in your app withparseDockDrop(body, { hubs: [], localDevHubs: ["http://localhost:5200"] }):localDevHubstakes loopback origins only, overhttp:, and is for development; leave it out in production. Then drag an agent from the local dock onto your local page. The command line checks that grant's URL with--profile dock --allow-http.
13. Test it#
Run the conformance suite against your app before you ship: see Conformance, whose adapter for Orders is orders-conformance.ts.
A complete Direct app with a bearer token#
Tickets, a help desk's tickets, is the smallest complete Direct app, in three files shown whole: nothing on them is left out, and every name is defined in them or exported by a package. Its agents authenticate with a bearer token on one MCP URL that every grant shares (the OAuth binding); swap the token for a secret URL and it is the Orders way. The conformance suite passes against it in process, and the command line's checks pass over HTTP, with a live token and a revoked one.
How the bearer binding answers, all done by the server below:
- The token names the grant.
newDirectGrant()gives a random grant id (g_…, stable for the grant's life, what pins and presence name) and a 128-bit secret, used as the token. The app keeps only the token's SHA-256 (secretHash), and finds the grant by it. - A token the app does not know: a plain 401 with
WWW-Authenticate: Bearer error="invalid_token"and noRevokedAnswer(unknownBearerResponse()), the bearer counterpart of a secret URL's 404. No token at all: the same 401 with the bare challengeWWW-Authenticate: Bearer(unknownBearerResponse({ missing: true })). Both are answered before the body is read. - A revoked or unknown token is told apart before anything else, a body over the cap included: the
RevokedAnswernever waits on the request. signedInhas no default. The person's routes need your sign-in; a copy of this file that leaves it out does not start.- A revoked token: 401 with the
RevokedAnswer({ error: "revoked", revoked_by, revoked_at, message }) and the sameWWW-Authenticate, to every method, before anything else:revokedResponse(host, revokedAt, { bearer: true }). A secret URL's revoked answer is the same body with 403 (revokedResponse(host, revokedAt)). - The person pastes two things into their agent: the MCP URL and the header
Authorization: Bearer <token>, shown once. A full OAuth 2.1 server issuing the tokens fits the same answers; this file mints them on the page to stay small.
The server:
/**
* Tickets: a complete Direct app in one file, whose agents authenticate with a bearer token on one shared MCP
* URL (APC 0.8, the OAuth binding). The guide at apc.tineira.com/docs/integrate shows it whole: every name it
* uses is defined here or exported by a package. Copy it, swap the tickets for your data and your sign-in for
* `signedIn`, and the conformance suite passes (tickets-conformance.ts; `apps/dock/test/docs-tickets.test.ts`
* runs it).
*
* Web standard Request and Response, so it runs on Node, Deno, Bun or a Cloudflare Worker. State is in memory,
* for one person: a real app keeps grants, pins and the view in its database, per person.
*/
import { parseParams, parseTarget, type ApcManifest, type FocusPayload, type FocusRow, type PresenceMessage, type ViewPayload } from "@tineira/apc-protocol";
import {
APC_INSTRUCTIONS,
InflightCalls,
MemoryWaitSlots,
apcJsonResponse,
apcManifest,
attachAttention,
attachThen,
attentionFor,
badContentLength,
initializeOf,
isUnread,
newDirectGrant,
presenceEvent,
registerApcTools,
revokedResponse,
revokedToolResult,
secretHash,
thenApplies,
toolError,
toolResult,
unknownBearerResponse,
type ToolResult,
} from "@tineira/apc-server";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { z } from "zod";
/** The app's data. A target carries only the kind and the id; the agent reads the rest through the tools. */
export interface Ticket {
id: string;
subject: string;
status: "open" | "closed";
}
export const TICKETS: Ticket[] = [
{ id: "t_101", subject: "Printer offline", status: "open" },
{ id: "t_102", subject: "VPN drops every hour", status: "open" },
{ id: "t_103", subject: "New laptop for Ana", status: "closed" },
];
/** One agent's access: a grant. The app keeps only a hash of its token, so the token is never stored. */
interface Grant {
/** What pins, presence and the agent bar name. Not secret. */
id: string;
/** SHA-256 of the bearer token: how a request finds its grant, and what a revoked grant leaves behind. */
tokenHash: string;
name: string;
/** The MCP client that connected with it (its `initialize`), or null before. */
client: string | null;
}
/** What the person's page hears on its event stream: presence, and "the agents changed". */
export type PageMessage = { type: "presence"; event: PresenceMessage } | { type: "agents" };
/** What the page shows of each agent. */
export interface AgentRow {
id: string;
name: string;
client: string | null;
pin: { label: string; seen: boolean } | null;
}
/** The most of an MCP request read: 1 MiB, far more than any call needs. Past it: HTTP 413. */
const MCP_BODY_MAX_BYTES = 1_048_576;
/** A request's body as text, read up to `cap` bytes; null past it, or when its `content-length` already says so. */
async function cappedText(request: Request, cap: number): Promise<string | null> {
if (badContentLength(request.headers, cap)) return null;
const reader = request.body?.getReader();
if (!reader) return "";
const decoder = new TextDecoder();
let text = "";
for (let size = 0; ; ) {
const { done, value } = await reader.read();
if (done) return text + decoder.decode();
size += value.byteLength;
if (size > cap) {
void reader.cancel().catch(() => {});
return null;
}
text += decoder.decode(value, { stream: true });
}
}
/** The token in `Authorization: Bearer <token>`, or null. */
function bearerToken(request: Request): string | null {
return request.headers.get("authorization")?.match(/^Bearer +([\w.~+/-]+=*)$/i)?.[1] ?? null;
}
export class TicketsApp {
readonly origin: string;
private readonly host: string;
/** Built once, at start: a mistake in it fails here, never as a 500 on every read of apc.json. */
private readonly manifest: ApcManifest;
private readonly signedIn: (request: Request) => boolean;
/** Live grants by token hash; revoked ones by token hash, with when. */
private readonly grants = new Map<string, Grant>();
private readonly revoked = new Map<string, string>();
/** One pin per grant, by grant id. */
private readonly pins = new Map<string, FocusRow>();
private view: { screen: string; params: Record<string, string | string[]>; selection: { kind: string; id: string } | null; updated_at: string } | null = null;
/** The person's open pages, each a stream of messages. An open stream is an open page. */
private readonly pages = new Set<(message: PageMessage) => void>();
/** One wait_for_focus per grant; every request runs in this one process, so the places live in memory. */
private readonly waitSlots = new MemoryWaitSlots();
/** MCP's notifications/cancelled comes in a POST of its own: the calls in flight, to find the one it names. */
private readonly calls = new InflightCalls();
/**
* `origin`: the public origin you configure, never one read from a request. `signedIn`: your own sign-in, required:
* whether a request carries the person's session. There is no default, so a copy of this file is never open to all.
*/
constructor(origin: string, options: { signedIn: (request: Request) => boolean }) {
this.origin = origin;
this.host = new URL(origin).host;
if (typeof options?.signedIn !== "function") throw new TypeError("TicketsApp: give signedIn, your own sign-in check");
this.signedIn = options.signedIn;
// One MCP URL, /mcp, shared by every grant: the bearer token names the grant. mcp.path is a prefix that starts and
// ends with /, and covers /mcp, the exact endpoint (APC 0.11) that readers from 0.11 on go by.
this.manifest = apcManifest({ name: "Tickets", origin, profiles: ["direct"], connect: "/", mcpPath: "/mcp/", endpoints: [{ path: "/mcp", profiles: ["direct"] }] });
}
async fetch(request: Request): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === "/.well-known/apc.json") return apcJsonResponse(this.manifest);
if (path === "/mcp") return this.mcp(request);
// The person's own routes: their session, and a change only from this origin's own pages.
if (!this.signedIn(request)) return Response.json({ error: "unauthorized" }, { status: 401 });
if (path === "/api/events") return this.events();
if (path === "/api/agents/list") return Response.json(this.agents());
if (request.method !== "POST") return Response.json({ error: "not_found" }, { status: 404 });
const origin = request.headers.get("origin");
if (origin !== null && origin !== this.origin) return Response.json({ error: "origin_not_allowed" }, { status: 403 });
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
if (path === "/api/view") return Response.json(this.reportView(body));
if (path === "/api/agents") return Response.json(await this.addAgent());
const agent = path.match(/^\/api\/agents\/(g_[0-9a-f]{8})\/(pin|unpin|revoke)$/);
if (agent?.[2] === "pin") return Response.json(this.pin(agent[1]!, body?.target));
if (agent?.[2] === "unpin") return Response.json(this.unpin(agent[1]!));
if (agent?.[2] === "revoke") return Response.json(this.revoke(agent[1]!));
return Response.json({ error: "not_found" }, { status: 404 });
}
/**
* The person makes an agent. It gets its own grant and token; the page shows the token once, to paste into the
* agent with the MCP URL (most clients take a custom `Authorization` header). The grant id is random, never
* derived from the token, and stays the same for the grant's life.
*/
async addAgent(): Promise<{ ok: true; id: string; url: string; token: string }> {
const { id, secret: token } = newDirectGrant();
const tokenHash = await secretHash(token);
this.grants.set(tokenHash, { id, tokenHash, name: "New agent", client: null });
this.publish({ type: "agents" });
return { ok: true, id, url: `${this.origin}/mcp`, token };
}
/** Revoke: at once, calling nobody. The token now answers `revoked` (401) to every method; its hash is all that is kept. */
revoke(grantId: string): { ok: boolean } {
const grant = [...this.grants.values()].find((g) => g.id === grantId);
if (!grant) return { ok: false };
this.revoked.set(grant.tokenHash, new Date().toISOString());
this.grants.delete(grant.tokenHash);
this.pins.delete(grant.id);
this.waitSlots.forget(grant.id);
this.publish({ type: "agents" });
return { ok: true };
}
/** The page reports the screen as identifiers: a screen name, key-only params, at most one selected ticket. */
reportView(raw: Record<string, unknown> | null): { ok: boolean } {
const screen = typeof raw?.screen === "string" && /^[a-z][a-z0-9_]{0,31}$/.test(raw.screen) ? raw.screen : null;
const params = parseParams(raw?.params ?? {});
const s = raw?.selection as { kind?: unknown; id?: unknown } | null | undefined;
const selection = s && s.kind === "ticket" && typeof s.id === "string" && TICKETS.some((t) => t.id === s.id) ? { kind: "ticket", id: s.id } : null;
if (!screen || !params) return { ok: false };
this.view = { screen, params, selection, updated_at: new Date().toISOString() };
return { ok: true };
}
/** The person drops an agent's mark on a ticket. One pin per grant: a new one replaces it, unread. */
pin(grantId: string, raw: unknown): { ok: boolean; error?: string } {
if (![...this.grants.values()].some((g) => g.id === grantId)) return { ok: false, error: "unknown_grant" };
const target = raw && typeof raw === "object" ? parseTarget(raw) : null;
if (!target || target.kind !== "ticket" || !TICKETS.some((t) => t.id === target.id)) return { ok: false, error: "invalid_target" };
this.pins.set(grantId, { ...target, grant_id: grantId, pinned_at: new Date().toISOString(), seen_at: null });
this.publish({ type: "agents" });
return { ok: true };
}
unpin(grantId: string): { ok: boolean } {
const had = this.pins.delete(grantId);
this.publish({ type: "agents" });
return { ok: had };
}
/** The agents, for the page's agent bar. */
agents(): AgentRow[] {
return [...this.grants.values()].map((g) => {
const pin = this.pins.get(g.id);
return { id: g.id, name: g.name, client: g.client, pin: pin ? { label: `ticket ${pin.id}`, seen: !isUnread(pin) } : null };
});
}
/** The person's page: a stream of messages. It is open while the stream is. */
events(): Response {
const encoder = new TextEncoder();
let send: ((message: PageMessage) => void) | null = null;
const stream = new ReadableStream<Uint8Array>({
start: (controller) => {
send = (message) => controller.enqueue(encoder.encode(`data: ${JSON.stringify(message)}\n\n`));
this.pages.add(send);
},
cancel: () => {
if (send) this.pages.delete(send);
},
});
return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
}
/** To every open page. A page whose stream closed is dropped: it never fails the tool call that published. */
private publish(message: PageMessage): void {
for (const send of this.pages) {
try {
send(message);
} catch {
this.pages.delete(send);
}
}
}
private viewPayload(): ViewPayload | null {
if (!this.view) return null;
const age = Math.max(0, Math.round((Date.now() - Date.parse(this.view.updated_at)) / 1000));
return { ...this.view, app_url: `${this.origin}/${this.view.screen}`, age_seconds: age, stale: age > 300, next: this.view.selection ? "get_ticket" : "list_tickets" };
}
/** What the agent receives for its pin: the target, where it is, and the exact call that reads it. */
private focusPayload(grantId: string): FocusPayload | null {
const pin = this.pins.get(grantId);
if (!pin?.id) return null;
return { kind: pin.kind, id: pin.id, part: pin.part, params: pin.params, app_url: `${this.origin}/tickets/${pin.id}`, pinned_at: pin.pinned_at, next: "get_ticket", next_args: { id: pin.id } };
}
/** What a token that holds no live grant answers: the `RevokedAnswer` (401) if it was revoked, else a plain 401. */
private notLive(tokenHash: string): Response {
const revokedAt = this.revoked.get(tokenHash);
return revokedAt ? revokedResponse(this.host, revokedAt, { bearer: true }) : unknownBearerResponse();
}
/**
* The MCP endpoint, one URL for every grant. No token: a plain 401 with the bare `Bearer` challenge. A token the
* app does not know: a plain 401 (no `RevokedAnswer`). A revoked token: 401 with the `RevokedAnswer` and
* `WWW-Authenticate: Bearer error="invalid_token"`, to every request, before anything else (its body is not even read).
*/
private async mcp(request: Request): Promise<Response> {
const token = bearerToken(request);
if (!token) return unknownBearerResponse({ missing: true });
const tokenHash = await secretHash(token);
if (!this.grants.has(tokenHash)) return this.notLive(tokenHash);
const text = request.method === "POST" ? await cappedText(request, MCP_BODY_MAX_BYTES).catch(() => null) : "";
if (text === null) return Response.json({ error: "too_large" }, { status: 413 });
// Read again after the body: a revoke while it arrived is answered as revoked.
const grant = this.grants.get(tokenHash);
if (!grant) return this.notLive(tokenHash);
if (request.method !== "POST") return new Response(null, { status: 405, headers: { allow: "POST" } });
let body: unknown = null;
try {
body = text ? JSON.parse(text) : null;
} catch {
// not JSON: the transport answers the parse error
}
// A cancel in this POST ends the call it names; the calls this POST carries can be cancelled the same way.
this.calls.cancel(grant.id, body);
const inflight = this.calls.track(grant.id, body);
const arriving = initializeOf(body);
if (arriving) {
grant.client = arriving.name;
if (grant.name === "New agent" && arriving.name) grant.name = arriving.name;
this.publish({ type: "agents" });
}
const server = new McpServer({ name: "tickets", version: "1.0.0" }, { instructions: `${APC_INSTRUCTIONS} Tickets lists a help desk's tickets.` });
// The wrapper first: registerApcTools registers through server.registerTool, so the two core tools get it too.
this.aroundEveryTool(server, grant);
registerApcTools(server, {
readView: async () => this.viewPayload(),
readFocus: async () => this.focusPayload(grant.id),
focusUnread: async () => isUnread(this.pins.get(grant.id) ?? null),
// Seen once delivered: the exact pin the result carried, never a newer one dropped since.
markSeen: async (pinnedAt) => {
const pin = this.pins.get(grant.id);
if (pin?.pinned_at === pinnedAt) pin.seen_at = new Date().toISOString();
this.publish({ type: "agents" });
},
// A wait ends when the person has no page open, and when its grant is revoked meanwhile.
pageOpen: async () => this.grants.get(tokenHash) === grant && this.pages.size > 0,
waitSlot: this.waitSlots.for(grant.id),
// A wait's open and closed (APC 0.11), so the page knows the agent is listening.
waitPresence: { grantId: grant.id, publish: (event) => this.publish({ type: "presence", event }) },
signal: AbortSignal.any([request.signal, inflight.signal]),
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
pollMs: 500,
});
server.registerTool(
"list_tickets",
{ title: "List the tickets", description: "Every ticket: id, subject and status.", inputSchema: {}, annotations: { readOnlyHint: true } },
async () => toolResult({ tickets: TICKETS }),
);
server.registerTool(
"get_ticket",
{ title: "Read one ticket", description: "One ticket by id (t_NNN). Usually called with the next_args of a focus.", inputSchema: { id: z.string() }, annotations: { readOnlyHint: true } },
async ({ id }) => {
const ticket = TICKETS.find((t) => t.id === id);
return ticket ? toolResult({ ticket }) : toolError("unknown_ticket", `No ticket ${id}.`);
},
);
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
await server.connect(transport);
// The transport wants a client that takes both JSON and an event stream; some clients send less.
const headers = new Headers(request.headers);
headers.set("accept", "application/json, text/event-stream");
try {
return await transport.handleRequest(new Request(request.url, { method: "POST", headers, body: text, signal: request.signal }));
} finally {
inflight.done();
}
}
/**
* Around every tool: the grant is checked before and after it runs (revoked meanwhile ends the call `revoked`),
* `attention` rides while the pin is unread, presence goes to the person's pages, and `then` rides while a page is
* open and the grant was pinned in the last 30 minutes, but never on a wait that came back empty.
*/
private aroundEveryTool(server: McpServer, grant: Grant): void {
const register = server.registerTool.bind(server) as (...args: unknown[]) => unknown;
const cut = (): ToolResult | null => {
if (this.grants.get(grant.tokenHash) === grant) return null;
const revokedAt = this.revoked.get(grant.tokenHash);
return revokedAt ? revokedToolResult(this.host, revokedAt) : toolError("unknown_grant", "This grant no longer exists.");
};
(server as unknown as { registerTool: (...args: unknown[]) => unknown }).registerTool = (name: unknown, config: unknown, run: unknown) =>
register(name, config, async (args: Record<string, unknown>, extra: unknown): Promise<ToolResult> => {
const tool = String(name);
const before = cut();
if (before) return before;
let result = await (run as (args: unknown, extra: unknown) => Promise<ToolResult>)(args, extra);
const after = cut();
if (after) return after;
const focus = this.focusPayload(grant.id);
if (focus && isUnread(this.pins.get(grant.id) ?? null)) result = attachAttention(result, attentionFor(focus));
if (!result.isError) {
const targets = tool === "get_ticket" && typeof args.id === "string" ? [{ kind: "ticket", id: args.id }] : [];
this.publish({ type: "presence", event: presenceEvent({ grantId: grant.id, tool, kind: "read", targets }) });
}
const emptyWait = tool === "wait_for_focus" && result.structuredContent?.focus == null;
return attachThen(result, !emptyWait && thenApplies(this.pages.size > 0, this.pins.get(grant.id)?.pinned_at));
});
}
}The page (bundle it with any bundler):
/**
* Tickets' page: the browser side of tickets-app.ts, with @tineira/apc-web, in plain DOM. Bundle it with any
* bundler into the page that lists the tickets; it talks to the server's /api/* routes.
*/
import { focusAttrs } from "@tineira/apc-protocol";
import { createViewReporter, defineAgentBar, enablePinning, flashTargets, initials, type ApcAgentsElement } from "@tineira/apc-web";
// Types only: the page never bundles the server module.
import type { AgentRow, Ticket } from "./tickets-app.ts";
const post = async (path: string, body: unknown = {}): Promise<Record<string, unknown>> =>
(await fetch(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })).json();
/** The tickets, each a row the person can point at: data-focus, made by focusAttrs. Your page draws your own data. */
const tickets: Ticket[] = [
{ id: "t_101", subject: "Printer offline", status: "open" },
{ id: "t_102", subject: "VPN drops every hour", status: "open" },
{ id: "t_103", subject: "New laptop for Ana", status: "closed" },
];
const table = document.body.appendChild(document.createElement("table"));
for (const ticket of tickets) {
const row = table.appendChild(document.createElement("tr"));
for (const [name, value] of Object.entries(focusAttrs({ kind: "ticket", id: ticket.id }))) row.setAttribute(name, value);
row.append(Object.assign(document.createElement("td"), { textContent: ticket.subject }), Object.assign(document.createElement("td"), { textContent: ticket.status }));
}
/** The screen as identifiers, sent when it changes. */
const reportView = createViewReporter((view) => void post("/api/view", view));
reportView({ screen: "tickets", params: {}, selection: null });
/** The agent bar: each agent's mark (drag it onto a ticket), its pin, × to unpin, ⊘ to revoke. It needs no paths on a Direct-only app. */
defineAgentBar();
const bar = document.body.appendChild(document.createElement("apc-agents")) as ApcAgentsElement;
bar.dockHint = null; // Direct only: no "get a dock" hint
const marks = new Map<string, string>();
async function refresh(): Promise<void> {
const rows = (await (await fetch("/api/agents/list")).json()) as AgentRow[];
marks.clear();
for (const row of rows) marks.set(row.id, initials(row.name, new Set(marks.values())));
bar.agents = rows.map((a) => ({ id: a.id, name: a.name, state: "idle", pin: a.pin ? { ...a.pin, here: true } : null }));
}
bar.addEventListener("apc-revoke", (e) => void post(`/api/agents/${(e as CustomEvent<{ id: string }>).detail.id}/revoke`).then(refresh));
bar.addEventListener("apc-unpin", (e) => void post(`/api/agents/${(e as CustomEvent<{ id: string }>).detail.id}/unpin`).then(refresh));
/** A new agent: its MCP URL and its token, shown once, for the person to paste into their agent. */
const add = document.body.appendChild(Object.assign(document.createElement("button"), { type: "button", textContent: "Connect an agent" }));
const secret = document.body.appendChild(document.createElement("pre"));
add.addEventListener("click", async () => {
const made = await post("/api/agents");
secret.textContent = `MCP URL: ${String(made.url)}\nHeader: Authorization: Bearer ${String(made.token)}\n(shown once)`;
await refresh();
});
/** The page's stream: while it is open the page is open (for `then` and wait_for_focus); it carries presence and changes. */
const events = new EventSource("/api/events");
events.onmessage = (message) => {
const data = JSON.parse(message.data as string) as { type: string; event?: Parameters<typeof flashTargets>[0] };
if (data.type === "presence" && data.event) flashTargets(data.event, marks.get(data.event.grant_id) ?? "?");
else void refresh();
};
/** Pinning: a mark dragged (or on a phone tapped, then a ticket tapped) onto a row pins that agent there. */
enablePinning({ onPin: (grantId, target) => void post(`/api/agents/${grantId}/pin`, { target }).then(refresh) });
void refresh();The conformance test: connect gives each agent's token in headers, and page.mobile models the page on a phone with @tineira/apc-web's own pieces.
/**
* Tickets against the conformance suite, in process: the adapter for tickets-app.ts. The app's `fetch` is called
* directly, and the person's page is the app's own event stream. Run it under `node --test`
* (`for (const c of apcConformance(ticketsUnderTest().adapter)) test(c.name, c.run)`) or with `checkTickets()`.
*/
import { apcConformance, runConformance, type ApcAppAdapter } from "@tineira/apc-conformance";
import type { FocusTarget, PresenceMessage } from "@tineira/apc-protocol";
import { barCanCollapse, createTapPin, type BarAgent } from "@tineira/apc-web";
import { TicketsApp } from "./tickets-app.ts";
const ORIGIN = "https://tickets.test";
/** The person's session: here a fixed cookie; in your app, your own sign-in. */
const SESSION = { cookie: "tickets_session=owner" };
export function ticketsUnderTest(): { app: TicketsApp; adapter: ApcAppAdapter } {
const app = new TicketsApp(ORIGIN, { signedIn: (request) => request.headers.get("cookie") === SESSION.cookie });
/** A request of the person's page: their session, JSON, and the page's own Origin. */
const call = async (path: string, body: unknown = {}) =>
(await app.fetch(new Request(`${ORIGIN}${path}`, { method: "POST", headers: { ...SESSION, "content-type": "application/json", origin: ORIGIN }, body: JSON.stringify(body) }))).json() as Promise<Record<string, unknown>>;
/** The person's page: open while its event stream is, which also carries presence. */
let page: { reader: ReadableStreamDefaultReader<Uint8Array>; done: Promise<void> } | null = null;
const presence: PresenceMessage[] = [];
async function setOpen(open: boolean): Promise<void> {
if (open && !page) {
const reader = (await app.fetch(new Request(`${ORIGIN}/api/events`, { headers: SESSION }))).body!.getReader();
const decoder = new TextDecoder();
const done = (async () => {
let buffer = "";
for (;;) {
const { value, done } = await reader.read().catch(() => ({ value: undefined, done: true }));
if (done) return;
buffer += decoder.decode(value, { stream: true });
let end: number;
while ((end = buffer.indexOf("\n\n")) >= 0) {
const message = JSON.parse(buffer.slice(6, end)) as { type: string; event?: PresenceMessage };
buffer = buffer.slice(end + 2);
if (message.type === "presence" && message.event) presence.push(message.event);
}
}
})();
page = { reader, done };
} else if (!open && page) {
await page.reader.cancel();
await page.done;
page = null;
}
}
const targets: [FocusTarget, FocusTarget] = [
{ kind: "ticket", id: "t_101", part: null, params: null },
{ kind: "ticket", id: "t_102", part: null, params: null },
];
const adapter: ApcAppAdapter = {
name: "Tickets",
profile: "direct",
fetch: (request) => app.fetch(request),
// The person makes an agent on the page: the shared MCP URL, and the grant's token in a header.
connect: async () => {
const made = await call("/api/agents");
return { grantId: made.id as string, mcpUrl: made.url as string, headers: { authorization: `Bearer ${made.token as string}` } };
},
targets,
probe: { tool: "list_tickets", args: {} },
page: {
setOpen,
showView: async () => void (await call("/api/view", { screen: "tickets", params: {}, selection: { kind: "ticket", id: "t_101" } })),
pin: async (grantId, target) => (await call(`/api/agents/${grantId}/pin`, { target })).ok === true,
takePresence: () => presence.splice(0),
revoke: async (grantId) => (await call(`/api/agents/${grantId}/revoke`)).ok === true,
// The page on a phone (APC 0.6), modelled with @tineira/apc-web's own pieces: the agent bar's collapse rule
// and the tap-to-pin controller enablePinning runs. A browser with touch emulation is the real check.
mobile: {
async agentBar() {
const bar: BarAgent[] = app.agents().map((a) => ({ id: a.id, name: a.name, state: "idle" }));
return { visible: bar.map((a) => a.id), collapsible: barCanCollapse(bar, true) };
},
async pinByTouch(grantId, target) {
const pins: Array<Promise<Record<string, unknown>>> = [];
const tap = createTapPin({ onPin: (id, t) => void pins.push(call(`/api/agents/${id}/pin`, { target: t })) });
tap.toggle(grantId);
return tap.tap({ element: {} as Element, target }) === "pinned" && (await pins[0]!).ok === true;
},
unpinByTouch: async (grantId) => (await call(`/api/agents/${grantId}/unpin`)).ok === true,
},
},
};
return { app, adapter };
}
/** Every check, with a line per check: what a CI job or a script prints. */
export async function checkTickets(): Promise<boolean> {
const report = await runConformance(ticketsUnderTest().adapter);
for (const r of report.results) console.log(`${r.ok ? "PASS" : "FAIL"} ${r.name}${r.error ? `: ${r.error}` : ""}`);
return report.failed === 0;
}
/** For a test runner: one test per check. */
export const ticketsChecks = () => apcConformance(ticketsUnderTest().adapter);Over HTTP, with the app running: make two agents, revoke one in the page, then run the command line once with the live one and the revoked one (see Conformance):
APC_TOKEN=… APC_REVOKED_TOKEN=… npx @tineira/apc-conformance@1.1.1 https://tickets.example --grant https://tickets.example/mcp --bearer-env APC_TOKEN --revoked https://tickets.example/mcp --revoked-bearer-env APC_REVOKED_TOKEN
Localize the page#
@tineira/apc-web draws words: the agent bar, the pin badge, the Direct agent list and the notes enablePinning shows. An app in another language passes every one of them, without forking the package. Each component takes one strings object (<apc-agents>, <apc-pin> and <apc-direct-agents> as a property; enablePinning({ strings })), typed by BarStrings, PinStrings, DirectStrings and PinningStrings. The keys you leave out keep their English default, exactly what the package always showed, so an app that passes nothing changes nothing.
/**
* Another language: every string the package draws is a key you can pass, tooltips and `aria-label`s included.
* A key you leave out stays English. A name, a count or a label is a function, so the word order and the
* plural forms are yours. Here, Spanish; the pin badge `<apc-pin>` takes `strings` the same way.
*/
bar.strings = {
toolbar: "Agentes",
markTitle: (name, connected) => `${name}${connected ? "" : " (aún sin conectar)"}. Arrástralo sobre cualquier cosa para apuntarlo.`,
revokeConfirm: "¿Revocar?",
revokeAria: (name) => `Revocar a ${name}`,
readingCount: (count) => (count === 1 ? "1 leyendo" : `${count} leyendo`),
nobodyReadingShort: "ningún agente leyendo",
reading: (names) => `Leyendo: ${names.join(", ")}`,
dockHint: "Usa este agente en todas tus apps con el dock",
dockHintDismiss: "Cerrar este aviso",
};
// An app that offers Direct only (no dock) turns the hint off: bar.dockHint = null, or dock-hint="off" on the element.
direct.strings = {
connectAgent: "Conectar un agente",
addAnother: "Agregar otro agente",
prompt: (url, appName) => `Conecta este servidor MCP remoto, llamado "${appName}". URL: ${url}. Usa Streamable HTTP y no necesita OAuth ni clave: el acceso está en la URL.`,
};
/** What `enablePinning` says (the tap-to-pin note, refused drops); pass it as `strings` there. `directOnlyNote` replaces the protocol's English note. */
export const pinningStrings: Partial<PinningStrings> = {
tapPrompt: (name) => `Toca lo que quieres que ${name} mire.`,
cancel: "Cancelar",
directOnlyNote: (appName) => `${appName} conecta agentes directamente, no con un dock.`,
};
/** A time in your own labels (a pin's "read at…") follows the page's language (`<html lang>`), not the machine's. */
export const readAt = (when: Date): string => formatPageTime(when, { timeStyle: "short" });- Tooltips and
aria-labels are strings too, not only the visible text: the mark's title, the pin dot, ×, ⊘ and its "Revoke?" confirmation, Unlink, the collapse and dismiss buttons. - Names, counts and labels are functions, so no sentence is built from English fragments:
reading(names)andreadingCount(count)(plurals are yours),joinPins(labels)for a linked agent's two pins ("A and B"),status(agent)andprompt(url, appName)for the Direct list. - The dock hint can be translated (
dockHint, orbar.dockHint = { text, url }) or turned off (bar.dockHint = null, ordock-hint="off"). An app that offers Direct only turns it off. - A dock agent dropped on a Direct-only app is answered with the protocol's
directOnlyNote(name). PassdirectOnlyNoteandcouldNotCheckNoteinPinningStringsfor your own words, or handleonDockUnsupportedyourself. - Dates and times you show (a pin's "read at …") follow the page:
formatPageTime(date)uses<html lang>, orlocalewhen you name one, and never the operating system's.pageLocale()gives the tag. The bar itself shows no date. - Left as they are: the symbols (×, ⊘, ‹, !, ✓), and what you pass in (agent names, pin labels, warnings, URLs).
Localizing changes no protocol text, the tools or conformance: Conformance passes in any language.
Operating APC on stateless hosts#
The Orders sample keeps its state in one process, as a Durable Object does. Many apps have no such process: a function per request (Vercel, say) and a Postgres database (Supabase, say). Two apps built that way, Autio (its dealer and personal MCPs) and Surplus, rewrote the server side and met the same traps. This section is what they learned. It is guidance, not rules: the spec says what must hold, and this says what it took to hold on a host with no memory between requests. The ids in parentheses are the issues where each point was found.
A wait is a row#
Keep one row per grant: the holder's token, when it claimed, when it expires. Autio calls the table apc_wait, Surplus ledger.agent_wait.
- Claim under a lock. The claim takes a per-grant advisory lock (
pg_advisory_xact_lock), deletes the grant's expired rows and writes a fresh holder token. The newest wait takes the slot over (Autio TIN-807). A claim made less than 2 s after the last is refused withretry_after_s, the real time left, so two waits fired together do not take the slot from each other in a loop (Autio TIN-844). Surplus also sets alock_timeoutof 2.5 s on the claim, so a stuck lock ends the call and not the pool (Surplus TIN-846). - The old wait finds out by itself. It keeps polling until its own timeout. Each poll asks whether its token still holds the slot, and a wait that lost it answers no focus and marks nothing. Giving the slot up answers whether it was still held, and only a wait that held it delivers (Autio TIN-807, Surplus TIN-846).
- Poll every 2 s, each poll in its own short transaction. Nothing is held across the sleep: no lock, no open transaction. Each poll checks that the grant is still live, so a revoke ends the wait at its next poll (Surplus TIN-847).
- Default 45 s, and set the route's time limit above the longest wait. Autio accepts 1 to 60 s with a route limit of 120 s; Surplus accepts 1 to 50 s with 60 s (Autio TIN-822).
- Tell the agent what happened. At the timeout:
timed_out: trueandpage_open: true. A wait taken over:focus: nulland a note. A page that closed:page_open: false. When the wait cannot run at all, answer that last shape with a note, never a tool error (Autio TIN-797).
Cancellation arrives in another request#
A stateless server is new for every POST. MCP's notifications/cancelled comes in a POST of its own, to a server that never saw the call, so the SDK cannot deliver it. The database has to.
- Key the wait by (grant, request key). The grant comes from the credential, never from the body. The request key is the JSON-RPC id of the
wait_for_focuscall, normalized the same way on the claim and on the cancel:n:<integer>for a safe integer,s:<string>for a well-formed string of 1 to 128 characters, and nothing else is a key.7and"7"are two keys, and id0is valid (request-key.tsin both apps, Autio TIN-844). - A cancel deletes the slot that holds that key. A cancel from another grant touches nothing. Answer the notification
202with an empty body, after a bounded transaction; a cancel that fails is logged by code and still answers202(Autio TIN-844, Surplus TIN-846). - Plant an early-cancel marker for a cancel that overtook its call. Two requests are in flight, and the cancel can win. When no slot matches, store the key in a marker for the grant: at most 8 keys, 10 s. A claim whose key is in the marker consumes it and answers
cancelled. Both run under the same per-grant lock, so they always see each other's rows. Without a marker that cancel is lost, and the wait that follows runs for a client that has gone (Autio TIN-844, Surplus TIN-846). - Only waits are keyed. A cancel for any other call, or one that arrives after the final answer, finds nothing to stop. The standard allows that window.
- Vercel:
request.signalis off unless you turn it on. A client hang-up firesrequest.signalonly for a function withsupportsCancellation(invercel.json, per route file), and Vercel then ends that function, except for work held bywaitUntil. Surplus turns it on for exactly its MCP routes and its RESTwait_for_focusroute, and splits that route out of its catch-all so that no REST write is on a cancellable function (Surplus TIN-866). - Hold the work before the handler starts. Register a promise with
after()(that iswaitUntil) first, and release it in afinallyonce the handler settled. A tool's write then finishes even when the client is gone. If the hold cannot be registered, fail closed: answer 503 and run nothing. Hold deferred work (audit rows, presence) the same way, even when it is registered after the client left. Read the signal only where stopping is safe, the wait loop and the delivery step, never in a write (Surplus TIN-866).
Trim, never fail#
One bad item must not fail the whole view read.
- Check each item on its own. The view's selection, a filter's id, the pin: each goes through its own check, and an item whose check throws is hidden, never shown unchecked. The rest of the state still answers. Surplus does this in TypeScript (
guardedAccess); Autio does it in SQL (apc_record_check_or_hidden), where an unreadable pin reads as no pin and a filter that cannot be checked is dropped (Autio TIN-797). - Hide only what is a defect, and fail on the rest. Autio hides on a closed list of SQLSTATEs (42703 undefined column, 42P01 undefined table, 42883 undefined function, 22P02 invalid text) and logs a warning with the code and the kind, nothing else. Anything else is raised again: an auth failure (42501) must still fail the whole read closed. Hiding is the narrowest answer, so nothing becomes visible that the check would not allow (Autio TIN-797).
- An applied migration does not prove every branch. PL/pgSQL resolves a query only when its branch runs. Autio shipped a check whose personal
carbranch read a column that does not exist. The migration applied cleanly; the first view with a car pin then failed the whole state, and both core tools answered unavailable (Autio TIN-797, TIN-794). Call each branch of a check function once in a test: one call per target kind. - Say why a read is empty. A null view or focus carries a
note. Log the cause as a code (rpc_<code>,timeout,throw), never an id or a value (Autio TIN-797).
Mark seen only after delivery#
A pin is lost if you mark it seen on a read the client never receives.
- No read marks. Not
get_current_view's read, not a wait's poll, not the envelope's read: a read can time out or be thrown away. - Mark once the body is final. Build the whole answer first, with
attentionandthen. Then mark that exact pin by thepinned_atthe database sent, with all its microseconds, so a newer pin is never marked by mistake. In a wait, mark after the slot is cleared. Skip the mark when the request was aborted. If the mark fails or times out, return the body anyway: a pin delivered twice is safe, a pin lost is not (Autio TIN-674, Surplus TIN-846).
Revoke, and the order of locks#
- Lock the grant row first, then its children. A transaction that touches a grant and the rows that point to it (tokens, codes, pin, wait rows) locks the grant row first, then the children in one fixed order (Surplus: codes, links, pin, wait). A revoke deletes the grant's pin and wait rows in its own transaction, and a pin re-checks that the grant is live under the grant's lock, so a pin can never land after a revoke (Surplus TIN-847, Autio
apc_pinandapc_grant_revoked_cleanup). FOR NO KEY UPDATE, notFOR UPDATE, for a grant writer. A child insert (a token, a wait claim) takes aKEY SHARElock on its grant through the foreign key.FOR UPDATEblocks it;FOR NO KEY UPDATEdoes not, and still keeps grant writers in line. Nobody changes a grant's id, so it is enough. The owner's pin takesFOR SHARE, so a pin and a revoke run one after the other: the pin commits first and the revoke deletes it, or the pin fails (Surplus TIN-847).- A job that touches several grants locks them in one order. Surplus's page heartbeat locks the owner's dock grants with
order by id for no key updatebefore it writes any of them, as revoke-all does. Two transactions that take the same rows in different orders can deadlock. The heartbeat also retries once on a deadlock (40P01) or a serialization loss (40001), logs the SQLSTATE if that fails too, and never fails the page for it (Surplus TIN-847, TIN-850). - Prove it on two real connections. Surplus has tests that run two transactions at once on the real migrations (
ledger-grant-children-concurrency,ledger-dock-concurrency). A mock cannot show a deadlock.
Ship order, and rollback order#
Every grant check reads the grant's columns, on every request. So a migration that adds a grant column ships before the build that reads it. If the build goes first, every agent gets a 401 until the migration lands (Surplus TIN-850, the dock grants migration).
- Roll back in the opposite order. Revert the app to a build that does not read the columns, then run the rollback migration. Keep that rollback as a file next to the migration.
- Do not fall back on a missing column. Surplus's token lookup does not catch 42703. The grant checks after it read the same columns, so a fallback would only move the failure. Failing closed is right.
- Or make the change safe in either order. Autio added a parameter to
apc_wait_claimwithdefault null, so the build from before the migration still resolves the function and the migration can go first (Autio TIN-844).
Presence over a private realtime channel#
The reference examples send presence on a page event stream. Without a long-lived process, use a private channel of your database's realtime service instead (Supabase Realtime in both apps).
- Ids only. The event is APC's
PresenceEvent: the grant, the tool, read or write, and at most 20 targets as{kind, id}. Never a name, an amount or free text (Surplus TIN-847). - Owner-only, private. One topic per person (
apc-user:{user_id}in Autio,agents:{user_id}in Surplus): a private channel, a policy that lets only that person read it, and no client may write to it. An agent token never listens. Surplus sends the event from the server through Realtime's broadcast endpoint, as private only. Autio sends it from a database function that runs for the agent's own grant (apc_publish_presence), which publishes nothing unless the person's page heartbeat is fresh (Autio TIN-670). - Send after a successful call, and never let it fail one. A missing function, an error or a read over 3 s leaves the tool's body as it is. Hold the send like the rest of the deferred work (see above).
- The same channel carries the revoke. Both apps broadcast an event when a grant ends, so every tab and device drops the agent's mark without a reload. Autio wraps only the send in its revoke triggers, so a failed broadcast can never fail a revoke (Autio TIN-815, Surplus TIN-847).
- Do not infer "waiting". A page cannot read the wait row, so it should not guess a waiting state from recent calls. Both apps did guess it (a call heard in the last 75 s, or the last call being a wait), and that shows "waiting" when no wait is running. Show no waiting state unless the app sends the presence
waitevents of APC 0.11, which only an app that claims and releases a wait atomically may send (Autio TIN-795, Surplus TIN-877, TIN-886).
Checklist#
GET /.well-known/apc.jsonnames your origin, your profiles andmcp.path, a prefix that starts and ends with/; build it once, at start. If the origin serves other MCP endpoints too, it lists the APC ones inmcp.endpoints(0.11; the spec): exact paths, and/{secret}last for one URL per grant. Keep fixed routes out of a{secret}parent, and keepmcp.pathfor readers before 0.11.declaresMcpUrlnow takes the profile ({ profile: "dock" }, or{ profile: "direct", shared: true }for an exact endpoint whose grants share the URL).- Every pointable element has
data-focus; targets carry ids and keys only. get_current_viewandwait_for_focusare registered on every grant.- Every tool runs inside the wrapper: revoke check,
attention, presence,then. - The agent bar is on every page, with Revoke; on a phone it stays in the page.
- If you show agents as pets:
<apc-pets>in the header, its states fed only by what the page knows, its colours following the page's scheme. - Revoke answers
revokedto every method (403 with a secret URL; 401 with a bearer token,revokedResponse(host, at, { bearer: true })); an unknown grant 404 (a plain 401 with a bearer token). wait_for_focusholds one wait per grant, and a pin is marked seen only once delivered.- Dock: every drop goes to the server; the hub is on your allowlist, checked on the drop and on the Allow (
parseDockDrop); a first drop calls/apc/connect(requestConnect) and consent happens on yourdock_connectpage (GET 200,Referrer-Policy: no-referrer, synchronous<head>script clearing#apc_connectintosessionStorage); consent uses the server's nonce and shows the pairing code, and the server sends the code to/apc/pairand keeps the grant only on the hub's acknowledgement (pairWithHub). - Dock: a grant serves data only after the hub's
initialize(dockGrantGate), and only for its own pairing (itsbinding); at an app implementing Dock or still serving any Dock grant, a grant that is not a Dock grant refuses the hub's introduction (directGrantGate, M12);POST /apc/revokeanswers the same 200 to anything (handleDockGiveBack); the person's routes checkOrigin,Sec-Fetch-Siteand the JSON media type;apc.jsonlistsdockonly while you can pair. - The conformance suite passes, on each profile you offer.