Skip to the content
OwnWing

DocsBuild

Build an OwnWing extension

An extension is your own app, running in your OwnWing stack as if it were part of it: people sign in to it with OwnWing ID, it shows up in the app launcher on the web and on the iPhone, the owner decides who may use it and what they may do, and it hears when someone is signed out.

Start with one command. In an OwnWing checkout:

./ownwing ext new recipes --name "Recipes"           # extensions/recipes, running and tested
scripts/agent/checks.sh <id>                       # npm ci, test, build

It writes a whole extension from Links, the example in extensions/example (a shared list of bookmarks and a private one for each person), with every name changed, its translations and a placeholder icon (scripts/ext-new.py; --help lists --color, --description, --order). It is an adaptive extension: it describes its screens as data and OwnWing’s web, iPhone and Android apps draw them with native controls, so it has no web UI code and no iPhone package (section 9). Then you replace the bookmarks with your own data and screens. This tutorial explains what the generated app does, part by part, in Links’ code.

You need Node 22 or newer, Python 3 and Docker. You don’t need to know OpenID Connect: the SDK does it.

  1. The manifest
  2. Sign-in with the SDK
  3. Roles
  4. Events
  5. Per-person storage
  6. The launcher icon
  7. Package it and ./ownwing ext add
  8. Testing locally
  9. Your extension’s screens
  10. Optional: a compiled iPhone module
  11. Your extension in coding agents (MCP)

The rules behind all this (what OwnWing promises an extension, and what it doesn’t give it) are in agent/design/extensions.md; the sign-in contract is contracts/auth/README.md.


1. The manifest

ownwing-extension.json tells OwnWing who your app is, where it runs, who may do what in it, and how to show it. ext new writes it; this is Links’:

{
  "id": "links",
  "name": "Links",
  "description": "Bookmarks for the household, and your own",
  "version": "0.1.0",
  "ownwing": ">=1.0",
  "host": "links",
  "service": "links:3000",
  "auth": {
    "redirect": "/auth/callback",
    "postLogout": "/",
    "events": "/auth/events",
    "roles": {
      "view": "See the shared links and keep their own",
      "edit": "Add and remove shared links"
    },
    "presets": {
      "editor": { "name": "Editor", "roles": ["view", "edit"] },
      "reader": { "name": "Reader", "roles": ["view"] }
    },
    "defaultRoles": { "admin": ["view", "edit"], "member": ["view"] }
  },
  "launcher": { "icon": "icon.svg", "color": "#2FBF71", "order": 90 },
  "storage": { "perPerson": "Links" },
  "mcp": { "path": "/mcp" },
  "settings": [
    { "env": "LINKS_PUBLIC_URL", "label": "Its own address (default https://links.<your domain>)", "optional": true }
  ]
}
Key Meaning
id 2–24 lowercase letters, digits and dashes, starting with a letter, unique in the install. It is also your client id at OwnWing ID and the aud of every token you get.
host, service Your address (https://links.<domain>), and the container and port the proxy and OwnWing ID reach inside the stack; you publish no ports.
auth.redirect, auth.postLogout, auth.events Your sign-in callback, where people land after signing out, and where OwnWing ID posts signed events (step 4).
auth.roles, presets, defaultRoles What the owner can give people in your app (with the admin page’s label), named sets of them, and what new people get by account kind.
launcher Your icon, the colour behind it and your place in the launcher.
storage.perPerson A folder of yours inside each person’s files: /users/<username>/Links (step 5).
storage.managed true when your app names the files in that folder itself (its database records them by path): Files then shows the folder read-only. Default false.
mcp Only with an MCP server for coding agents (step 10): { "path": "/mcp" }, where it answers on your service (path defaults to /mcp).
backup Only with a database of your own: how ./ownwing backup saves it consistently (step 7).
settings Environment variables the installer lists for the owner.
ios Only with a native iPhone module (step 9): { "module": "…Module", "product": "…Feature" }.

You never register your app by hand: OwnWing ID reads the manifest when it starts. The full rules are extensions/schema/ownwing-extension.schema.json; ./ownwing ext check <folder> checks the ones OwnWing ID enforces.

2. Sign-in with the SDK

OwnWing ID is an OpenID Connect provider. Your app sends the browser there, gets it back with a one-time code, trades the code for an ID token server to server, checks the token, and starts its own session. The token is a short-lived OwnWing token signed with OwnWing ID’s Ed25519 key.

The @ownwing/sdk package does every step of that for you (PKCE, state, nonce, the code exchange, and all the checks on the token), and it passes the same test vectors as OwnWing’s own apps. There are versions for Rust and Swift too; using any other OpenID Connect library is fine as well.

npm install @ownwing/sdk hono @hono/node-server

Inside this repo the example uses the SDK from sdk/typescript ("file:../../sdk/typescript", built by the preinstall script). In your own project, use the version above.

Configuration comes from the environment the stack gives every app (src/config.ts):

import { configFromEnv } from "@ownwing/sdk";

const publicUrl = process.env.LINKS_PUBLIC_URL || `https://links.${process.env.OWNWING_DOMAIN}`;
// reads OWNWING_ID_ISSUER, OWNWING_ID_URL, OWNWING_ID_TOKEN_URL and OWNWING_ID_PUBLIC_KEY
const signInConfig = configFromEnv(process.env, { clientId: "links", publicUrl });

Without OWNWING_ID_PUBLIC_KEY every sign-in is refused: the SDK fails closed.

Two routes do the whole sign-in (src/app.ts, section 1):

import { ReplayCache, SignIn, STATE_COOKIE, ownwingTheme, safeNext } from "@ownwing/sdk";

const replay = new ReplayCache();          // every token is single use; one per process
const signIn = new SignIn({ ...signInConfig, replay });

// 1. Off to OwnWing ID, with a fresh state, nonce and PKCE verifier kept in a short cookie.
app.get("/auth/login", (c) => {
  const { url, cookie } = signIn.begin(safeNext(c.req.query("next")));
  setCookie(c, STATE_COOKIE.name, cookie, { path: "/auth", httpOnly: true, secure: true, sameSite: "Lax", maxAge: 600 });
  return c.redirect(url, 302);
});

// 2. Back from OwnWing ID: check the state and issuer, trade the code, verify the ID token.
app.get("/auth/callback", async (c) => {
  const pending = getCookie(c, STATE_COOKIE.name);
  deleteCookie(c, STATE_COOKIE.name, { path: "/auth" });
  const r = await signIn.finish(
    { code: c.req.query("code"), state: c.req.query("state"), iss: c.req.query("iss"), error: c.req.query("error") },
    pending,
  );
  if (!r.ok) return r.relogin ? c.redirect(r.relogin) : c.text(r.reason, r.status);

  // r.claims: sub (the person), usr (username), name, scope (their roles), theme, …
  const id = sessions.start({ sub: r.claims.sub, usr: r.claims.usr!, name: r.claims.name ?? r.claims.usr!, roles: r.claims.scope.split(" "), theme: ownwingTheme(r.claims.theme) ?? "system" });
  setCookie(c, "links_session", id, { path: "/", httpOnly: true, secure: true, sameSite: "Lax" });
  return c.redirect(r.next, 302);
});

After that your app runs on its own session (src/sessions.ts: a random id in a cookie). Keep it at most a day: OwnWing ID asks apps to check back daily, and a silent trip through /auth/login does that without the person noticing.

Signing out ends your session, then OwnWing ID’s, so one “Sign out” means signed out:

app.post("/auth/logout", (c) => {
  sessions.end(getCookie(c, "links_session"));
  deleteCookie(c, "links_session", { path: "/" });
  return c.redirect(signIn.logoutUrl(), 303);
});

Every other page checks for a session first, and sends strangers to /auth/login?next=<the page>. Links also refuses form posts whose Origin isn’t its own address.

3. Roles

The ID token’s scope holds this person’s roles in your app, as the role names from your manifest, separated by spaces. The owner gives roles in OwnWing ID’s admin page, where they show as links.view and links.edit; your app sees scope: "view edit".

Role (admin page) scope word In Links
links.view view see the shared list, keep a private one
links.edit edit add and remove shared links

Check roles with hasScope when the session starts, and again on each action:

import { hasScope } from "@ownwing/sdk";

// at sign-in: no `view`, no Links
if (!hasScope(r.claims, "view")) return c.text("Ask the owner to give you Links.", 403);

// on each change to the shared list
if (!session.roles.includes("edit")) return c.text("Only editors can change the shared links.", 403);

OwnWing ID only gives a token to people who have at least one role in your app, but checking is cheap and your app stays right if someone mis-configures it.

When the owner changes someone’s roles, OwnWing ID sends your app a revoke (next step). Their next visit signs them in again silently, with the new roles.

4. Events

OwnWing ID tells your server things as they happen, with a signed token posted to auth.events:

POST /auth/events   {"token": "<signed event>"}     over the stack's network
Event What to do
revoke End every session of that person (they were paused, removed, or their roles changed).
prefs Their light or dark choice changed: use it in every session of theirs.
logout End the one session named by sid (only apps OwnWing ID marks for it get this).
anything else Answer 200 and ignore it.
import { eventAction, verifyOwnWingEvent } from "@ownwing/sdk";

app.post("/auth/events", async (c) => {
  // JSON only: a form on another site can't post here without a preflight
  if (!c.req.header("content-type")?.startsWith("application/json")) return c.json({ ok: false }, 415);
  const { token } = await c.req.json();
  const r = verifyOwnWingEvent(token, { publicKey, issuer, audience: "links", replay });
  if (!r.ok) return c.json({ ok: false, error: r.reason }, 401);

  const action = eventAction(r.event);
  if (action.kind === "revoke") sessions.endAll(action.sub);
  if (action.kind === "prefs") sessions.setTheme(action.sub, action.theme);
  return c.json({ ok: true });
});

Links prints the theme on its <html data-theme="…">; its CSS has a light set, a dark set, and follows the device for system. The ID token carries the same theme at sign-in.

OwnWing ID retries an event it couldn’t deliver for a day, so it’s fine to be briefly down.

5. Per-person storage

With "storage": { "perPerson": "Links" }, each person gets a folder of yours inside their own files: /users/<username>/Links. It sits next to their photos and documents, so it is backed up with them and they can see and take their data.

Links keeps two lists (src/storage.ts):

/data/links.json                    the shared list: the app's own data
/users/<username>/Links/links.json  one person's private list

The username is the token’s usr. It comes from a verified token, but a path is a path, so check it anyway before you build one:

const USERNAME = /^[a-z][a-z0-9-]{1,23}$/;

file(list: "shared" | { usr: string }) {
  if (list === "shared") return join(this.dataDir, "links.json");
  if (!USERNAME.test(list.usr)) throw new Error("not an OwnWing username");
  return join(this.usersDir, list.usr, "Links", "links.json");
}

Write safely: a temporary file, then a rename, so a crash never leaves half a list. Only ever touch your own folder in someone’s files; OwnWing gives extensions no other app’s data.

It is an app folder in Files. Its name at the top of each person’s home is kept for your app, as Photos is for Photos: nobody can take that name, rename the folder, move it or put it in the trash. People still open it and see their files there. When your app names the files itself (a database keeps each one by its path, so a file renamed behind its back is lost to it), add "managed": true:

"storage": { "perPerson": "Notes", "managed": true }

and Files shows the whole folder read-only. Links keeps one plain JSON file that people may look at, so it leaves managed off.

Files learns the app folders from OWNWING_APP_FOLDERS, which ./ownwing writes into .env from the manifests of the extensions you added (a managed value, like OWNWING_APPS: never edit it by hand) and the stack passes to Files: comma-separated <id>=<Folder>, with :ro when managed is true, for example notes=Notes:ro,links=Links. ext add and ext remove rewrite it.

6. The launcher icon

Every OwnWing app has a mark in the same language, drawn on a 120 × 120 grid (the whole style, with every app’s colours, is the ownwing-icons skill, .claude/skills/ownwing-icons/SKILL.md; the files are in brand/README.md):

  • a tile of your own colour, corners rx="28", a vertical gradient lighter at the top. Pick a hue none of the apps use: Photos is yellow, Files periwinkle, Links green (#5EDB95 → #1FA35C), and the other extensions in your extensions/ their own (each manifest’s launcher.color);
  • one bold white glyph, #FFFFFF, soft and rounded (strokes about 10 units, round caps and joins), about 84 units wide;
  • one accent in your hue’s pale tint (Links: #D2F5E1); details are cut out of the glyph, never outlined.

Links’ chain, icon.svg (the file is the drawing; to have brand/tools/marks.py draw your mark and its variants from code, define it in your .agents/brand/mark.py, see brand/README.md):

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120">
  <defs><linearGradient id="glinks" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#5EDB95"/>
    <stop offset="1" stop-color="#1FA35C"/></linearGradient></defs>
  <rect width="120" height="120" rx="28" fill="url(#glinks)"/>
  <defs><mask id="lk" maskUnits="userSpaceOnUse" x="0" y="0" width="120" height="120">
    <rect width="120" height="120" fill="#fff"/>
    <rect x="56" y="50" width="42" height="20" rx="10" fill="none" stroke="#000" stroke-width="15"
          transform="rotate(-45 60 60)"/></mask></defs>
  <g transform="rotate(-45 60 60)">
    <rect x="22" y="50" width="42" height="20" rx="10" fill="none" stroke="#D2F5E1" stroke-width="10" mask="url(#lk)"/>
    <rect x="56" y="50" width="42" height="20" rx="10" fill="none" stroke="#FFFFFF" stroke-width="10"/>
  </g>
</svg>

Name it in the manifest ("launcher": { "icon": "icon.svg", "color": "#2FBF71" }) and serve it at /icon.svg too, for your own favicon and header.

7. Package it and ./ownwing ext add

An extension is one folder: the manifest, compose.yaml (one service), a Dockerfile, icon.svg, a README, its code and tests (and contract/, ios/ when it has a phone module). The Dockerfile builds one bundled file and runs it as an unprivileged user; compose.yaml names no network (it joins the stack’s), publishes no ports (the proxy routes links.<domain> to links:3000 from the manifest), keeps its data in <OWNWING_DATA>/extensions/<id>, runs as the install’s user, read_only with every capability dropped. ext new writes both; keep those rules when you change them.

Then, from your OwnWing folder:

./ownwing ext check extensions/example     # is the folder a valid extension?
./ownwing ext add extensions/example       # or a git URL
./ownwing up

An extension that describes its screens as data (its manifest has "ui": {"entry": "/api/ui/home"}, see contracts/ui/README.md) can draw them on the web while you build, with no OwnWing stack running:

./ownwing ext preview extensions/<id> --target http://127.0.0.1:3000   # your extension's dev server

It prints a page address (http://127.0.0.1:8788/; add ?entry=/api/ui/other for another screen or ?theme=dark) and two environment variables to start your extension with. The preview signs in for you the way the iPhone does (a throwaway key, trusted by nothing but your own dev server).

ext add shows what the extension’s compose file asks of the machine and lists its settings (set them in .env), adds it to the stack, and restarts OwnWing ID if the stack is running so it registers the app (otherwise ./ownwing up does). Open https://links.<domain>, or tap Links in the launcher. Later: ./ownwing ext list, ext remove links; new code is ./ownwing up --build; a changed manifest or icon needs ext remove and ext add again (its data stays), because ext add is what hands them to OwnWing ID. A manifest that breaks the schema is skipped by OwnWing ID with only a line in its log, so run ext check first.

Backups. ./ownwing backup saves every extension’s data folder, <OWNWING_DATA>/extensions/<id>/, in extensions.tar.gz. Plain files (Links’ JSON) need nothing more. A database that is written while it runs (Postgres, MySQL, a busy SQLite) can’t be copied file by file, so the manifest says how to dump it:

"backup": {
  "service": "notes-db",
  "dump": "pg_dumpall -U notes --clean --if-exists",
  "restore": "psql -q -U notes -d postgres",
  "skip": ["db"]
}
Key Meaning
service The compose service that holds the database (one of your compose.yaml’s).
dump A shell command run in that service that prints the whole dump on stdout.
restore A shell command run there that reads the dump on stdin.
skip Folders under your data folder left out of extensions.tar.gz (the database’s own files, which the dump replaces).

Backup runs docker compose exec -T <service> sh -c "<dump>" and keeps the output, gzipped, as extensions/<id>.dump.gz in the backup folder; ./ownwing restore puts the data folder back, starts the service and pipes the dump into restore (backup and restore).

8. Testing locally

You can test everything without an OwnWing ID running. The SDK’s testing helper makes a throwaway signing key and signs tokens with it:

import { testIssuer } from "@ownwing/sdk/testing";
const id = testIssuer("https://id.example.com");   // id.publicKey goes in OWNWING_ID_PUBLIC_KEY
const token = id.sign({ sub: "u_abcdefgh23", aud: "links", usr: "sam", scope: "view", amr: ["passkey"], auth_time: now - 5, nonce });

Links’ tests (extensions/example/test/app.test.ts) build the app with a fake token endpoint (the SDK’s SignIn takes a fetch), then walk the real browser dance:

const login = await app.request("/auth/login?next=/");                       // 302 to OwnWing ID
const authorize = new URL(login.headers.get("location")!);                   // has state, nonce, code_challenge
// the fake endpoint checks the code and PKCE verifier, and answers id.sign({…, nonce})
const callback = await app.request(`/auth/callback?code=hac_test&state=…&iss=…`, { headers: { cookie: stateCookie } });
// → 302 to "/", with a links_session cookie

They cover: the redirect and its PKCE parameters, a good sign-in, a state from another browser, someone without view, sign-out, revoke and prefs events, forged and replayed events, private files landing in /users/<username>/Links, only editors changing the shared list, and every screen validating (no errors, no warnings) for an editor and a reader in several languages.

cd extensions/example
npm ci && npm test && npm run build
docker build --build-context sdk=../../sdk -t ownwing-links .   # in this repo (it builds the web renderer too)

To click through it for real, run OwnWing on your laptop (./ownwing init keeps the default domain ownwing.localhost, which needs no DNS), add the extension, and open https://links.ownwing.localhost.

9. Your extension’s screens

An adaptive extension has no UI code of its own. It answers GET /api/ui/... with screen documents (JSON: a title, a toolbar, the data it reads, a body of blocks) and OwnWing’s apps draw them natively: SwiftUI on the iPhone, Compose on Android, OwnWing’s web renderer in the browser, in OwnWing’s look, light and dark, in the person’s language, right to left, with VoiceOver and TalkBack. The specification is contracts/ui/README.md; the examples to copy are in contracts/ui/examples/ (a task app, settings, charts, a week planner made only of primitives, a diet and gym app).

The manifest names the first screen (every other screen is a path it navigates to) and, optionally, an accessory: a small screen drawn on every screen of the extension (contracts/ui/README.md § 2.1):

"ui": { "entry": "/api/ui/home", "accessory": "/api/ui/accessory" }

A screen, built in code with the SDK (@ownwing/sdk/ui, TypeScript; ownwing::ui in Rust, feature ui) and answered per request, so every word is in the person’s language:

import { screen, list, section, repeat, row, expr, act, serve } from "@ownwing/sdk/ui";

app.get("/api/ui/home", async (c) => {
  const t = await translatorFor(session.locale, c.req.header("accept-language"));
  return serve(screen({                                     // serve checks it and answers with the screens' media type
    title: t.t("notes.title", "Notes"),
    largeTitle: true,
    state: { query: "" },                                   // the screen's variables
    data: { notes: { url: "/api/notes", select: "items" } },   // read from your own API with the person's session
    search: { bind: "query" },                              // the platform's search field
    toolbar: [{ id: "add", label: t.t("notes.add", "New note"), icon: "add", action: act.navigate("/api/ui/notes/new", "sheet") }],
    body: list([section([
      repeat({
        items: expr("filter(data.notes, n => contains(lower(n.title), lower(state.query)))"),
        key: expr("note.id"), as: "note",
        template: row({ title: "=note.title", accessory: "chevron", onTap: act.navigate("='/api/ui/notes/' + note.id") }),
      }),
    ])]),
  }));
});

What a screen is made of:

  • Ready-made blocks, native on every platform: list, row (with swipe actions), detail, form and its fields (text, toggle, picker, date, photo…), chart, map, tabs, sheet, empty, button… Revision 3 adds secret and tokens fields, camera and scanner capture, donut and gauge charts and keyboard shortcuts (contracts/ui/README.md § 4.4, § 4.12).
  • Primitives for anything else: vstack, hstack, grid, scroll, absolute (children placed by coordinates: planners, timelines), text, icon, shape, path, repeat, if.
  • Expressions: a string starting with = ("=item.done and not state.hidden") is a small, safe, side-effect-free language with helpers for lists, text, numbers and dates, computed on the device and identical on every platform.
  • Actions, the only side effects: http (call your API, then refresh or navigate), navigate, set (state), confirm, toast, open, share, copy, haptic…

Data goes in through data sources (paths on your own address, fetched with the person’s session, kept for offline reading) and out through http actions. Your API checks roles as ever: a screen only hides a button, the server decides. A write carries the header X-OwnWing-UI: 1, which a form on another site can’t send, so refuse a write without it (Links’ session middleware does).

On the web, your extension serves OwnWing’s prebuilt renderer at its own root and has no web code (@ownwing/sdk/ui/host):

const web = webRenderer({ dir: config.webDir, entry: "/api/ui/home", app: { id: "notes", name: "Notes", color: "#8E5BE8" } });
app.get("*", async (c) => (await web.handle(c.req.raw, { person, locale, theme })) ?? c.notFound());   // after your session check

The renderer is built from sdk/react (npm run web in the extension builds it into ./web; the Dockerfile’s web stage does the same in the image). On the iPhone and Android, the apps find ui in OwnWing ID’s /api/apps and draw the screens themselves.

Check them. serve() and assertValid(doc) throw with every problem listed (the schema, every expression, ids, accessibility, limits); Links’ tests validate each screen for an editor and a reader in four languages and fail on warnings. A coding agent can check a document without running anything: the gateway’s MCP tool ownwing_validate_screen (docs/mcp.md) returns the errors and warnings.

See them while you build.

npm run web && npm run build
./ownwing ext preview <id>           # prints OWNWING_ID_ISSUER and OWNWING_ID_PUBLIC_KEY: start your server with them
# then open http://127.0.0.1:8788/   (?entry=/api/ui/other opens another screen, ?theme=dark)

The preview serves the web renderer against your dev server and signs in for you, the way the phone does (a throwaway key trusted by nothing but your own dev server). On a Mac, scripts/agent/mac.sh sim --route ext/<id> draws the same screens natively on the iPhone simulator.

The coding-agent skill ownwing-extension-screens (.claude/skills/) explains every block, primitive, expression helper and action with short examples; it is what ./ownwing ext new points a new extension’s agent at.


10. Optional: a compiled iPhone module

The OwnWing iPhone app shows every extension in its launcher. An extension with ui screens (section 9) is drawn natively there with nothing to build; a compiled module is for what blocks can’t express (a terminal, screen sharing) and wins on the phone when present. Without either, tapping an extension opens your web address in Safari. With ./ownwing ext new <id> --ios you get a compiled one from the start. Apple lets no app load code at run time, so modules are compiled into the app: whoever builds their own OwnWing iPhone app includes the ones in their checkout.

What --ios writes (from templates/extension-ios):

Part What it is
extensions/<id>/ios/Package.swift A Swift package on OwnWing’s core package (ios/Packages/OwnWingCore)
<Type>Core Foundation only: the models (decoding contract/<id>.json) and the API client. Builds and tests on Linux
<Type>Feature SwiftUI: <Type>Module, conforming to OwnWingModule (its id, name, mark, sign-in, screens, hub card, devSession), and its strings’ catalog
extensions/<id>/ios/Tests The Core test that decodes the contract’s fixtures
the manifest’s ios { "module": "<Type>Module", "product": "<Type>Feature" }, and "usage" when it needs the microphone, camera and the like (below)
ios/Extensions.yml, ios/ExtensionPackages/<id>, ios/OwnWing/App/Extensions.swift Written by ios/scripts/extensions.sh for this checkout, before every xcodegen (the install script, the simulator and CI run it), and git-ignored: each checkout builds the modules of the extensions it holds. It adds every module a manifest names to the app (the link gives each package its id as its name: Xcode names a local package after its folder, and every extension’s is ios)

Its sign-in. The app signs in to OwnWing ID once per phone. For your module it fetches a five-minute OwnWing token (audience = your client id, amr ["device"], no nonce) and calls the module’s signIn(ownwingToken:deviceName:), which trades it at your server for your own session:

POST https://links.<domain>/api/auth/phone   {"token": "…", "deviceName": "Sam's iPhone"}
→ {"ok": true, "session": "…", "expiresIn": 86400}         then: Authorization: Bearer <session>

Links’ server already does this (src/app.ts, the SDK’s verifyOwnWingToken with nonce: null); its fixtures and errors are in extensions/example/contract. A 401 later tells the app to fetch a new OwnWing token and try once more.

Sensitive actions take a step-up: quick sign-in (Face ID, a fingerprint) or the passcode on the phone, proven to your server with a 60-second token (OwnWingStepUp.token(for:reason:bioOnly:) in the module, the X-OwnWing-Step-Up header; on the server, verify it like a phone token, then isFreshStepUp and the same sub as the session). The ownwing-extension-ios and ownwing-extension-signin skills have the details.

The microphone, the camera and the like. iOS asks the person before an app uses them, with a sentence from the app’s Info.plist, and ends an app that opens one without it. Your module can’t add to the app’s Info.plist, so say what it needs in the manifest, one sentence each:

"ios": { "module": "<Type>Module", "product": "<Type>Feature",
         "usage": { "microphone": "When you record a voice note, Notes hears this iPhone's microphone." } }

The names are microphone, camera, speech, location, contacts, bluetooth and motion. ios/scripts/extensions.sh writes each sentence into the app (ios/Extensions.yml); the keys the app itself already has (Face ID, photos, the local network) aren’t yours to set.

Build and test. The Core’s tests run on Linux; the app builds on a Mac with Xcode (agent/runbooks/iphone.md):

scripts/agent/swift.sh --package extensions/<id>/ios test     # or: scripts/agent/checks.sh swift
ios/scripts/extensions.sh                                     # wire this checkout's modules into the app

11. Your extension in coding agents (MCP)

OwnWing has one MCP server for coding agents (Claude Code and the like, docs/mcp.md): the gateway at mcp.<your domain>. It reaches each app’s own MCP server on the stack’s network and shows its tools as <app>_<tool>. Yours joins by saying so in the manifest:

"mcp": { "path": "/mcp" }

From then on, the agent consent screen (OwnWing ID, the first time someone connects an agent) lists your app beside Photos and Files, with a read or write switch, for the people who have a role in it; removing the extension (./ownwing ext remove) takes it out of the agents’ tools. An app with no mcp key is not offered to agents.

What your server may rely on, and must do:

  • Who calls. Only the gateway, with a token it trades OwnWing ID for: an OwnWing token for your id (two minutes, reused for many calls), scope the person’s roles in your app, access read or write (what the person gave the agent), act the agent. @ownwing/sdk/mcp (verifyAgentToken) and ownwing::agent (verify_agent_token) check it. Answer 401 to anything else: a person’s own session never opens it.
  • The person’s data only. The agent acts as that person, with the roles in scope. Check them in each tool as you do in your pages, and never return another person’s data, or anything that needs a step-up.
  • access: "read" never changes anything. ownwingTool refuses a write tool for it (error code forbidden).
  • Plain tool names (search, add, delete), a JSON Schema for inputs and outputs, and the annotations readOnlyHint, destructiveHint, idempotentHint (the helper sets them).
  • search {query, limit} if you have one: ownwing_search calls it on every granted app.
  • Resources at ownwing://<your id>/<kind>/<id>; errors as tool errors with a stable code in structuredContent.error.code: not_found, invalid_arguments, forbidden, too_large, app_error.
  • Subscriptions (resources/subscribe): tell watching agents when something changes, from the same place your own events come from (Subscriptions.publish).

TypeScript, with the official @modelcontextprotocol/sdk (install it and zod yourself):

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { createMcpHandler, ownwingTool, ToolError } from "@ownwing/sdk/mcp";
import { z } from "zod";

const handler = createMcpHandler({
  publicKey, issuer, audience: "notes",            // OWNWING_ID_PUBLIC_KEY, OWNWING_ID_ISSUER, your id
  create: () => {
    const server = new McpServer({ name: "notes", version: "1.0.0" });
    ownwingTool(server, {
      name: "search", title: "Search notes", access: "read", role: "view",
      description: "Search the person's notes by words.",
      inputSchema: { query: z.string(), limit: z.number().int().optional() },
      outputSchema: { notes: z.array(z.object({ id: z.string(), title: z.string() })) },
      run: async ({ query, limit }, ctx) => ({ notes: await find(ctx.sub, query, limit ?? 10) }),
    });
    return server;
  },
});
app.all("/mcp", (c) => handler.handle(c.req.raw)); // before your session middleware

Rust, with rmcp (ownwing-sdk with features = ["mcp"]): serve StreamableHttpService at your path behind a middleware that calls ownwing::mcp::authenticate and puts the AgentContext in the request’s extensions; in a tool, agent_of(&ctx.extensions), guard(&ctx, write, role), ok(…), fail("not_found", …), tool_annotations(…). sdk/rust/tests/mcp.rs is a whole server.

Links is the example: extensions/example/src/mcp.ts (tools search, list, add, update, delete, the resource ownwing://links/link/<id>, subscriptions) and its test/mcp.test.ts; ./ownwing ext new copies them. To try it: connect an agent to the gateway (docs/mcp.md) and ask it to add a link.

Checklist

  • Started from ./ownwing ext new (or kept everything it writes).
  • ui.entry in the manifest and screens that validate (no errors, no warnings) in the extension’s tests; no web UI code: the prebuilt renderer is served at its root.
  • ownwing-extension.json with a unique id, your roles and a launcher entry.
  • Sign-in at /auth/login and /auth/callback; your own session, a day at most; sign-out through OwnWing ID.
  • Roles checked from scope, at sign-in and on every action.
  • POST /auth/events handles revoke and prefs, JSON only.
  • Your data in /data; people’s own data only in /users/<username>/<your folder> ("managed": true if your app names the files there itself).
  • A database of your own? A backup entry in the manifest that dumps and restores it.
  • icon.svg in the family style, with a colour of your own.
  • compose.yaml: one service, the stack’s network, no published ports.
  • Tests that sign in against a fake token endpoint.
  • An MCP server for coding agents? mcp in the manifest, only the gateway’s token accepted, write tools refused for access: "read", the person’s own data only.

Edit this page on GitHub