@mgcrea/mcp-apple-maps 1.38.0 → 1.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server--c2qkmbX.js","names":["#lane","#write","#unreadable","num","str","#path","#openUrl","#seedTimeoutMs","#read","#describeIn","#existing","#donorNear","#maxHistory","#toSource","#seededDonors","#col","#colText","#unfiledClause","#entityFor","#placeSelect","#toPlace","#keyClause","#config","#lane","#openUrl","#logger","#home","#located","#store","#storeError","#render","#renderCollection","queryArg","queryArg"],"sources":["../src/build-info.ts","../src/client/dates.ts","../src/client/errors.ts","../src/client/locate.ts","../src/client/lane.ts","../src/client/open-url.ts","../src/client/place-source.ts","../src/client/ref.ts","../src/client/store.ts","../src/client/maps.ts","../src/config.ts","../src/guide.ts","../src/prompts.ts","../src/tools/util.ts","../src/tools/store-writes.ts","../src/tools/diagnostics.ts","../src/tools/places.ts","../src/tools/index.ts","../src/server.ts"],"sourcesContent":["// Build-time / runtime identity for the running server. `name`/`version` are\n// read from package.json at startup (always accurate); `gitCommit` /\n// `gitCommitDate` are injected by tsdown's `define` substitution at build time\n// and fall back to \"unknown\" when running from source (e.g. vitest).\n\nimport { readPackageIdentity, type BuildInfo } from \"@mgcrea/mcp-apple-core\";\n\n// oxlint-disable no-underscore-dangle -- bundler-injected build-time constants.\ndeclare const __GIT_COMMIT__: string;\ndeclare const __GIT_COMMIT_DATE__: string;\n\nconst pkg = readPackageIdentity(new URL(\"../package.json\", import.meta.url), {\n name: \"@mgcrea/mcp-apple-maps\",\n version: \"0.0.0\",\n});\n\nexport type { BuildInfo };\n\nexport const BUILD_INFO: BuildInfo = {\n name: pkg.name,\n version: pkg.version,\n gitCommit: typeof __GIT_COMMIT__ === \"string\" ? __GIT_COMMIT__ : \"unknown\",\n gitCommitDate: typeof __GIT_COMMIT_DATE__ === \"string\" ? __GIT_COMMIT_DATE__ : \"unknown\",\n};\n","/**\n * Date handling for the Maps tools.\n *\n * Deliberately much smaller than `packages/safari/src/client/dates.ts`. That\n * surface needed a whole input grammar because history is a range query; Maps'\n * entities are lists a person curates, and v1 ships no tool taking a date\n * argument. So this module solves only the OUTPUT half — turning a stored\n * number into an instant. Inventing a parser nothing calls would be a fourth\n * copy of a grammar `packages/safari` has already noted should be hoisted into\n * core rather than duplicated again.\n *\n * ## The epoch is DETECTED, never assumed\n *\n * `docs/maps.md` records the measurement: `ZCREATETIME` resolves to\n * **apple-seconds** (Core Data, 2001 anchor). The same value read as unix\n * seconds lands in **1995** — well-formed, plausible at a glance, and wrong by\n * 31 years. `pnpm probe:maps` prints both readings side by side precisely\n * because the wrong one does not announce itself.\n *\n * So the offset is resolved from the store's own newest timestamp at open time,\n * and when it cannot be resolved every date renders `null` rather than being\n * guessed. An absent timestamp is a visible gap somebody can report; a\n * confidently wrong one is not. This is the discipline `packages/safari`\n * arrived at after a probe misread its own column — adopted here rather than\n * re-derived.\n */\n\nimport { CORE_DATA_EPOCH_OFFSET, detectEpoch, type Epoch } from \"@mgcrea/mcp-apple-core\";\n\nexport { CORE_DATA_EPOCH_OFFSET };\n\n/**\n * How this store's timestamps map onto real time. Re-exported so callers here\n * have one import for dates.\n *\n * `confident` is the field that matters, and it now comes from `detectEpoch`\n * itself: the offset alone cannot distinguish \"measured as unix\" from \"gave up\n * and assumed unix\", and this module used to tell them apart by matching a\n * regex against the detector's prose — a coupling to a sentence in another\n * package.\n */\nexport type { Epoch };\n\nexport const resolveEpoch = (maxTimestamp: number | null, now: number = Date.now()): Epoch =>\n detectEpoch(maxTimestamp, now);\n\n/** The expectation docs/maps.md carries, used only where no store is open. */\nexport const APPLE_SECONDS: Epoch = {\n offset: CORE_DATA_EPOCH_OFFSET,\n reason: \"assumed apple-seconds; no store was opened to measure against\",\n confident: false,\n};\n\n/** A stored timestamp to a JS Date, or null when it cannot be placed. */\nexport const fromStoreTime = (value: number | null, epoch: Epoch): Date | null => {\n if (value === null || !Number.isFinite(value) || value === 0) return null;\n if (!epoch.confident) return null;\n const date = new Date((value + epoch.offset) * 1000);\n return Number.isNaN(date.getTime()) ? null : date;\n};\n\n/** ISO-8601, or null. What every date field on a result carries. */\nexport const renderInstant = (value: number | null, epoch: Epoch): string | null =>\n fromStoreTime(value, epoch)?.toISOString() ?? null;\n","/**\n * Maps' error surface. The taxonomy lives in `@mgcrea/mcp-apple-core`; what\n * belongs here is the identity those messages are written against, plus the\n * failures no other surface has.\n */\n\nimport { AppleAutomationError, type SurfaceContext } from \"@mgcrea/mcp-apple-core\";\n\nexport const MAPS_SURFACE: SurfaceContext = {\n appName: \"Maps\",\n envPrefix: \"APPLE_MAPS\",\n};\n\n/**\n * Maps is one of the few Apple apps whose bundle id matches its display name —\n * unlike `com.apple.iCal`, `com.apple.AddressBook` and `com.apple.MobileSMS`.\n * Stated rather than assumed, because this repo has been caught by the opposite\n * three times.\n *\n * It is recorded here and used by almost nothing. Maps ships **no scripting\n * dictionary** — `/System/Applications/Maps.app` contains no `.sdef`, checked\n * directly rather than inferred from `NSAppleScriptEnabled` — so there is no\n * Apple Events lane to address, and this server never sends one.\n */\nexport const MAPS_BUNDLE_ID = \"com.apple.Maps\";\n\nexport {\n AppleAutomationError as AppleMapsError,\n IndexUnavailableError,\n PlatformError,\n PreconditionError,\n ProtocolError,\n SchemaDriftError,\n TccDeniedError,\n WritesDisabledError,\n} from \"@mgcrea/mcp-apple-core\";\n\n/**\n * The store could not be read.\n *\n * This surface has **one lane and no fallback**, which puts it with Messages\n * rather than with Safari: without Full Disk Access there is no degraded Maps\n * server, there is no Maps server. So every read throws this rather than\n * returning an empty list — an empty `favorites` reads exactly like a person\n * who has saved no places, and that is the failure this error exists to\n * prevent.\n *\n * The hint names the trap that actually catches people: the store lives at a\n * path with **no file extension**, inside the one directory in Maps' container\n * that Full Disk Access gates. A sweep for `*.db` finds nothing and concludes\n * the data is not on disk. It is.\n */\nexport class MapsStoreUnavailableError extends AppleAutomationError {\n override readonly name = \"MapsStoreUnavailableError\";\n\n constructor(reason: string) {\n super(\n `${reason} Maps has no second lane — it ships no scripting dictionary, so there is no ` +\n `Apple Events fallback and nothing at all can be read without the grant.`,\n {},\n );\n }\n}\n\n/**\n * A write could not be prepared: no place record to copy, or one Maps\n * resolved too far from the coordinate given. Raised before the store lane is\n * asked to save anything, so nothing was written.\n */\nexport class MapsWriteError extends AppleAutomationError {\n override readonly name = \"MapsWriteError\";\n}\n\n/** A ref no longer resolves — the place was removed, or the store was re-synced. */\nexport class PlaceNotFoundError extends AppleAutomationError {\n override readonly name = \"PlaceNotFoundError\";\n\n constructor(ref: string) {\n super(\n `No place for ref \"${ref}\". It may have been removed in Maps, or iCloud may have ` +\n `re-synced the store and renumbered it. Re-run the listing to get a current ref.`,\n { ref },\n );\n }\n}\n\n/**\n * The epoch could not be identified from the data.\n *\n * The same discipline `packages/safari` applies, for the same measured reason:\n * a wrong epoch produces dates that are well-formed and wrong by 31 years.\n * `docs/maps.md` records that this store's `ZCREATETIME` read as apple-seconds\n * and that a unix-seconds reading of the same value lands in 1995 while still\n * looking entirely plausible. So the offset is detected from the store at open\n * time and dates are WITHHELD when it cannot be.\n */\nexport class UndatableStoreError extends AppleAutomationError {\n override readonly name = \"UndatableStoreError\";\n\n constructor(reason: string) {\n super(\n `Maps' timestamps could not be placed on a known epoch (${reason}). Dates are withheld ` +\n `rather than guessed — a timestamp wrong by decades reads exactly like a correct one. ` +\n `Everything that does not depend on a date still works.`,\n {},\n );\n }\n}\n","import { readdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport {\n describeStore,\n inspectFile,\n type FileFacts,\n type StoreFacts,\n} from \"@mgcrea/mcp-apple-core\";\n\n/**\n * Find Maps' store.\n *\n * ## The path, and the three ways it was missed\n *\n * `~/Library/Containers/com.apple.Maps/Data/Maps/MapsSync_0.0.1` — 3.3 MB of\n * Core Data on the probed machine. `docs/maps.md` records that this surface was\n * declared \"no file lane\" three separate times before the file was found, and\n * each failure is a rule this locator is shaped by:\n *\n * 1. **The file has no extension.** A sweep for `*.db` / `*.sqlite*` finds\n * nothing here. Nothing in this file matches on a suffix.\n * 2. **`Data/Maps/` is gated.** It was the ONE unreadable directory in the\n * container, so a listing taken without Full Disk Access omits it, and the\n * omission reads as absence. `inspectFile` splits exists from readable\n * precisely so those two never collapse into one answer.\n * 3. **`group.com.apple.Maps` is a decoy.** It exists, it is EPERM without the\n * grant, and it holds three files that are not the store. A probe that\n * could not descend into it reported it as empty.\n *\n * The rule underneath all three is the one `docs/surfaces.md` states: \"'Absent'\n * and 'EPERM' are different findings.\" Keeping them apart, and saying which one\n * happened, is most of this module's job.\n *\n * ## The device-local cache is located and never read\n *\n * `MapsSync_0.0.1_deviceLocalCache.db` sits beside the store with the same 33\n * entities and, on the probed machine, **zero rows in every one of them**. It is\n * reported by diagnostics so anyone comparing the directory against this\n * server's output can see it was considered, and it is never opened.\n */\n\n/** The container path. `Data/Maps` is the gated directory, not `Data/Library`. */\nexport const MAPS_DIR = [\"Library\", \"Containers\", \"com.apple.Maps\", \"Data\", \"Maps\"];\n\n/**\n * No extension, and a version in the name.\n *\n * The `0.0.1` was stable on every machine this project has measured, but it is a\n * version string and it will move. `locateStore` falls back to scanning for a\n * `MapsSync_*` sibling rather than reporting a rename as \"Maps has never run\".\n */\nexport const STORE_FILENAME = \"MapsSync_0.0.1\";\nexport const STORE_PREFIX = \"MapsSync_\";\nexport const LOCAL_CACHE_SUFFIX = \"_deviceLocalCache.db\";\n\nexport const FDA_HINT =\n \"Grant Full Disk Access to the app running this server (System Settings > Privacy & \" +\n \"Security > Full Disk Access) and restart it. Granting it to Maps.app does nothing — the \" +\n \"reader needs the permission, not the app.\";\n\nexport type LocatedFile = FileFacts & { path: string };\n\nexport type LocateResult = StoreFacts & {\n directory: string;\n storePath: string | null;\n /** Reported so a reader can see it was considered. Never opened. */\n localCache: LocatedFile;\n /** True when the name came from a directory scan rather than the constant. */\n resolvedByScan: boolean;\n reason: string | null;\n};\n\nexport const defaultDirectory = (home: string = homedir()): string => join(home, ...MAPS_DIR);\n\nexport const defaultStorePath = (home: string = homedir()): string =>\n join(defaultDirectory(home), STORE_FILENAME);\n\nconst locateFile = (path: string): LocatedFile => ({ ...inspectFile(path), path });\n\n/**\n * Look for a `MapsSync_*` that is neither the local cache nor a SQLite sidecar.\n *\n * Only reached when the constant path is absent, and it needs the directory to\n * be listable — the same grant the store itself needs, so this asks for no new\n * permission and simply survives a version bump.\n */\nconst scanForStore = (directory: string, readdir: (p: string) => string[]): string | null => {\n let names: string[];\n try {\n names = readdir(directory);\n } catch {\n return null;\n }\n const candidate = names\n .filter(\n (n) =>\n n.startsWith(STORE_PREFIX) &&\n !n.endsWith(LOCAL_CACHE_SUFFIX) &&\n !n.endsWith(\"-wal\") &&\n !n.endsWith(\"-shm\"),\n )\n .toSorted()\n .at(-1);\n return candidate ? join(directory, candidate) : null;\n};\n\nexport const locateStore = (\n opts: {\n storePath?: string | undefined;\n home?: string;\n /** Injected by tests so a scan never reaches a real directory. */\n readdir?: (path: string) => string[];\n } = {},\n): LocateResult => {\n const directory = defaultDirectory(opts.home);\n const readdir = opts.readdir ?? ((p: string): string[] => readdirSync(p));\n\n const explicit = opts.storePath;\n const constant = defaultStorePath(opts.home);\n\n let storePath = explicit ?? constant;\n let resolvedByScan = false;\n\n if (!explicit && !describeStore(constant).exists) {\n const scanned = scanForStore(directory, readdir);\n if (scanned) {\n storePath = scanned;\n resolvedByScan = true;\n }\n }\n\n const facts = describeStore(storePath);\n\n const reason = facts.readable\n ? null\n : facts.exists\n ? `Found Maps' store at ${storePath} but cannot read it. ${FDA_HINT}`\n : explicit\n ? `No file at ${explicit}. APPLE_MAPS_STORE points at nothing.`\n : `No Maps store at ${storePath}, and no MapsSync_* file in ${directory}. Either Maps ` +\n `has never been used on this account, or the directory itself is not readable — those ` +\n `look identical from outside and only the grant tells them apart. ${FDA_HINT}`;\n\n return {\n ...facts,\n directory,\n storePath: facts.exists || !explicit ? storePath : null,\n localCache: locateFile(`${constant}${LOCAL_CACHE_SUFFIX}`),\n resolvedByScan,\n reason,\n };\n};\n","import { openStoreLane, type StoreLane, StoreLaneError } from \"@mgcrea/mcp-apple-core\";\n\nimport { MAPS_SURFACE } from \"./errors.js\";\nimport type { SourceKind } from \"./place-source.js\";\n\n/** What the app answers after one save. `changed` is empty when there was nothing to do. */\nexport type LaneWrite = {\n /** The item written, or the one that already stood there: a dashed uuid. */\n id: string;\n changed: string[];\n /** False when the item already existed and was returned unchanged. */\n created: boolean;\n /** `fileInGuide` only: whether the read-back found the place in the Guide. */\n filed?: boolean;\n modelVersion: string | null;\n /** True only on a Maps model whose iCloud upload was measured. */\n syncMeasured: boolean;\n};\n\n/** Whether the app can write this Mac's Maps store, and why not when it cannot. */\nexport type LaneStatus = {\n compatible: boolean;\n modelVersion: string | null;\n syncMeasured: boolean;\n refusal: string | null;\n};\n\n/** Where the place record to copy comes from: an item Maps wrote, by its identifier. */\nexport type PlaceFrom = {\n source: SourceKind;\n sourceId: string;\n /**\n * What the caller searched Maps for. The app shows it as the place's name\n * only when the source has none of its own (a recent), until a device\n * refreshes the place; it never becomes a label.\n */\n query: string;\n /** The caller's own label, only when they gave one: the app saves it as `customName`. */\n name?: string | undefined;\n /** The caller's coordinate, when given: the app refuses a record far from it. */\n near?: { latitude: number; longitude: number } | undefined;\n};\n\nconst isRecord = (v: unknown): v is Record<string, unknown> => typeof v === \"object\" && v !== null;\nconst isStringOrNull = (v: unknown): v is string | null => v === null || typeof v === \"string\";\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Only the keys given: an absent `name` or `near` is left off the wire, not sent as null. */\nconst placeParams = (p: PlaceFrom): Record<string, unknown> => ({\n source: p.source,\n sourceId: p.sourceId,\n query: p.query,\n ...(p.name !== undefined ? { name: p.name } : {}),\n ...(p.near ? { near: { latitude: p.near.latitude, longitude: p.near.longitude } } : {}),\n});\n\n/**\n * Maps' writes, saved by Cupertino.app through Core Data with Maps' own model,\n * so they are recorded in persistent history like a change made in the app.\n *\n * The app does the work and validates every argument; this side only names the\n * method and checks the answer has the shape the tools report. A reply of\n * another shape is a `StoreLaneError` with reason `protocol`, the reason core\n * uses for a reply it cannot read. The same lane as Voice Memos'\n * (`packages/voice-memos/src/client/lane.ts`), on surface `maps`.\n */\nexport class MapsLane {\n readonly #lane: StoreLane;\n\n private constructor(lane: StoreLane) {\n this.#lane = lane;\n }\n\n /**\n * Null when this server is not hosted by Cupertino: see `core/src/store-lane.ts`.\n *\n * Opening connects nothing. Cupertino spawns the server with the lane env just\n * to list its tools, and that listing must never wait on the app.\n */\n static open(env: NodeJS.ProcessEnv = process.env): MapsLane | null {\n const lane = openStoreLane(MAPS_SURFACE, env);\n return lane ? new MapsLane(lane) : null;\n }\n\n close(): void {\n this.#lane.close();\n }\n\n /** A favourite with its own copy of the source's place record. */\n addFavorite(p: PlaceFrom): Promise<LaneWrite> {\n return this.#write(\"maps.addFavorite\", placeParams(p));\n }\n\n removeFavorite(id: string): Promise<LaneWrite> {\n return this.#write(\"maps.removeFavorite\", { id });\n }\n\n /** A saved place in no Guide, with its own copy of the source's place record. */\n savePlace(p: PlaceFrom): Promise<LaneWrite> {\n return this.#write(\"maps.savePlace\", placeParams(p));\n }\n\n removeSavedPlace(id: string): Promise<LaneWrite> {\n return this.#write(\"maps.removeSavedPlace\", { id });\n }\n\n /**\n * File a saved place in a Guide: one already saved, by `placeId`, or one to\n * save first from a source, which the app saves and files in one save.\n */\n fileInGuide(p: { guide: string; placeId: string } | ({ guide: string } & PlaceFrom)) {\n const params =\n \"placeId\" in p\n ? { guide: p.guide, placeId: p.placeId }\n : { guide: p.guide, ...placeParams(p) };\n return this.#write(\"maps.fileInGuide\", params, { filed: true });\n }\n\n async status(): Promise<LaneStatus> {\n const r = await this.#lane.call(\"maps.status\", {});\n if (\n !isRecord(r) ||\n typeof r.compatible !== \"boolean\" ||\n !isStringOrNull(r.modelVersion) ||\n typeof r.syncMeasured !== \"boolean\" ||\n !isStringOrNull(r.refusal)\n ) {\n throw this.#unreadable(\"maps.status\");\n }\n return {\n compatible: r.compatible,\n modelVersion: r.modelVersion,\n syncMeasured: r.syncMeasured,\n refusal: r.refusal,\n };\n }\n\n /**\n * One write, its answer checked. `filed` is required where the method files:\n * the tool reports it, and a missing one must not read as \"not filed\".\n */\n async #write(\n method: string,\n params: Record<string, unknown>,\n want: { filed?: true } = {},\n ): Promise<LaneWrite> {\n const r = await this.#lane.call(method, params);\n if (\n !isRecord(r) ||\n typeof r.id !== \"string\" ||\n !UUID.test(r.id) ||\n !Array.isArray(r.changed) ||\n !r.changed.every((c) => typeof c === \"string\") ||\n typeof r.created !== \"boolean\" ||\n (want.filed\n ? typeof r.filed !== \"boolean\"\n : r.filed !== undefined && typeof r.filed !== \"boolean\") ||\n !isStringOrNull(r.modelVersion) ||\n typeof r.syncMeasured !== \"boolean\"\n ) {\n throw this.#unreadable(method);\n }\n return {\n // Lowercase, as every id read from the store is here: Swift spells uuids in capitals.\n id: r.id.toLowerCase(),\n changed: r.changed as string[],\n created: r.created,\n ...(typeof r.filed === \"boolean\" ? { filed: r.filed } : {}),\n modelVersion: r.modelVersion,\n syncMeasured: r.syncMeasured,\n };\n }\n\n #unreadable(method: string): StoreLaneError {\n return new StoreLaneError(\n MAPS_SURFACE,\n \"protocol\",\n `the reply to ${method} is not the shape this server reads`,\n );\n }\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\n/**\n * How a place is opened in Maps, so Maps mints the place record a write copies.\n *\n * `maps://?q=<query>` goes through LaunchServices, not Apple Events and not\n * Accessibility, and Maps resolves the place and files it in Recents with a\n * full record attached (`place-source.ts`). Injected so tests never launch an\n * application.\n */\nexport type OpenUrl = (url: string) => void | Promise<void>;\n\nexport const defaultOpenUrl: OpenUrl = async (url) => {\n // `-g` so the user's foreground app is not stolen. `timeout` because a wedged\n // LaunchServices would otherwise block forever, and this runs inside a tool\n // call somebody is waiting on. Asynchronous, like the poll that follows it:\n // this is a stdio server, and a synchronous wait here is a server that cannot\n // read its stdin, answer another call or honour a cancellation meanwhile.\n await promisify(execFile)(\"/usr/bin/open\", [\"-g\", url], { timeout: 10_000 });\n};\n","import { DatabaseSync } from \"node:sqlite\";\n\nimport { MapsWriteError } from \"./errors.js\";\nimport { defaultOpenUrl, type OpenUrl } from \"./open-url.js\";\nimport type { EntityKey } from \"./store.js\";\n\n/**\n * Finding a place record for the store lane, without writing anything.\n *\n * The store lane saves through Maps' own Core Data model, and it can only COPY\n * a place record (`ZMIXINMAPITEM.ZMAPITEMSTORAGE`) that Maps minted: the record\n * is a GEO protobuf of one to four kilobytes that nobody here can generate, and\n * on the measured model the lane's saves reach the account's other devices, so\n * a fabricated record would go with them. `docs/maps.md` has the measurements.\n * So before the lane is asked to write, this finds a record to copy and names\n * the item that OWNS it, by that item's `ZIDENTIFIER`, because the lane fetches\n * through the model by uuid, not by row id.\n *\n * Two ways to get one, in order, both kept from the SQL route this package ran\n * until 2026-11-11:\n *\n * 1. A record already in the store within about a metre of the coordinate,\n * owned by a favourite, a saved place or a recent. Costs nothing.\n * 2. Seeding: open `maps://?q=<query>` and poll Recents above a watermark for\n * the record Maps files there, refused when a second place lands there\n * meanwhile. Leaves a Recents entry, which is why the first way is always\n * tried first.\n *\n * Every connection here is read-only, and none is held across the seed: Maps is\n * being asked to write the very row being waited for.\n */\n\n/** The owning item's kind, as the app's Maps writer spells its `SourceKind`. */\nexport type SourceKind = \"favorite\" | \"savedPlace\" | \"recent\";\n\nexport type PlaceSource = {\n kind: SourceKind;\n /** The owning item's `ZIDENTIFIER`, as a lowercase dashed uuid. */\n id: string;\n /** The record's own coordinate, which is Maps' canonical one. */\n latitude: number;\n longitude: number;\n /** True when Maps had to be asked to resolve the place, leaving a Recents entry. */\n seeded: boolean;\n};\n\nconst STORAGE_POLL_MS = 250;\n\n/** A pause that yields the event loop, unlike `Atomics.wait`, which does not. */\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n\n/**\n * Progress, on stderr: stdout carries the MCP protocol. Seeding can take tens\n * of seconds, and a long call that says nothing reads as a hang.\n */\nconst progress = (message: string): void => {\n process.stderr.write(`[apple-maps-mcp] ${message}\\n`);\n};\n\n/**\n * Same doorway: 1e-5 degrees is ~1.1 m of latitude. Close enough that two rows\n * are one place, far enough apart that neighbouring shops are not merged.\n */\nconst NEAR = 1e-5;\n\n/**\n * How far a resolved place may sit from the caller's coordinate: ~250 m. The\n * caller's number and Apple's routinely differ by a building's width, and a\n * search resolves to the entrance rather than the pin.\n */\nconst SEED_TOLERANCE = 2.5e-3;\n\nconst near = (aLat: number, aLon: number, bLat: number, bLon: number): boolean =>\n Math.abs(aLat - bLat) <= SEED_TOLERANCE && Math.abs(aLon - bLon) <= SEED_TOLERANCE;\n\nconst toRad = (deg: number): number => (deg * Math.PI) / 180;\n\n/** Metres between two coordinates, for the error message only. */\nconst haversineMetres = (aLat: number, aLon: number, bLat: number, bLon: number): number => {\n const dLat = toRad(bLat - aLat);\n const dLon = toRad(bLon - aLon);\n const h =\n Math.sin(dLat / 2) ** 2 +\n Math.cos(toRad(aLat)) * Math.cos(toRad(bLat)) * Math.sin(dLon / 2) ** 2;\n return 6_371_000 * 2 * Math.asin(Math.sqrt(h));\n};\n\n/** `HEX(ZIDENTIFIER)` to the dashed lowercase form refs and the lane use. */\nconst uuidOfHex = (hex: unknown): string | null => {\n if (typeof hex !== \"string\") return null;\n const h = hex.toLowerCase();\n if (!/^[0-9a-f]{32}$/.test(h)) return null;\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n};\n\n/**\n * A row's entity, by name.\n *\n * `ZCOLLECTIONITEM` holds both `CollectionPlaceItem` and `CollectionTransitItem`\n * rows, and `ZHISTORYITEM` more than places, so the table alone does not say a\n * row is a saved place or a recent place. A missing entity yields NULL, and a\n * comparison with NULL matches nothing, which is the right answer for a store\n * that has no such entity.\n */\nconst entityIs = (alias: string, name: \"CollectionPlaceItem\" | \"HistoryPlaceItem\"): string =>\n `${alias}.\"Z_ENT\" = (SELECT \"Z_ENT\" FROM \"Z_PRIMARYKEY\" WHERE \"Z_NAME\" = '${name}')`;\n\n/**\n * An identifier the lane can be given: present and the 16 bytes of a uuid. A\n * row without one cannot be named to the lane, which fetches by uuid only.\n */\nconst named = (alias: string): string => `LENGTH(${alias}.\"ZIDENTIFIER\") = 16`;\n\nconst TABLE_OF: Record<\"favorite\" | \"collection-item\" | \"history\", string> = {\n favorite: \"ZFAVORITEITEM\",\n \"collection-item\": \"ZCOLLECTIONITEM\",\n history: \"ZHISTORYITEM\",\n};\n\ntype SourceRow = { kind: SourceKind; hex: string; lat: number; lon: number };\n\n/**\n * A favourite or saved place as it stands in the store, for a tool's answer.\n *\n * The name is the label when the user set one, else the place's own name, as\n * the read tools render it. The coordinate is the item's, else its map\n * item's: a field the store does not hold is null, never the caller's guess.\n */\nexport type StoredPlace = {\n id: string;\n name: string | null;\n latitude: number | null;\n longitude: number | null;\n};\n\nconst num = (v: unknown): number | null => (v === null || v === undefined ? null : Number(v));\nconst str = (v: unknown): string | null => (typeof v === \"string\" ? v : null);\n\nexport class PlaceSourceFinder {\n readonly #path: string;\n readonly #openUrl: OpenUrl;\n readonly #seedTimeoutMs: number;\n\n constructor(opts: { storePath: string; openUrl?: OpenUrl; seedTimeoutMs?: number }) {\n this.#path = opts.storePath;\n this.#openUrl = opts.openUrl ?? defaultOpenUrl;\n this.#seedTimeoutMs = opts.seedTimeoutMs ?? 30_000;\n }\n\n /**\n * A short-lived read-only handle per use. Under WAL a connection that has\n * begun reading holds a snapshot and may not see another process's commits,\n * so a handle is never kept between calls.\n */\n #read<T>(fn: (db: DatabaseSync) => T): T {\n const db = new DatabaseSync(this.#path, { readOnly: true });\n try {\n return fn(db);\n } finally {\n db.close();\n }\n }\n\n /**\n * An existing item in `table` for this place, matched as the SQL route\n * matched favourites: a TIGHT coordinate (~1 m) when both numbers came from Maps, or\n * the NAME plus a LOOSE coordinate (~250 m) for a caller's own coordinate.\n * The name is what makes the loose radius safe: it only merges rows the\n * caller already calls the same thing.\n */\n #existing(\n table: string,\n where: string,\n q: { latitude: number; longitude: number; name?: string | undefined },\n ): StoredPlace | null {\n return this.#read((db) => {\n const select = `SELECT HEX(t.\"ZIDENTIFIER\") AS hex FROM \"${table}\" t\n WHERE ${where} AND ${named(\"t\")}\n AND t.\"ZLATITUDE\" BETWEEN ? AND ? AND t.\"ZLONGITUDE\" BETWEEN ? AND ?`;\n const { latitude: lat, longitude: lon } = q;\n const tight = db\n .prepare(`${select} LIMIT 1`)\n .get(lat - NEAR, lat + NEAR, lon - NEAR, lon + NEAR) as { hex: string } | undefined;\n const row =\n tight ??\n (q.name === undefined\n ? undefined\n : (db\n .prepare(`${select} AND t.\"ZMAPITEMNAME\" = ? LIMIT 1`)\n .get(\n lat - SEED_TOLERANCE,\n lat + SEED_TOLERANCE,\n lon - SEED_TOLERANCE,\n lon + SEED_TOLERANCE,\n q.name,\n ) as { hex: string } | undefined));\n return row ? this.#describeIn(db, table, row.hex) : null;\n });\n }\n\n /** The row with this `HEX(ZIDENTIFIER)` in `table`, described, or null. */\n #describeIn(db: DatabaseSync, table: string, hex: string): StoredPlace | null {\n const id = uuidOfHex(hex);\n if (!id) return null;\n const row = db\n .prepare(\n `SELECT COALESCE(t.\"ZCUSTOMNAME\", t.\"ZMAPITEMNAME\") AS name,\n COALESCE(t.\"ZLATITUDE\", m.\"ZLATITUDE\") AS lat,\n COALESCE(t.\"ZLONGITUDE\", m.\"ZLONGITUDE\") AS lon\n FROM \"${table}\" t LEFT JOIN \"ZMIXINMAPITEM\" m ON m.\"Z_PK\" = t.\"ZMAPITEM\"\n WHERE HEX(t.\"ZIDENTIFIER\") = ? LIMIT 1`,\n )\n .get(hex.toUpperCase()) as { name: unknown; lat: unknown; lon: unknown } | undefined;\n if (!row) return null;\n return { id, name: str(row.name), latitude: num(row.lat), longitude: num(row.lon) };\n }\n\n /**\n * Read back a favourite or saved place by the identifier the lane answered\n * with, so a tool reports the item as it stands rather than what was asked\n * for. Null when no such row is in the store (yet), or `id` is not a uuid.\n */\n describe(kind: \"favorite\" | \"collection-item\", id: string): StoredPlace | null {\n const hex = id.replaceAll(\"-\", \"\").toUpperCase();\n if (!/^[0-9A-F]{32}$/.test(hex)) return null;\n return this.#read((db) => this.#describeIn(db, TABLE_OF[kind], hex));\n }\n\n /** An existing favourite for this place. Idempotence for `add_favorite`. */\n existingFavorite(q: { latitude: number; longitude: number; name?: string }): StoredPlace | null {\n return this.#existing(\"ZFAVORITEITEM\", \"1 = 1\", q);\n }\n\n /** An existing saved place (a `CollectionPlaceItem`) for this place. */\n existingSavedPlace(q: {\n latitude: number;\n longitude: number;\n name?: string;\n }): StoredPlace | null {\n return this.#existing(\"ZCOLLECTIONITEM\", entityIs(\"t\", \"CollectionPlaceItem\"), q);\n }\n\n /**\n * A record already in the store within ~1 m, with an owner the lane can be\n * given. Favourites first, then saved places, then recents: the record is the\n * same object whichever row points at it, so the order only makes the answer\n * deterministic.\n */\n #donorNear(db: DatabaseSync, lat: number, lon: number): SourceRow | null {\n const row = db\n .prepare(\n `WITH near AS (\n SELECT m.\"Z_PK\" AS pk, m.\"ZLATITUDE\" AS lat, m.\"ZLONGITUDE\" AS lon\n FROM \"ZMIXINMAPITEM\" m\n WHERE m.\"ZMAPITEMSTORAGE\" IS NOT NULL\n AND m.\"ZLATITUDE\" BETWEEN ? AND ? AND m.\"ZLONGITUDE\" BETWEEN ? AND ?\n )\n SELECT kind, hex, lat, lon FROM (\n SELECT 0 AS rank, 'favorite' AS kind, HEX(f.\"ZIDENTIFIER\") AS hex, n.lat, n.lon\n FROM near n JOIN \"ZFAVORITEITEM\" f ON f.\"ZMAPITEM\" = n.pk\n WHERE ${named(\"f\")}\n UNION ALL\n SELECT 1, 'savedPlace', HEX(ci.\"ZIDENTIFIER\"), n.lat, n.lon\n FROM near n JOIN \"ZCOLLECTIONITEM\" ci ON ci.\"ZMAPITEM\" = n.pk\n WHERE ${named(\"ci\")} AND ${entityIs(\"ci\", \"CollectionPlaceItem\")}\n UNION ALL\n SELECT 2, 'recent', HEX(h.\"ZIDENTIFIER\"), n.lat, n.lon\n FROM near n JOIN \"ZHISTORYITEM\" h ON h.\"ZMAPITEM\" = n.pk\n WHERE ${named(\"h\")} AND ${entityIs(\"h\", \"HistoryPlaceItem\")}\n )\n ORDER BY rank LIMIT 1`,\n )\n .get(lat - NEAR, lat + NEAR, lon - NEAR, lon + NEAR) as SourceRow | undefined;\n return row ?? null;\n }\n\n /**\n * The recent places carrying a record above a watermark, newest first, two\n * at most: two is enough to tell the seed's own from a second place opened\n * in Maps meanwhile.\n */\n #seededDonors(db: DatabaseSync, sinceHistoryPk: number): SourceRow[] {\n return db\n .prepare(\n `SELECT 'recent' AS kind, HEX(h.\"ZIDENTIFIER\") AS hex,\n m.\"ZLATITUDE\" AS lat, m.\"ZLONGITUDE\" AS lon\n FROM \"ZHISTORYITEM\" h\n JOIN \"ZMIXINMAPITEM\" m ON m.\"Z_PK\" = h.\"ZMAPITEM\"\n WHERE h.\"Z_PK\" > ? AND m.\"ZMAPITEMSTORAGE\" IS NOT NULL\n AND ${named(\"h\")} AND ${entityIs(\"h\", \"HistoryPlaceItem\")}\n ORDER BY h.\"Z_PK\" DESC LIMIT 2`,\n )\n .all(sinceHistoryPk) as SourceRow[];\n }\n\n #maxHistory(db: DatabaseSync): number {\n const row = db.prepare(`SELECT MAX(Z_PK) AS m FROM ZHISTORYITEM`).get() as\n | { m: number | bigint | null }\n | undefined;\n return Number(row?.m ?? 0);\n }\n\n #toSource(row: SourceRow, seeded: boolean): PlaceSource {\n const id = uuidOfHex(row.hex);\n // The SQL admits only 16-byte identifiers, so this cannot fail; the check\n // keeps a malformed row from ever being named to the lane as \"\".\n if (!id) throw new MapsWriteError(\"A place record's owner has no usable identifier.\");\n return {\n kind: row.kind,\n id,\n latitude: Number(row.lat),\n longitude: Number(row.lon),\n seeded,\n };\n }\n\n /**\n * A place record for `query`: one already in the store near the coordinate,\n * else one Maps mints on being asked. Refuses a resolution more than ~250 m\n * from the coordinate given, and a seed that produces nothing in time.\n *\n * Async because the seed can take thirty seconds, and a blocking wait would\n * leave this single-threaded stdio server unable to answer anything.\n */\n async find(q: { query: string; latitude?: number; longitude?: number }): Promise<PlaceSource> {\n const hasCoords = q.latitude !== undefined && q.longitude !== undefined;\n const lat = q.latitude ?? 0;\n const lon = q.longitude ?? 0;\n\n // ── 1. read ──────────────────────────────────────────────────────────────\n progress(`finding a place record for ${JSON.stringify(q.query)}: reading the store`);\n const { donor, watermark } = this.#read((db) => ({\n donor: hasCoords ? this.#donorNear(db, lat, lon) : null,\n watermark: this.#maxHistory(db),\n }));\n if (donor) return this.#toSource(donor, false);\n\n // ── 2. seed, holding nothing ─────────────────────────────────────────────\n // No coordinate in the URL: `?q=<name>` is the form measured to make Maps\n // file a recent with a record. With `&ll=<lat>,<lon>` Maps opened a place\n // card but filed nothing in Recents, so a poll on that form ran to its\n // timeout every time. The coordinate still serves to\n // de-duplicate and to check what Maps resolved; it stays out of the URL.\n const url = `maps://?q=${encodeURIComponent(q.query)}`;\n progress(`asking Maps to resolve ${JSON.stringify(q.query)}…`);\n await this.#openUrl(url);\n progress(`opened, waiting up to ${Math.round(this.#seedTimeoutMs / 1000)}s for a record`);\n const deadline = Date.now() + this.#seedTimeoutMs;\n let landed: SourceRow[] = [];\n let polls = 0;\n while (Date.now() < deadline && landed.length === 0) {\n landed = this.#read((db) => this.#seededDonors(db, watermark));\n if (landed.length === 0) await sleep(STORAGE_POLL_MS);\n polls += 1;\n if (polls % 8 === 0) progress(`still waiting (${polls * (STORAGE_POLL_MS / 1000)}s)…`);\n }\n if (landed.length > 1) {\n // Two places filed since the watermark: the newest need not be the seed's, and with no\n // coordinate nothing else tells them apart. Copying the wrong one would save, and sync,\n // another place.\n throw new MapsWriteError(\n `While Maps resolved ${JSON.stringify(q.query)}, another place was opened in Maps too, ` +\n `so which record is this one's cannot be told. Nothing was saved — try again.`,\n { query: q.query, reason: \"invalid\" },\n );\n }\n const seeded = landed[0] ?? null;\n\n if (!seeded) {\n throw new MapsWriteError(\n `Maps did not produce a place record for \"${q.query}\" within ` +\n `${Math.round(this.#seedTimeoutMs / 1000)}s. Maps must be RUNNING for this to work — ` +\n `it is the only thing that can create a place record. It may also have resolved the ` +\n `query to a search rather than a place, since searches get no record. Try a more ` +\n `specific name, or pass latitude and longitude.`,\n { query: q.query },\n );\n }\n if (hasCoords && !near(Number(seeded.lat), Number(seeded.lon), lat, lon)) {\n // Maps resolved SOMETHING, but not the place asked for. Copying its record\n // would save the wrong place, and the lane's saves reach the account's\n // other devices, so this refuses.\n throw new MapsWriteError(\n `Maps resolved ${JSON.stringify(q.query)} to a place about ` +\n `${Math.round(haversineMetres(Number(seeded.lat), Number(seeded.lon), lat, lon))}m from the coordinate ` +\n `given, so it is probably not the place meant. Nothing was saved — try a more ` +\n `specific name.`,\n { query: q.query },\n );\n }\n progress(`got a place record after ${polls} polls`);\n return this.#toSource(seeded, true);\n }\n\n /**\n * The `ZIDENTIFIER` of the row a read tool's ref names, or null when the row\n * is not there or has no identifier — a row-id-only ref the lane, which\n * fetches by uuid, cannot be given.\n */\n identifierOf(kind: \"favorite\" | \"collection-item\" | \"history\", key: EntityKey): string | null {\n const table = TABLE_OF[kind];\n const [where, param] =\n \"uuid\" in key\n ? [`HEX(\"ZIDENTIFIER\") = ?`, key.uuid.replaceAll(\"-\", \"\").toUpperCase()]\n : [`\"Z_PK\" = ?`, key.rowId];\n return this.#read((db) => {\n const row = db\n .prepare(`SELECT HEX(\"ZIDENTIFIER\") AS hex FROM \"${table}\" WHERE ${where} LIMIT 1`)\n .get(param) as { hex: string | null } | undefined;\n return uuidOfHex(row?.hex);\n });\n }\n}\n","import { AppleAutomationError } from \"@mgcrea/mcp-apple-core\";\n\nimport type { EntityKey } from \"./store.js\";\n\n/**\n * Refs for places and collections.\n *\n * ## Why the ref is not `ZMUID`\n *\n * `ZMUID` is Apple's own place identifier and looks like the better key — it is\n * the same number for the same restaurant across every device. It is not used,\n * for two measured reasons recorded in `docs/maps.md`:\n *\n * * It is populated **20 of 23** favourites. The three without it are the\n * rows that have no linked place at all, but a ref scheme that cannot\n * address three rows in twenty-three is not a ref scheme.\n * * It identifies a PLACE, not an entry. The same café saved as a favourite\n * AND filed in a collection carries one `ZMUID` across both, so a ref built\n * on it could not say which of the two a caller meant.\n *\n * The keys below address the ENTRY, which is what every tool here returns. The\n * kind is carried in the prefix so a favourite ref and a collection-item ref\n * can never be confused for one another.\n *\n * ## What the ref carries: a uuid when the store has one, a row id when it does not\n *\n * `ZIDENTIFIER` — a 16-byte Core Data UUID — is set on every favourite,\n * collection, collection item and recent on a real store, and is distinct on\n * every one. It addresses the ENTRY, survives a delete elsewhere in the table,\n * and survives an iCloud re-sync renumbering rows. It is the ref whenever\n * `store.ts` can confirm total coverage.\n *\n * It was found by watching Maps write, not by reading the schema — see\n * `docs/maps.md`. The read probe never reported it, because a probe can only\n * report columns it thought to look for.\n *\n * When a store has no usable identifier the ref falls back to the Core Data row\n * id, and then the old caveat applies in full: `Z_PK` is reused after a delete\n * and renumbered by a re-sync, so such a ref is only good for the session.\n * `packages/messages` rejected row ids outright for that reason; here they are\n * the degraded mode rather than the design.\n *\n * The two are told apart BY SHAPE — a uuid is 32 hex characters, a row id is\n * decimal — and the resolver refuses to try a uuid against a store with no\n * identifier column rather than reinterpreting it as a number. Silently\n * resolving one key space in the other would find a real but wrong place, which\n * is worse than finding nothing.\n *\n * ## Why `p1:` and `pc1:`\n *\n * `c1:` is Calendar's, `r1:` Reminders', `k1:` Contacts', `n1:` Notes',\n * `m1:`/`mc1:` Messages', `s1:`/`sb1:` Safari's. A ref that decodes under two\n * surfaces is worse than one that decodes under none, so each prefix is claimed\n * once and the version digit keeps a future change additive rather than a\n * silent reinterpretation of refs already sitting in a conversation.\n */\n\nexport const PLACE_REF_VERSION = \"p1\";\nexport const COLLECTION_REF_VERSION = \"pc1\";\n\n/** The entity a place ref points into. Carried in the ref, never guessed. */\nexport type PlaceKind = \"favorite\" | \"collection-item\" | \"history\";\n\nconst KIND_CODE: Record<PlaceKind, string> = {\n favorite: \"f\",\n \"collection-item\": \"c\",\n history: \"h\",\n};\nconst CODE_KIND: Record<string, PlaceKind> = {\n f: \"favorite\",\n c: \"collection-item\",\n h: \"history\",\n};\n\nconst PLACE_PATTERN = /^p1:([fch]):([0-9a-f]{32}|\\d+)$/;\nconst COLLECTION_PATTERN = /^pc1:([0-9a-f]{32}|\\d+)$/;\n\n/** 32 hex characters is a uuid; anything else that matched the pattern is a row id. */\nconst toKey = (raw: string): EntityKey =>\n /^[0-9a-f]{32}$/.test(raw)\n ? {\n uuid: `${raw.slice(0, 8)}-${raw.slice(8, 12)}-${raw.slice(12, 16)}-${raw.slice(16, 20)}-${raw.slice(20)}`,\n }\n : { rowId: Number(raw) };\n\n/** A uuid goes into the ref undashed, so the ref stays one opaque token. */\nconst fromKey = (key: EntityKey): string =>\n \"uuid\" in key ? key.uuid.replaceAll(\"-\", \"\").toLowerCase() : String(key.rowId);\n\nconst otherSurface = (raw: string): string => {\n if (raw.startsWith(\"c1:\")) return \" That one is a Calendar event ref.\";\n if (raw.startsWith(\"r1:\")) return \" That one is a Reminders ref.\";\n if (raw.startsWith(\"k1:\")) return \" That one is a Contacts ref.\";\n if (raw.startsWith(\"n1:\")) return \" That one is a Notes ref.\";\n if (raw.startsWith(\"mc1:\")) return \" That one is a Messages chat ref.\";\n if (raw.startsWith(\"m1:\")) return \" That one is a Messages message ref.\";\n if (raw.startsWith(\"sb1:\")) return \" That one is a Safari bookmark ref.\";\n if (raw.startsWith(\"s1:\")) return \" That one is a Safari history ref.\";\n if (raw.startsWith(\"pc1:\")) return \" That one is a COLLECTION ref — this wants a place ref.\";\n if (raw.startsWith(\"p1:\")) return \" That one is a PLACE ref — this wants a collection ref.\";\n return \"\";\n};\n\nexport class InvalidMapsRefError extends AppleAutomationError {\n override readonly name = \"InvalidMapsRefError\";\n\n constructor(raw: string, want: \"place\" | \"collection\") {\n const shape = want === \"place\" ? '\"p1:<kind>:<id>\"' : '\"pc1:<id>\"';\n super(\n `\"${raw}\" is not a ${want} ref. Refs come from apple_maps_* results and look like ` +\n `${shape} — they are opaque and must not be constructed by hand.${otherSurface(raw)}`,\n { ref: raw },\n );\n }\n}\n\nexport const encodePlaceRef = (kind: PlaceKind, key: EntityKey): string =>\n `${PLACE_REF_VERSION}:${KIND_CODE[kind]}:${fromKey(key)}`;\n\nexport const encodeCollectionRef = (key: EntityKey): string =>\n `${COLLECTION_REF_VERSION}:${fromKey(key)}`;\n\nexport const decodePlaceRef = (raw: string): { kind: PlaceKind; key: EntityKey } => {\n const m = PLACE_PATTERN.exec(raw.trim());\n const kind = m?.[1] ? CODE_KIND[m[1]] : undefined;\n if (!m?.[2] || !kind) throw new InvalidMapsRefError(raw, \"place\");\n return { kind, key: toKey(m[2]) };\n};\n\nexport const decodeCollectionRef = (raw: string): EntityKey => {\n const m = COLLECTION_PATTERN.exec(raw.trim());\n if (!m?.[1]) throw new InvalidMapsRefError(raw, \"collection\");\n return toKey(m[1]);\n};\n","import type { DatabaseSync } from \"node:sqlite\";\n\nimport {\n columnsOf,\n escapeLike,\n fingerprintSchema,\n openReadOnly,\n SchemaDriftError,\n type Logger,\n type ReadOnlyMode,\n} from \"@mgcrea/mcp-apple-core\";\n\nimport { resolveEpoch, type Epoch } from \"./dates.js\";\n\n/**\n * Maps' file lane. There is no other lane.\n *\n * ## What is measured, and what is NOT\n *\n * MEASURED by `pnpm probe:maps` on macOS 26.6 — 146 schema objects, fingerprint\n * `2bbc03143125`, Core Data, `ZCREATETIME` on apple-seconds:\n *\n * ZFAVORITEITEM 24 rows ZCOLLECTION 10 rows\n * ZCOLLECTIONITEM 30 rows ZHISTORYITEM 34 rows\n * ZMIXINMAPITEM 71 rows ZREVIEWEDPLACE 24 rows\n *\n * and the id bridge, verified by running the join rather than by reading column\n * names: `ZMIXINMAPITEM`'s inverse relationships partition exactly —\n * 30 collection items + 21 favourites + 20 history rows = 71 = every row.\n *\n * NOT measured: this file has never been run against the real store by its\n * author, who has no Full Disk Access. Everything below is written against a\n * probe REPORT, which is one step further from the data than\n * `packages/safari/src/client/store.ts` was, and that file already treats every\n * column as optional. This one goes further in two ways.\n *\n * ## Columns are resolved BY COVERAGE, not by first name match\n *\n * The probe found `ZHISTORYITEM` carrying both `ZLATITUDE` (1 of 33 rows) and\n * `ZLATITUDE1` (19 of 33). A resolver that took the first candidate it\n * recognised would pick the column that is null 97% of the time and report that\n * Maps holds almost no coordinates. So each logical field names several\n * candidates and the one with the **most non-null values** wins, counted at\n * open time. That is a real query per candidate, run once, on tables of tens of\n * rows.\n *\n * ## Collection membership is a JOIN TABLE, and it is VALIDATED not guessed\n *\n * MEASURED: membership is `Z_6PLACES(Z_6COLLECTIONS, Z_7PLACES)`, a Core Data\n * many-to-many. `Z_PRIMARYKEY` decodes ordinal 6 as Collection and 7 as\n * CollectionItem, so the relationship is `Collection.places`.\n *\n * Four column names were guessed here before it was found — ZCOLLECTION,\n * ZCOLLECTION1, ZPARENTCOLLECTION, ZOWNINGCOLLECTION — and the store has none\n * of them, so every guide listed empty. A many-to-many leaves NO COLUMN on\n * either entity, so no list of column names could have contained the answer.\n * The near-miss is what makes this worth stating: `ZCOLLECTIONITEM.ZMAPITEM`\n * joins `ZCOLLECTION` for 3 of 10 collections, and a resolver picking the\n * best-covered joinable column would have chosen it and been confidently wrong.\n *\n * So membership is resolved BY RUNNING THE JOIN and scoring it against an\n * oracle the store hands over for free: `ZCOLLECTION.ZPLACESCOUNT`, Maps' own\n * count per guide. A candidate is accepted only when it reproduces all ten\n * numbers exactly with no key pointing at a missing collection. That survives\n * Apple renaming the relationship, which a hard-coded `Z_6PLACES` would not.\n *\n * The oracle is not independent evidence, and it is stronger for it. Core Data\n * maintains `ZPLACESCOUNT` with a trigger that reads:\n *\n * UPDATE ZCOLLECTION SET ZPLACESCOUNT =\n * (SELECT IFNULL(COUNT(Z_6COLLECTIONS), 0)\n * FROM Z_6PLACES WHERE Z_6COLLECTIONS = NEW.Z_PK)\n *\n * so Apple's own schema states the relationship this resolver re-derives. The\n * count match is therefore guaranteed for the true mechanism rather than lucky,\n * and coincidental for anything else. The triggers are visible only in the\n * captured fixture — `pnpm probe:maps --write` omits them from the replay\n * because they call Core Data's private SQLite functions, which is recorded in\n * `writeFixture`.\n *\n * Because it is many-to-many, one place can sit in several guides, and the\n * membership query uses `IN (SELECT ...)` rather than a JOIN so a place in two\n * guides is not returned twice from one of them.\n *\n * MEASURED: 30 item rows, 18 of them in a guide. The other 12 belong to no\n * collection at all; all 30 link to a `ZMIXINMAPITEM`, so they are intact\n * places rather than broken rows.\n *\n * `SchemaDriftError` fires for exactly one condition — none of the three\n * place-bearing tables exists — because without them there is no surface.\n * Everything else is a capability downgrade that is reported, never a throw.\n */\n\nexport const FAVORITES_TABLE = \"ZFAVORITEITEM\";\nexport const COLLECTIONS_TABLE = \"ZCOLLECTION\";\nexport const COLLECTION_ITEMS_TABLE = \"ZCOLLECTIONITEM\";\nexport const HISTORY_TABLE = \"ZHISTORYITEM\";\nexport const MAP_ITEMS_TABLE = \"ZMIXINMAPITEM\";\n\n/**\n * Candidates per logical field, best-known first — but order only breaks ties.\n * Coverage decides. See the header.\n */\nconst NAME_CANDIDATES = [\"ZMAPITEMNAME\", \"ZCUSTOMNAME\", \"ZLOCATIONDISPLAY\", \"ZTITLE\"] as const;\nconst LAT_CANDIDATES = [\"ZLATITUDE\", \"ZLATITUDE1\"] as const;\nconst LON_CANDIDATES = [\"ZLONGITUDE\", \"ZLONGITUDE1\"] as const;\nconst ADDRESS_CANDIDATES = [\"ZMAPITEMADDRESS\", \"ZORIGINATINGADDRESSSTRING\"] as const;\nconst MUID_CANDIDATES = [\"ZMUID\"] as const;\nconst MAP_ITEM_FK_CANDIDATES = [\"ZMAPITEM\"] as const;\nconst CREATED_CANDIDATES = [\"ZCREATETIME\"] as const;\nconst MODIFIED_CANDIDATES = [\"ZMODIFICATIONTIME\"] as const;\nconst COLLECTION_TITLE_CANDIDATES = [\"ZTITLE\", \"ZNAME\", \"ZCUSTOMNAME\"] as const;\n\n/**\n * The stable per-entry identifier, if this store has one.\n *\n * FOUND BY WATCHING MAPS WRITE, not by reading the schema: every row Maps\n * created during `pnpm probe:maps-write` carried `ZIDENTIFIER`, a 16-byte blob\n * — a UUID. It is not in the read probe's report because that probe only looked\n * for columns it already had candidates for, which is a good argument for\n * diffing a live write even when the read surface already works.\n *\n * `ZORIGINALIDENTIFIER` is deliberately NOT a candidate. It exists on\n * `ZCOLLECTIONITEM` and is populated on 3 rows of 30 — it records where an entry\n * was copied FROM, so it is neither complete nor unique to the entry.\n */\nconst IDENTIFIER_CANDIDATES = [\"ZIDENTIFIER\"] as const;\n\n/**\n * Maps' own count of the places in a guide, and the oracle every membership\n * candidate is scored against. See the header.\n */\nconst COLLECTION_COUNT_COLUMN = \"ZPLACESCOUNT\";\n\n/** Core Data's own tables, which are never a relationship. */\nconst RESERVED_JOIN_TABLES = new Set([\"Z_METADATA\", \"Z_MODELCACHE\", \"Z_PRIMARYKEY\"]);\n\nexport type FieldMap = {\n /**\n * The column holding a stable UUID, or null when this store has none good\n * enough to address rows by. See `resolveIdentifier`.\n */\n identifier: string | null;\n name: string | null;\n customName: string | null;\n latitude: string | null;\n longitude: string | null;\n address: string | null;\n muid: string | null;\n mapItem: string | null;\n created: string | null;\n modified: string | null;\n};\n\nexport type EntityFacts = {\n table: string;\n present: boolean;\n rows: number;\n columns: Set<string>;\n fields: FieldMap;\n};\n\n/**\n * How an item says which collection it is in, once proved against the oracle.\n *\n * Two shapes because Core Data has two: a scalar foreign key named after the\n * relationship, and a `Z_<ordinal><RELATIONSHIP>` join table for a\n * many-to-many. THIS store uses the second. Both are carried because the\n * resolver proves whichever is there rather than assuming, and a store that\n * changes shape should degrade rather than read the wrong column.\n */\nexport type CollectionMembership =\n | { kind: \"column\"; column: string }\n | { kind: \"joinTable\"; table: string; collectionColumn: string; itemColumn: string };\n\nexport type StoreCapabilities = {\n fingerprint: string;\n tables: string[];\n favorites: EntityFacts;\n collections: EntityFacts;\n collectionItems: EntityFacts;\n history: EntityFacts;\n mapItems: EntityFacts;\n /**\n * The proved membership mechanism, or null when nothing reproduced\n * `ZPLACESCOUNT` and collections must therefore list without their places.\n */\n membership: CollectionMembership | null;\n /**\n * The membership mechanism as one short string, for diagnostics.\n *\n * Kept because `apple_maps_diagnostics` reported `collectionFk` before this\n * was understood, and a field that silently changes meaning is worse than one\n * that widens: it now names a join table as well as a column.\n */\n collectionFk: string | null;\n epoch: Epoch;\n};\n\nexport type PlaceRow = {\n id: number;\n /**\n * The stable identifier, when the store has one. Null means refs on this\n * entity fall back to the row id and are only good for the session.\n */\n uuid: string | null;\n name: string | null;\n customName: string | null;\n latitude: number | null;\n longitude: number | null;\n address: string | null;\n /**\n * Apple's place id, carried as a STRING.\n *\n * MEASURED on a real store: `-2679868148951248105`. It is a 64-bit integer and\n * `node:sqlite` THROWS on one past `Number.MAX_SAFE_INTEGER` rather than\n * truncating, so reading it as a number failed the whole listing with\n * \"Value is too large to be represented as a JavaScript number\" — one column\n * taking down every favourite. `docs/surfaces.md` states the rule this broke:\n * read such columns as BigInt or `CAST(... AS TEXT)`.\n *\n * The fixture used a small id, so the offline suite passed. Only the real\n * store has ids of this size.\n */\n muid: string | null;\n createdRaw: number | null;\n modifiedRaw: number | null;\n /**\n * False when the row has no linked `ZMIXINMAPITEM`.\n *\n * MEASURED: 3 of 23 favourites, and they carry no name and no coordinate\n * either. Almost certainly the unconfigured Home / Work / School slots that\n * Maps creates whether or not anyone fills them in. They are RETURNED rather\n * than filtered, with this flag, because silently dropping rows is how a\n * caller concludes a favourite was deleted.\n */\n linked: boolean;\n};\n\nexport type CollectionRow = {\n id: number;\n uuid: string | null;\n title: string | null;\n placesCount: number | null;\n createdRaw: number | null;\n modifiedRaw: number | null;\n};\n\n/**\n * How a caller addresses one row.\n *\n * Two shapes rather than one because the store decides which is available, not\n * the caller: a store whose `ZIDENTIFIER` is complete gets durable refs, one\n * without falls back to row ids. Making the difference explicit in the type\n * means a resolver cannot quietly treat a row id as a uuid when the store\n * changed underneath it.\n */\nexport type EntityKey = { uuid: string } | { rowId: number };\n\nconst isRealTable = (name: string): boolean => !name.startsWith(\"sqlite_\");\n\n/**\n * `HEX()` of a 16-byte blob to a canonical UUID.\n *\n * Returns null on anything that is not exactly 32 hex characters. Core Data\n * stores a UUID attribute as 16 raw bytes, so a different length means the\n * column is not what this code thinks it is — and a malformed ref that still\n * looks ref-shaped would be resolved against the wrong row rather than rejected.\n */\nconst toUuid = (hex: unknown): string | null => {\n if (hex === null || hex === undefined) return null;\n const h = String(hex).toLowerCase();\n if (!/^[0-9a-f]{32}$/.test(h)) return null;\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n};\n\n/** A `NULL AS alias` column reads back as null; every other value is coerced. */\nconst num = (v: unknown): number | null =>\n v === null || v === undefined ? null : Number(v as number);\nconst str = (v: unknown): string | null =>\n v === null || v === undefined ? null : String(v as string);\n\n/**\n * Pick the candidate column with the most non-null values.\n *\n * Returns null when none of the candidates exists, and also when they all exist\n * and are all empty — an all-null column is not a usable field, and reporting\n * one as resolved would produce a result whose every value is null with no\n * explanation.\n */\nconst resolveField = (\n db: DatabaseSync,\n table: string,\n columns: Set<string>,\n candidates: readonly string[],\n rows: number,\n): string | null => {\n const present = candidates.filter((c) => columns.has(c));\n if (present.length === 0) return null;\n if (rows === 0) return present[0] ?? null;\n let best: { name: string; count: number } | null = null;\n for (const name of present) {\n let count = 0;\n try {\n // COUNT() is always small. The VALUES are not — see PlaceRow.muid — so\n // nothing here ever selects the column itself.\n count = Number(\n (\n db.prepare(`SELECT COUNT(\"${name}\") AS c FROM \"${table}\"`).get() as {\n c: number | bigint;\n }\n ).c,\n );\n } catch {\n continue;\n }\n if (!best || count > best.count) best = { name, count };\n }\n return best && best.count > 0 ? best.name : (present[0] ?? null);\n};\n\n/**\n * The identifier column, but ONLY if it can actually carry every ref.\n *\n * Coverage is not enough here, and this is the difference between a fix and a\n * trap. A column populated on the rows Maps has written lately and null on the\n * ones that predate it would work perfectly for every place the user saves from\n * now on and fail silently for the places they already had — the failure mode\n * hardest to notice and worst to hit, since the older entries are the ones a\n * person is most likely to ask about.\n *\n * So the bar is TOTAL: set on every row, and distinct across every row. Anything\n * less returns null and the store falls back to `Z_PK`, which is worse but\n * uniformly worse. Measured on a real store: 24/24 favourites, 30/30 collection\n * items, 10/10 collections, 33/33 recents, all distinct.\n */\nconst resolveIdentifier = (\n db: DatabaseSync,\n table: string,\n columns: Set<string>,\n rows: number,\n): string | null => {\n const present = IDENTIFIER_CANDIDATES.filter((c) => columns.has(c));\n if (present.length === 0 || rows === 0) return null;\n for (const name of present) {\n try {\n const r = db\n .prepare(\n `SELECT COUNT(\"${name}\") AS nset, COUNT(DISTINCT \"${name}\") AS ndistinct FROM \"${table}\"`,\n )\n .get() as { nset: number | bigint; ndistinct: number | bigint };\n if (Number(r.nset) === rows && Number(r.ndistinct) === rows) return name;\n } catch {\n continue;\n }\n }\n return null;\n};\n\nconst countRows = (db: DatabaseSync, table: string): number => {\n try {\n return Number(\n (db.prepare(`SELECT COUNT(*) AS c FROM \"${table}\"`).get() as { c: number | bigint }).c,\n );\n } catch {\n return 0;\n }\n};\n\nconst describeEntity = (\n db: DatabaseSync,\n table: string,\n tables: string[],\n nameCandidates: readonly string[] = NAME_CANDIDATES,\n): EntityFacts => {\n const present = tables.includes(table);\n if (!present) {\n return {\n table,\n present: false,\n rows: 0,\n columns: new Set(),\n fields: {\n identifier: null,\n name: null,\n customName: null,\n latitude: null,\n longitude: null,\n address: null,\n muid: null,\n mapItem: null,\n created: null,\n modified: null,\n },\n };\n }\n const columns = new Set(columnsOf(db, table));\n const rows = countRows(db, table);\n const pick = (cands: readonly string[]): string | null =>\n resolveField(db, table, columns, cands, rows);\n return {\n table,\n present,\n rows,\n columns,\n fields: {\n identifier: resolveIdentifier(db, table, columns, rows),\n name: pick(nameCandidates),\n // Always named directly: it is the user's own label and must never be\n // confused with the place's name, even when it wins on coverage.\n customName: columns.has(\"ZCUSTOMNAME\") ? \"ZCUSTOMNAME\" : null,\n latitude: pick(LAT_CANDIDATES),\n longitude: pick(LON_CANDIDATES),\n address: pick(ADDRESS_CANDIDATES),\n muid: pick(MUID_CANDIDATES),\n mapItem: pick(MAP_ITEM_FK_CANDIDATES),\n created: pick(CREATED_CANDIDATES),\n modified: pick(MODIFIED_CANDIDATES),\n },\n };\n};\n\n/**\n * Maps' own places-per-guide, keyed by collection row id.\n *\n * Null when the store has no `ZPLACESCOUNT`, which changes what the resolver\n * below is allowed to accept — see `resolveMembership`.\n */\nconst declaredCounts = (db: DatabaseSync, collections: EntityFacts): Map<number, number> | null => {\n if (!collections.present || !collections.columns.has(COLLECTION_COUNT_COLUMN)) return null;\n try {\n const rows = db\n .prepare(`SELECT \"Z_PK\" AS pk, \"${COLLECTION_COUNT_COLUMN}\" AS n FROM \"${collections.table}\"`)\n .all() as { pk: number | bigint; n: number | bigint | null }[];\n return new Map(rows.map((r) => [Number(r.pk), Number(r.n ?? 0)]));\n } catch {\n return null;\n }\n};\n\n/**\n * Group a candidate's keys and count the items under each.\n *\n * Keys are read as TEXT because `ZMUID` is an INTEGER column holding 64-bit\n * place ids, and `node:sqlite` THROWS on those rather than truncating — reading\n * raw would drop the candidate into a catch instead of rejecting it on the\n * evidence. See `PlaceRow.muid`.\n */\nconst tally = (db: DatabaseSync, sql: string): Map<number, number> => {\n try {\n const rows = db.prepare(sql).all() as { pk: string | null; n: number | bigint }[];\n return new Map(\n rows.filter((r) => r.pk !== null).map((r) => [Number(r.pk), Number(r.n)] as const),\n );\n } catch {\n return new Map();\n }\n};\n\n/**\n * Does this candidate reproduce Maps' own counts, exactly, for every guide?\n *\n * Exactness is the whole test. `ZCOLLECTIONITEM.ZMAPITEM` matches 3 of 10\n * collections by coincidence, so \"mostly right\" is precisely the answer that\n * must be rejected. A key pointing at no collection at all (`unknown`) is\n * disqualifying for the same reason.\n */\nconst reproducesCounts = (declared: Map<number, number>, tallies: Map<number, number>): boolean => {\n for (const pk of tallies.keys()) if (!declared.has(pk)) return false;\n for (const [pk, n] of declared) if ((tallies.get(pk) ?? 0) !== n) return false;\n return true;\n};\n\n/**\n * Find how an item belongs to a collection, by running each candidate join.\n *\n * Scalar columns are tried before join tables only so the cheaper query runs\n * first; the verdict does not depend on order, because a candidate is accepted\n * only when it reproduces every count. When several would qualify the first is\n * taken, and that ambiguity cannot arise on a store whose counts are distinct.\n *\n * WITHOUT the oracle the bar changes rather than disappearing: a single join\n * table whose every key resolves on both sides is accepted, and anything\n * ambiguous is refused. That is weaker evidence, and it is the reason the\n * result is reported to callers rather than assumed.\n */\nconst resolveMembership = (\n db: DatabaseSync,\n collectionItems: EntityFacts,\n collections: EntityFacts,\n tables: string[],\n): CollectionMembership | null => {\n if (!collectionItems.present || !collections.present) return null;\n const declared = declaredCounts(db, collections);\n\n if (declared) {\n for (const column of collectionItems.columns) {\n if ([\"Z_PK\", \"Z_ENT\", \"Z_OPT\"].includes(column)) continue;\n const tallies = tally(\n db,\n `SELECT CAST(t.\"${column}\" AS TEXT) AS pk, COUNT(*) AS n FROM \"${collectionItems.table}\" t\n WHERE t.\"${column}\" IS NOT NULL GROUP BY t.\"${column}\"`,\n );\n if (tallies.size > 0 && reproducesCounts(declared, tallies))\n return { kind: \"column\", column };\n }\n }\n\n const joinTables = tables.filter((t) => t.startsWith(\"Z_\") && !RESERVED_JOIN_TABLES.has(t));\n const accepted: CollectionMembership[] = [];\n for (const table of joinTables) {\n const columns = columnsOf(db, table);\n // Both orientations: the column names do not say which side is which, and\n // reading `Z_6COLLECTIONS` as the collection side is an inference, not a\n // fact. On the real store the wrong orientation scores 3 of 10.\n for (const collectionColumn of columns) {\n for (const itemColumn of columns) {\n if (collectionColumn === itemColumn) continue;\n const tallies = tally(\n db,\n `SELECT CAST(j.\"${collectionColumn}\" AS TEXT) AS pk, COUNT(*) AS n FROM \"${table}\" j\n JOIN \"${collectionItems.table}\" t ON t.\"Z_PK\" = j.\"${itemColumn}\"\n GROUP BY j.\"${collectionColumn}\"`,\n );\n if (tallies.size === 0) continue;\n if (declared) {\n if (reproducesCounts(declared, tallies))\n return { kind: \"joinTable\", table, collectionColumn, itemColumn };\n continue;\n }\n // No oracle: demand that every key on both sides resolves to a real row.\n const orphaned = tally(\n db,\n `SELECT CAST(j.\"${collectionColumn}\" AS TEXT) AS pk, COUNT(*) AS n FROM \"${table}\" j\n LEFT JOIN \"${collections.table}\" c ON c.\"Z_PK\" = j.\"${collectionColumn}\"\n WHERE c.\"Z_PK\" IS NULL GROUP BY j.\"${collectionColumn}\"`,\n );\n if (orphaned.size === 0)\n accepted.push({ kind: \"joinTable\", table, collectionColumn, itemColumn });\n }\n }\n }\n // Exactly one unambiguous reading, or nothing. Two candidates mean the\n // evidence does not distinguish them, and picking one would be a guess.\n return accepted.length === 1 ? (accepted[0] ?? null) : null;\n};\n\n/** The mechanism as one short string, for diagnostics. */\nconst describeMembership = (m: CollectionMembership | null): string | null => {\n if (!m) return null;\n return m.kind === \"column\" ? m.column : `${m.table}(${m.collectionColumn}, ${m.itemColumn})`;\n};\n\nexport const introspect = (db: DatabaseSync, now: number = Date.now()): StoreCapabilities => {\n const tables = (\n db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name`).all() as {\n name: string;\n }[]\n )\n .map((r) => r.name)\n .filter(isRealTable);\n\n const favorites = describeEntity(db, FAVORITES_TABLE, tables);\n const collectionItems = describeEntity(db, COLLECTION_ITEMS_TABLE, tables);\n const history = describeEntity(db, HISTORY_TABLE, tables);\n\n if (!favorites.present && !collectionItems.present && !history.present) {\n throw new SchemaDriftError(\n `Maps' store has none of \"${FAVORITES_TABLE}\", \"${COLLECTION_ITEMS_TABLE}\" or ` +\n `\"${HISTORY_TABLE}\" (found: ${tables.join(\", \") || \"nothing\"}). This is either not a ` +\n `MapsSync store or Apple has restructured it. Nothing can be read from it.`,\n );\n }\n\n const collections = describeEntity(db, COLLECTIONS_TABLE, tables, COLLECTION_TITLE_CANDIDATES);\n const mapItems = describeEntity(db, MAP_ITEMS_TABLE, tables);\n\n const membership = resolveMembership(db, collectionItems, collections, tables);\n\n // The epoch comes from whichever place table has the most rows and a created\n // column — one measurement for the whole store, since every entity is written\n // by the same framework.\n const dated = [favorites, collectionItems, history, mapItems]\n .filter((e) => e.present && e.rows > 0 && e.fields.created)\n .toSorted((a, b) => b.rows - a.rows)[0];\n let maxCreated: number | null = null;\n if (dated?.fields.created) {\n try {\n maxCreated = (\n db\n .prepare(`SELECT MAX(CAST(\"${dated.fields.created}\" AS REAL)) AS m FROM \"${dated.table}\"`)\n .get() as { m: number | null }\n ).m;\n } catch {\n maxCreated = null;\n }\n }\n\n return {\n fingerprint: fingerprintSchema(db),\n tables,\n favorites,\n collections,\n collectionItems,\n history,\n mapItems,\n membership,\n collectionFk: describeMembership(membership),\n epoch: resolveEpoch(maxCreated, now),\n };\n};\n\nexport class MapsStore {\n readonly db: DatabaseSync;\n readonly caps: StoreCapabilities;\n readonly path: string;\n readonly mode: ReadOnlyMode;\n\n constructor(opts: {\n db: DatabaseSync;\n caps: StoreCapabilities;\n path: string;\n mode: ReadOnlyMode;\n }) {\n this.db = opts.db;\n this.caps = opts.caps;\n this.path = opts.path;\n this.mode = opts.mode;\n }\n\n /**\n * One column, or `NULL` under the same alias when it could not be resolved.\n *\n * The same guard `packages/safari` uses, and needed more here: this schema was\n * read from a probe report rather than from the database, so a wrong\n * expectation should cost one field instead of the whole lane.\n */\n #col(column: string | null, alias: string, table = \"t\"): string {\n return column ? `${table}.\"${column}\" AS ${alias}` : `NULL AS ${alias}`;\n }\n\n /**\n * The same, for a column whose value may not fit in a JS double.\n *\n * SQLite holds 64-bit integers; a JS number holds 53 bits of them, and\n * `node:sqlite` refuses rather than silently losing precision. Casting in SQL\n * keeps the exact value and moves the decision about what to do with it out\n * of the driver.\n */\n #colText(column: string | null, alias: string, table = \"t\"): string {\n return column ? `CAST(${table}.\"${column}\" AS TEXT) AS ${alias}` : `NULL AS ${alias}`;\n }\n\n #placeSelect(e: EntityFacts): string {\n const f = e.fields;\n return [\n `t.\"Z_PK\" AS id`,\n f.identifier ? `HEX(t.\"${f.identifier}\") AS uuid` : `NULL AS uuid`,\n this.#col(f.name, \"name\"),\n this.#col(f.customName, \"customName\"),\n this.#col(f.latitude, \"latitude\"),\n this.#col(f.longitude, \"longitude\"),\n this.#col(f.address, \"address\"),\n this.#colText(f.muid, \"muid\"),\n this.#col(f.created, \"createdRaw\"),\n this.#col(f.modified, \"modifiedRaw\"),\n f.mapItem ? `t.\"${f.mapItem}\" AS mapItem` : `NULL AS mapItem`,\n ].join(\", \");\n }\n\n #toPlace(r: Record<string, unknown>): PlaceRow {\n return {\n id: Number(r.id),\n uuid: toUuid(r.uuid),\n name: str(r.name),\n customName: str(r.customName),\n latitude: num(r.latitude),\n longitude: num(r.longitude),\n address: str(r.address),\n // MEASURED on a real store: 12 of 20 linked favourites carry ZMUID = 0.\n // Zero is a sentinel for \"no Apple place id\", not an id, and reporting it\n // as one invites a caller to treat two unrelated places as the same\n // place. Only 8 of the 20 have a real id, and all 8 are 19 digits.\n muid:\n r.muid === null || r.muid === undefined || String(r.muid) === \"0\" ? null : String(r.muid),\n createdRaw: num(r.createdRaw),\n modifiedRaw: num(r.modifiedRaw),\n linked: r.mapItem !== null && r.mapItem !== undefined,\n };\n }\n\n #entityFor(kind: \"favorite\" | \"collection-item\" | \"history\"): EntityFacts {\n if (kind === \"favorite\") return this.caps.favorites;\n if (kind === \"collection-item\") return this.caps.collectionItems;\n return this.caps.history;\n }\n\n /**\n * Items belonging to no collection at all, or null when unanswerable.\n *\n * MEASURED: 30 collection items, 18 filed in a guide, 12 in none — and Core\n * Data has deleted nothing (`Z_PRIMARYKEY.Z_MAX` equals the live count for\n * both `Collection` and `CollectionItem`), so these are not the debris of\n * removed guides. 7 of the 12 appear nowhere else in the store: not as a\n * favourite, not in another guide, not in recents. They are places the user\n * saved that no other tool can reach.\n *\n * `NOT IN` needs the null guard. A subquery yielding a single NULL makes\n * `NOT IN` false for EVERY row, so the filter would silently return nothing\n * and read as \"you have no unfiled places\" — the failure this whole surface\n * keeps having to design against.\n */\n #unfiledClause(): string | null {\n const m = this.caps.membership;\n if (!m) return null;\n if (m.kind === \"column\") return `t.\"${m.column}\" IS NULL`;\n return (\n `t.\"Z_PK\" NOT IN (SELECT j.\"${m.itemColumn}\" FROM \"${m.table}\" j ` +\n `WHERE j.\"${m.itemColumn}\" IS NOT NULL)`\n );\n }\n\n /** How many collection items are filed in no collection; null when unknown. */\n unfiledCount(): number | null {\n const e = this.caps.collectionItems;\n const clause = this.#unfiledClause();\n if (!e.present || !clause) return null;\n try {\n return Number(\n (\n this.db.prepare(`SELECT COUNT(*) AS c FROM \"${e.table}\" t WHERE ${clause}`).get() as {\n c: number | bigint;\n }\n ).c,\n );\n } catch {\n return null;\n }\n }\n\n /** One entity's places, newest first when a date is available. */\n places(\n kind: \"favorite\" | \"collection-item\" | \"history\",\n opts: {\n limit: number;\n collectionId?: number | undefined;\n query?: string | undefined;\n /** Only items filed in NO collection. See `#unfiledClause`. */\n unfiled?: boolean | undefined;\n },\n ): { rows: PlaceRow[]; truncated: boolean } {\n const e = this.#entityFor(kind);\n if (!e.present || e.rows === 0) return { rows: [], truncated: false };\n\n const where: string[] = [];\n const params: (string | number)[] = [];\n\n if (opts.collectionId !== undefined) {\n const m = this.caps.membership;\n // Nothing reproduced ZPLACESCOUNT, so which places are in this guide is\n // genuinely unknown. Empty is the honest answer and callers are told why.\n if (!m) return { rows: [], truncated: false };\n if (m.kind === \"column\") {\n where.push(`t.\"${m.column}\" = ?`);\n } else {\n // IN, not JOIN, because the question is set membership: is this item\n // in this guide. A JOIN also multiplies the row by the number of\n // matching join rows, which is 1 today only because Core Data gives the\n // table a compound primary key — a property of the schema rather than\n // of the query. IN does not depend on it.\n where.push(\n `t.\"Z_PK\" IN (SELECT j.\"${m.itemColumn}\" FROM \"${m.table}\" j ` +\n `WHERE j.\"${m.collectionColumn}\" = ?)`,\n );\n }\n params.push(opts.collectionId);\n }\n\n if (opts.unfiled) {\n const clause = this.#unfiledClause();\n // Membership is unresolved, so \"in no collection\" is not a question this\n // store can answer either. Empty, and the caller is told why.\n if (!clause) return { rows: [], truncated: false };\n where.push(clause);\n }\n\n if (opts.query) {\n const pattern = `%${escapeLike(opts.query)}%`;\n const clauses: string[] = [];\n for (const col of [e.fields.name, e.fields.customName, e.fields.address]) {\n if (!col) continue;\n clauses.push(`t.\"${col}\" LIKE ? ESCAPE '\\\\'`);\n params.push(pattern);\n }\n // No searchable column means no rows can match. Returning everything\n // would be worse than returning nothing: it reads as a successful search.\n if (clauses.length === 0) return { rows: [], truncated: false };\n where.push(`(${clauses.join(\" OR \")})`);\n }\n\n const limit = Math.max(1, opts.limit);\n params.push(limit + 1);\n\n const order = e.fields.modified\n ? `t.\"${e.fields.modified}\" DESC`\n : e.fields.created\n ? `t.\"${e.fields.created}\" DESC`\n : `t.\"Z_PK\" DESC`;\n\n const sql =\n `SELECT ${this.#placeSelect(e)} FROM \"${e.table}\" t ` +\n (where.length ? `WHERE ${where.join(\" AND \")} ` : \"\") +\n `ORDER BY ${order} LIMIT ?`;\n\n const raw = this.db.prepare(sql).all(...params) as Record<string, unknown>[];\n return {\n rows: raw.slice(0, limit).map((r) => this.#toPlace(r)),\n truncated: raw.length > limit,\n };\n }\n\n /**\n * The WHERE clause and parameter for one key, or null when the key cannot be\n * honoured against this entity.\n *\n * A uuid key against a store with no resolved identifier column returns null\n * rather than falling back to the row id. The two number spaces are unrelated,\n * so a fallback would resolve to a real but WRONG place — the one outcome\n * worse than not finding it.\n *\n * `HEX()` on both sides rather than `X'..'` literal: it keeps the comparison\n * in one form, and these tables are tens of rows, so the lost index is free.\n */\n #keyClause(e: EntityFacts, key: EntityKey): { sql: string; param: string | number } | null {\n if (\"uuid\" in key) {\n if (!e.fields.identifier) return null;\n return {\n sql: `HEX(t.\"${e.fields.identifier}\") = ?`,\n param: key.uuid.replaceAll(\"-\", \"\").toUpperCase(),\n };\n }\n return { sql: `t.\"Z_PK\" = ?`, param: key.rowId };\n }\n\n /** One place by entity and key. */\n place(kind: \"favorite\" | \"collection-item\" | \"history\", key: EntityKey): PlaceRow | null {\n const e = this.#entityFor(kind);\n if (!e.present) return null;\n const clause = this.#keyClause(e, key);\n if (!clause) return null;\n const sql = `SELECT ${this.#placeSelect(e)} FROM \"${e.table}\" t WHERE ${clause.sql} LIMIT 1`;\n const r = this.db.prepare(sql).get(clause.param) as Record<string, unknown> | undefined;\n return r ? this.#toPlace(r) : null;\n }\n\n /**\n * A collection key to the row id its items point at.\n *\n * Collection membership is a Core Data foreign key, so it holds `Z_PK` values\n * whatever the ref carries. A uuid ref has to be translated before it can\n * filter items, and this is the one place that happens.\n */\n collectionRowId(key: EntityKey): number | null {\n if (!(\"uuid\" in key)) return key.rowId;\n const e = this.caps.collections;\n const clause = this.#keyClause(e, key);\n if (!e.present || !clause) return null;\n const r = this.db\n .prepare(`SELECT t.\"Z_PK\" AS id FROM \"${e.table}\" t WHERE ${clause.sql} LIMIT 1`)\n .get(clause.param) as { id: number | bigint } | undefined;\n return r ? Number(r.id) : null;\n }\n\n collections(opts: { limit: number }): { rows: CollectionRow[]; truncated: boolean } {\n const e = this.caps.collections;\n if (!e.present || e.rows === 0) return { rows: [], truncated: false };\n const limit = Math.max(1, opts.limit);\n const hasCount = e.columns.has(\"ZPLACESCOUNT\");\n const order = e.fields.modified ? `t.\"${e.fields.modified}\" DESC` : `t.\"Z_PK\" DESC`;\n const sql =\n `SELECT t.\"Z_PK\" AS id, ` +\n `${e.fields.identifier ? `HEX(t.\"${e.fields.identifier}\") AS uuid` : `NULL AS uuid`}, ` +\n `${this.#col(e.fields.name, \"title\")}, ` +\n `${hasCount ? `t.\"ZPLACESCOUNT\" AS placesCount` : `NULL AS placesCount`}, ` +\n `${this.#col(e.fields.created, \"createdRaw\")}, ` +\n `${this.#col(e.fields.modified, \"modifiedRaw\")} ` +\n `FROM \"${e.table}\" t ORDER BY ${order} LIMIT ?`;\n const raw = this.db.prepare(sql).all(limit + 1) as Record<string, unknown>[];\n return {\n rows: raw.slice(0, limit).map((r) => ({\n id: Number(r.id),\n uuid: toUuid(r.uuid),\n title: r.title === null || r.title === undefined ? null : String(r.title),\n placesCount: r.placesCount === null ? null : Number(r.placesCount),\n createdRaw: r.createdRaw === null ? null : Number(r.createdRaw),\n modifiedRaw: r.modifiedRaw === null ? null : Number(r.modifiedRaw),\n })),\n truncated: raw.length > limit,\n };\n }\n\n close(): void {\n try {\n this.db.close();\n } catch {\n // Already closed, or the handle died with the process. Nothing to do.\n }\n }\n}\n\nexport const openStore = (opts: {\n path: string;\n mode?: ReadOnlyMode;\n logger?: Logger;\n now?: number;\n hint?: string;\n}): MapsStore => {\n const opened = openReadOnly(opts.path, opts.mode ?? \"auto\", {\n envVar: \"APPLE_MAPS_INDEX_MODE\",\n label: \"Maps' place store\",\n ...(opts.hint ? { hint: opts.hint } : {}),\n validate: (db) => introspect(db, opts.now),\n fatal: (err) => err instanceof SchemaDriftError,\n onFallback: () =>\n opts.logger?.warn?.(\n \"maps: opened immutable; places saved since the last checkpoint may be missing\",\n ),\n });\n return new MapsStore({\n db: opened.db,\n caps: opened.validated,\n path: opts.path,\n mode: opened.mode,\n });\n};\n","import type { Logger, ReadOnlyMode } from \"@mgcrea/mcp-apple-core\";\n\nimport type { Config } from \"../config.js\";\nimport { renderInstant, type Epoch } from \"./dates.js\";\nimport { MapsStoreUnavailableError } from \"./errors.js\";\nimport { MapsLane } from \"./lane.js\";\nimport { locateStore, type LocateResult } from \"./locate.js\";\nimport type { OpenUrl } from \"./open-url.js\";\nimport { PlaceSourceFinder } from \"./place-source.js\";\nimport { encodeCollectionRef, encodePlaceRef, type PlaceKind } from \"./ref.js\";\nimport type { EntityKey } from \"./store.js\";\nimport { openStore, type CollectionRow, type MapsStore, type PlaceRow } from \"./store.js\";\n\n/**\n * The client.\n *\n * ## One lane, and the consequence of that\n *\n * Safari's orchestrator exists to keep two lanes from being mistaken for one\n * another. Maps has no second lane at all — the app ships no scripting\n * dictionary — so this class has the opposite job: making sure the ABSENCE of\n * the one lane is never mistaken for an absence of data.\n *\n * Without Full Disk Access every list would naturally come back `[]`, and an\n * empty `favorites` reads exactly like a person who has saved no places. So a\n * read with no store THROWS a named error; it never returns an empty array.\n * That is the same rule `packages/messages` follows, and for the same reason:\n * both are surfaces where the grant is not an optimisation.\n */\n\nexport type RenderedPlace = {\n ref: string;\n kind: PlaceKind;\n /** The user's own label when they set one, otherwise the place's name. */\n name: string | null;\n /** The place's own name, kept separate so a rename is visible as one. */\n placeName: string | null;\n address: string | null;\n latitude: number | null;\n longitude: number | null;\n /**\n * Apple's place identifier. Stable for the same place across devices, and\n * shared between a favourite and a collection entry for the same place — so\n * it is reported, and never used as the ref. See `ref.ts`.\n *\n * A STRING: it is a 64-bit integer that does not fit in a JS number. A real\n * store returned `-2679868148951248105`.\n */\n muid: string | null;\n created: string | null;\n modified: string | null;\n /**\n * False for a row with no linked place record. MEASURED: 3 of 23 favourites,\n * carrying no name and no coordinate — almost certainly the unconfigured\n * Home / Work / School slots Maps creates whether or not anyone fills them in.\n */\n linked: boolean;\n};\n\nexport type RenderedCollection = {\n ref: string;\n title: string | null;\n /** Maps' own count, which may include items this server cannot enumerate. */\n placesCount: number | null;\n created: string | null;\n modified: string | null;\n};\n\nexport type CreateClientOptions = {\n config: Config;\n logger?: Logger;\n /** Injected by tests so discovery never reaches the developer's real home. */\n home?: string;\n /**\n * The store lane, for tests. A seam of the same shape as `home`: null pins\n * the npm surface on a machine that IS hosted, a lane opened on a stub socket\n * drives the lane tools, and undefined asks the environment, which is what\n * the server does.\n */\n lane?: MapsLane | null | undefined;\n /**\n * How a place is opened in Maps to seed a record, for tests, so a suite never\n * launches the app. Undefined is `open -g`.\n */\n openUrl?: OpenUrl | undefined;\n};\n\n/**\n * What diagnostics says about one entity: how many rows, which column won for\n * each field, and which fields resolved to nothing. `resolved` is the part that\n * matters when a result looks wrong — it names the column actually being read.\n */\nconst summariseEntity = (e: MapsStore[\"caps\"][\"favorites\"]) => ({\n rows: e.rows,\n resolved: Object.fromEntries(Object.entries(e.fields).filter(([, v]) => v !== null)),\n unresolved: Object.entries(e.fields)\n .filter(([, v]) => v === null)\n .map(([k]) => k),\n});\n\nexport class AppleMapsClient {\n readonly #config: Config;\n\n /**\n * The store lane, when this server is hosted by Cupertino: the five writes,\n * saved by the app with Maps' own model, and Maps' only write route.\n *\n * Null when it is not, which is the supported case rather than a fault: the\n * npm package has to work with no app on the machine, and then it only\n * reads. `tools/index.ts` registers no write tool. Opening it connects\n * nothing.\n */\n readonly #lane: MapsLane | null;\n readonly #openUrl: OpenUrl | undefined;\n readonly #logger: Logger | undefined;\n readonly #home: string | undefined;\n\n #located: LocateResult | null = null;\n #store: MapsStore | null = null;\n #storeError: string | null = null;\n\n constructor(opts: CreateClientOptions) {\n this.#config = opts.config;\n this.#lane = opts.lane !== undefined ? opts.lane : MapsLane.open();\n this.#openUrl = opts.openUrl;\n this.#logger = opts.logger;\n this.#home = opts.home;\n }\n\n get config(): Config {\n return this.#config;\n }\n\n get lane(): MapsLane | null {\n return this.#lane;\n }\n\n located(): LocateResult {\n this.#located ??= locateStore({\n storePath: this.#config.storePath,\n ...(this.#home ? { home: this.#home } : {}),\n });\n return this.#located;\n }\n\n /**\n * A read-only finder of place records for the store lane, bound to the\n * located store, or an error explaining why not. It writes nothing: the lane\n * does the writing, through Maps' own model. Its own connections, rather than\n * the shared one `store()` opens, because it must not hold one across a seed.\n */\n placeSource(openUrl: OpenUrl | undefined = this.#openUrl): PlaceSourceFinder {\n const located = this.located();\n if (!located.readable || !located.storePath) {\n throw new MapsStoreUnavailableError(located.reason ?? \"Maps' store could not be opened.\");\n }\n return new PlaceSourceFinder({\n storePath: located.storePath,\n seedTimeoutMs: this.#config.seedTimeoutMs,\n ...(openUrl ? { openUrl } : {}),\n });\n }\n\n /** Open the store, once, lazily. Every read goes through here. */\n store(): MapsStore {\n if (this.#store) return this.#store;\n if (this.#storeError !== null) throw new MapsStoreUnavailableError(this.#storeError);\n\n const located = this.located();\n if (!located.readable || !located.storePath) {\n this.#storeError = located.reason ?? \"Maps' store could not be opened.\";\n throw new MapsStoreUnavailableError(this.#storeError);\n }\n try {\n this.#store = openStore({\n path: located.storePath,\n mode: this.#config.indexMode as ReadOnlyMode,\n ...(this.#logger ? { logger: this.#logger } : {}),\n });\n return this.#store;\n } catch (err) {\n this.#storeError = err instanceof Error ? err.message : String(err);\n throw err;\n }\n }\n\n get epoch(): Epoch {\n return this.store().caps.epoch;\n }\n\n #render(kind: PlaceKind, row: PlaceRow, epoch: Epoch): RenderedPlace {\n return {\n ref: encodePlaceRef(kind, row.uuid ? { uuid: row.uuid } : { rowId: row.id }),\n kind,\n name: row.customName ?? row.name,\n placeName: row.name,\n address: row.address,\n latitude: row.latitude,\n longitude: row.longitude,\n muid: row.muid,\n created: renderInstant(row.createdRaw, epoch),\n modified: renderInstant(row.modifiedRaw, epoch),\n linked: row.linked,\n };\n }\n\n #renderCollection(row: CollectionRow, epoch: Epoch): RenderedCollection {\n return {\n ref: encodeCollectionRef(row.uuid ? { uuid: row.uuid } : { rowId: row.id }),\n title: row.title,\n placesCount: row.placesCount,\n created: renderInstant(row.createdRaw, epoch),\n modified: renderInstant(row.modifiedRaw, epoch),\n };\n }\n\n places(\n kind: PlaceKind,\n opts: {\n limit: number;\n collectionId?: number | undefined;\n query?: string | undefined;\n unfiled?: boolean | undefined;\n },\n ): { places: RenderedPlace[]; truncated: boolean; datesAvailable: boolean } {\n const store = this.store();\n const { rows, truncated } = store.places(kind, opts);\n return {\n places: rows.map((r) => this.#render(kind, r, store.caps.epoch)),\n truncated,\n datesAvailable: store.caps.epoch.confident,\n };\n }\n\n place(kind: PlaceKind, key: EntityKey): RenderedPlace | null {\n const store = this.store();\n const row = store.place(kind, key);\n return row ? this.#render(kind, row, store.caps.epoch) : null;\n }\n\n /**\n * A collection ref to the row id its items point at, or null when the ref\n * addresses nothing in this store.\n *\n * Collection membership is a Core Data foreign key and always holds `Z_PK`,\n * so a uuid ref has to be translated before it can filter items.\n */\n collectionRowId(key: EntityKey): number | null {\n return this.store().collectionRowId(key);\n }\n\n collections(opts: { limit: number }): {\n collections: RenderedCollection[];\n truncated: boolean;\n /** Null when the membership key was not found — see `store.ts`. */\n itemsEnumerable: boolean;\n /**\n * Saved places filed in no collection, or null when unanswerable.\n *\n * Reported beside the collections because the counts otherwise do not add\n * up and nothing says so: the guides account for 18 places while the store\n * holds 30, and a caller comparing the two has no way to learn where the\n * rest went.\n */\n unfiled: number | null;\n } {\n const store = this.store();\n const { rows, truncated } = store.collections(opts);\n return {\n collections: rows.map((r) => this.#renderCollection(r, store.caps.epoch)),\n truncated,\n itemsEnumerable: store.caps.membership !== null,\n unfiled: store.unfiledCount(),\n };\n }\n\n /**\n * Search every place-bearing entity at once.\n *\n * Three separate queries rather than a UNION, because the three tables have\n * different resolved columns and a UNION would have to flatten them to the\n * narrowest — which on this store means losing history's coordinates, since\n * they live in a differently named column from the other two.\n */\n search(opts: { query: string; limit: number }): {\n places: RenderedPlace[];\n truncated: boolean;\n datesAvailable: boolean;\n } {\n const store = this.store();\n const kinds: PlaceKind[] = [\"favorite\", \"collection-item\", \"history\"];\n const places: RenderedPlace[] = [];\n let truncated = false;\n for (const kind of kinds) {\n const { rows, truncated: t } = store.places(kind, {\n limit: opts.limit,\n query: opts.query,\n });\n truncated ||= t;\n for (const r of rows) places.push(this.#render(kind, r, store.caps.epoch));\n }\n return {\n places: places.slice(0, opts.limit),\n truncated: truncated || places.length > opts.limit,\n datesAvailable: store.caps.epoch.confident,\n };\n }\n\n /** Everything diagnostics needs, with no failure allowed to fail the call. */\n status(): {\n located: LocateResult;\n store: { opened: boolean; mode: string | null; reason: string | null };\n capabilities: Record<string, unknown> | null;\n } {\n const located = this.located();\n let store: MapsStore | null = null;\n let reason: string | null = located.reason;\n try {\n store = this.store();\n } catch (err) {\n reason = err instanceof Error ? err.message : String(err);\n }\n return {\n located,\n store: { opened: store !== null, mode: store?.mode ?? null, reason },\n capabilities: store\n ? {\n fingerprint: store.caps.fingerprint,\n tableCount: store.caps.tables.length,\n epoch: store.caps.epoch,\n collectionFk: store.caps.collectionFk,\n collectionMembership: store.caps.membership,\n entities: {\n favorites: summariseEntity(store.caps.favorites),\n collections: summariseEntity(store.caps.collections),\n collectionItems: summariseEntity(store.caps.collectionItems),\n history: summariseEntity(store.caps.history),\n mapItems: summariseEntity(store.caps.mapItems),\n },\n }\n : null,\n };\n }\n\n close(): void {\n this.#store?.close();\n this.#store = null;\n this.#lane?.close();\n }\n}\n","import {\n BaseConfigSchema,\n parseBool,\n parseConfig,\n parseIntOpt,\n trimmed,\n} from \"@mgcrea/mcp-apple-core\";\nimport { z } from \"zod\";\n\n/**\n * Configuration is environment-only — this server holds no secret at all. Its\n * access is the macOS permission the user granted, which is the whole point.\n *\n * `allowWrites` gates the mutating tools, and only matters when Cupertino\n * hosts this server. Maps has no scripting dictionary and no registered App\n * Intents, so its one write route is Cupertino's store lane, which saves with\n * Maps' own Core Data model; on macOS 27.2 those saves were measured on\n * 2026-11-11 to reach an iPhone through iCloud. Run from npm there is no lane,\n * and no write tool is registered whatever this says. The lane keeps one rule:\n * never fabricate a place record, only ever copy one Maps wrote itself. See\n * `docs/maps.md`.\n */\nconst ConfigSchema = BaseConfigSchema.extend({\n /** Explicit store path. Bypasses discovery — for tests and forensic copies. */\n storePath: z.string().optional(),\n indexMode: z.enum([\"auto\", \"ro\", \"immutable\", \"off\"]).default(\"auto\"),\n /**\n * How long `add_favorite` waits for Maps to resolve a place it does not know.\n * Tens of seconds is normal — Maps goes to the network — and a slow link\n * needs more; this is the one timeout in the bundle that was not a setting.\n */\n seedTimeoutMs: z.number().int().min(1_000).max(600_000).default(30_000),\n}).strict();\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\nexport const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config =>\n parseConfig(ConfigSchema, {\n allowWrites: parseBool(env.APPLE_MAPS_ALLOW_WRITES),\n exposePrompts: parseBool(env.APPLE_MAPS_EXPOSE_PROMPTS),\n lazyTools: parseBool(env.APPLE_MAPS_LAZY_TOOLS),\n storePath: trimmed(env.APPLE_MAPS_STORE),\n indexMode: trimmed(env.APPLE_MAPS_INDEX_MODE),\n osascriptPath: trimmed(env.APPLE_MAPS_OSASCRIPT_PATH),\n osascriptTimeoutMs: parseIntOpt(env.APPLE_MAPS_OSASCRIPT_TIMEOUT_MS),\n maxResults: parseIntOpt(env.APPLE_MAPS_MAX_RESULTS),\n seedTimeoutMs: parseIntOpt(env.APPLE_MAPS_SEED_TIMEOUT_MS),\n });\n","/**\n * The Maps operating manual, served as `cupertino://maps/guide` and embedded\n * ahead of every Maps prompt. Static by design — see the note in the Mail guide.\n */\nexport const MAPS_GUIDE = `# Maps — how to drive this server\n\n## What this surface is, and is not\n\nIt reads the places **saved on this Mac**: favourites, collections (Guides) and\nrecents. It does **not** search Apple's map of the world, geocode an address,\ngive directions, or compute a travel time. If asked for any of those, say so\nplainly rather than searching the saved places and presenting a near-miss —\n\"the nearest coffee shop\" is not a question this server can answer, and a\nfavourite called \"Coffee\" is not the answer to it.\n\n## One lane, and no fallback\n\nMaps ships **no scripting dictionary** — there is no \\`.sdef\\` in the app bundle\n— so unlike every other surface here there is no Apple Events lane to fall back\nto. Everything comes from a Core Data store under **Full Disk Access**.\n\nThe consequence matters: without the grant this server returns an **error**, not\nan empty list. If a tool ever does return an empty list, that means the user has\ngenuinely saved nothing of that kind. Check\n\\`cupertino://maps/diagnostics\\` before concluding either way.\n\n## Which tool answers which question\n\n| Question | Tool |\n| --- | --- |\n| What places has the user saved? | \\`apple_maps_list_favorites\\` |\n| What Guides do they keep? | \\`apple_maps_list_collections\\` |\n| What is filed in one Guide? | \\`apple_maps_list_collection_places\\` |\n| Where have they looked recently? | \\`apple_maps_list_recents\\` |\n| Find a saved place by name or address | \\`apple_maps_search_places\\` |\n| One place, in full | \\`apple_maps_get_place\\` |\n\n## Writing, when Cupertino hosts this server\n\nWith writes on and Cupertino hosting this server, five tools save through Maps'\nown data model inside Cupertino, as a change made in the app is. They are the\nonly way this server writes: run from npm it only reads, and none of them is\nlisted. If the user asks for a change then, say it needs Cupertino.\n\n| Change | Tool |\n| --- | --- |\n| Pin a place (the Pinned list) | \\`apple_maps_add_favorite\\` |\n| Unpin it | \\`apple_maps_remove_favorite\\` |\n| Save a place to the library, in no Guide | \\`apple_maps_save_place\\` |\n| Remove a saved place | \\`apple_maps_remove_saved_place\\` |\n| File a place in an existing Guide | \\`apple_maps_add_place_to_guide\\` |\n\n**Unpinning is not removing.** As in Maps, \\`apple_maps_remove_favorite\\` keeps\nthe place in the user's library as a saved place. To take a place out of Maps\nentirely, unpin it and then remove the saved place with\n\\`apple_maps_remove_saved_place\\`, by a ref from \\`apple_maps_list_unfiled_places\\`\nor \\`apple_maps_list_collection_places\\`.\n\n**Removes take a ref** from a listing, never a coordinate.\n\\`apple_maps_add_place_to_guide\\` takes a ref to a saved place, or a \\`query\\` to\nsave a new place and file it in one call.\n\n**A new place lands in Recents.** Only Maps can make a place record, so unless the\nplace is already in the store near the coordinate given, Maps resolves it by\nname, and it then also appears in the user's Recents. Give a coordinate when\nyou have one. The answer says so in \\`recentsNote\\`; tell the user.\n\n**On the measured model, a save reaches iCloud without the app:** when the\nresult's \\`syncMeasured\\` is true, Maps' background service uploads it even\nwith Maps closed. Say the change is saved on this Mac and on its way to\nother devices, not that it is already on the iPhone. When the result's\n\\`syncMeasured\\` is false, the save still happened but sync is not yet measured on\nthis macOS: pass on its \\`sync\\` sentence, which asks to check the place on another\ndevice.\n\nA refusal's reason is in \\`details.reason\\`. A place Maps resolved more than about\n250 m from the coordinate given is refused as \\`invalid\\`: confirm the place with\nthe user rather than retrying without a coordinate. \\`incompatible\\` and\n\\`writesOff\\` will not pass on a retry.\n\n## Four things not to say\n\n**\\`linked: false\\` is not a broken row.** Some favourites have no place\nattached, no name and no coordinate. They are Maps' unconfigured Home / Work /\nSchool slots. Report them as unset, not as places.\n\n**A null date is unknown, not old.** Timestamps are placed on an epoch detected\nfrom the store. When detection fails every date reads \\`null\\` rather than being\nguessed, because a date wrong by 31 years reads exactly like a correct one.\n\n**A collection with no listable places may still have places.** How an item\nbelongs to a collection is not exposed by every version of this store. When the\nkey is missing, \\`placesCount\\` is still Maps' own accurate number and the\nplaces simply cannot be enumerated. Say that, rather than reporting an empty\nGuide.\n\n**Refs expire.** They address a row in a store that iCloud re-syncs, and Core\nData reuses row ids after a delete. A ref is good for this conversation. Do not\nstore one or hand it back later.\n\n## Privacy, worth holding in mind\n\nSaved places are a home address, a doctor, a school, a partner's flat. This is\namong the most sensitive data any surface here reads. Answer what was asked;\ndo not enumerate everything because a listing tool is available.\n`;\n","import { promptArg, registerWorkflowPrompt, type PromptContext } from \"@mgcrea/mcp-apple-core\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\n\nimport { MAPS_GUIDE } from \"./guide.js\";\n\nconst CTX: PromptContext = { surface: \"maps\", guide: MAPS_GUIDE };\n\n/**\n * Maps' one workflow prompt.\n *\n * It exists because \"where was that place\" spans three lists that hold the same\n * kind of thing for different reasons — a favourite is deliberate, a collection\n * entry is filed, a recent is incidental — and searching only one produces a\n * confident answer to a question nobody asked. The prompt also carries the\n * refusal: this server does not know about places the user has never saved, and\n * the most likely way to be wrong here is to answer anyway.\n */\nexport const registerPrompts = (server: McpServer): void => {\n registerWorkflowPrompt(server, CTX, {\n name: \"apple_maps_where_was_that_place\",\n title: \"Find a place I saved\",\n description:\n \"Track down a saved place across favourites, Guides and recents — three lists that hold \" +\n \"places for different reasons. Read-only.\",\n argsSchema: {\n about: promptArg('What the place was, e.g. \"the ramen place near the office\".'),\n },\n build: ({ about }) => `Find the saved place ${about ? `matching: ${about}` : \"I am after\"}.\n\nStart with \\`apple_maps_search_places\\` — it covers favourites, Guide entries and\nrecents in one call, and tells you which kind each match came from. That\ndistinction is the answer, not a detail: a favourite is somewhere I chose to\nkeep, a recent is somewhere I merely looked at once.\n\nIf that finds nothing, list the three directly before concluding it is not\nthere — a place I saved under my own label (\"Mum's\") will not match a search for\nwhat it actually is.\n\nThen report what you found, with the address and how it was saved.\n\nThree things to get right:\n- If nothing matches, say I have not saved it. Do **not** fall back to guessing\n a place from general knowledge — this server only knows what is on this Mac,\n and inventing an address is the worst possible failure here.\n- An entry with \\`linked: false\\` is an unconfigured Home/Work/School slot, not\n a place. Do not report it as one.\n- If a date reads null, the date is unknown. Do not describe it as old.\n\nIf every list comes back empty, check \\`cupertino://maps/diagnostics\\` before\nconcluding I have saved nothing — this surface has no second lane, so a missing\nFull Disk Access grant takes all of it at once.`,\n });\n};\n","/**\n * Maps' tool helpers. The generic half lives in `@mgcrea/mcp-apple-core`;\n * re-exported here so tools import from one place.\n */\nexport {\n compact,\n confirmArg,\n fail,\n limitArg,\n ok,\n okText,\n resolveLimit,\n toFailure,\n wrap,\n wrapResult,\n type ToolResult,\n} from \"@mgcrea/mcp-apple-core\";\n\nimport { z } from \"zod\";\n\nexport const placeRefArg = z\n .string()\n .min(1)\n .describe(\n 'An opaque place ref from a listing (looks like \"p1:f:12\"). Do not construct one by hand. ' +\n \"Refs address a row in the local store, so they are only valid for this session — an \" +\n \"iCloud re-sync can renumber them.\",\n );\n\nexport const collectionRefArg = z\n .string()\n .min(1)\n .describe('An opaque collection ref from apple_maps_list_collections (looks like \"pc1:3\").');\n\nexport const queryArg = z\n .string()\n .min(1)\n .describe(\n \"Text to look for in a place's name, the label you gave it, or its address. Wildcards are \" +\n 'escaped, so searching for \"100%\" finds that literal string.',\n );\n","import { StoreLaneError } from \"@mgcrea/mcp-apple-core\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\nimport { z } from \"zod\";\n\nimport type { LaneWrite, MapsLane } from \"../client/lane.js\";\nimport type { AppleMapsClient } from \"../client/maps.js\";\nimport type { PlaceSource, StoredPlace } from \"../client/place-source.js\";\nimport {\n decodePlaceRef,\n encodePlaceRef,\n InvalidMapsRefError,\n type PlaceKind,\n} from \"../client/ref.js\";\nimport type { EntityKey } from \"../client/store.js\";\nimport { compact, confirmArg, fail, ok, placeRefArg, type ToolResult, wrapResult } from \"./util.js\";\n\n/** The five tools this file registers, in registration order. */\nexport const STORE_WRITE_TOOLS: readonly string[] = [\n \"apple_maps_add_favorite\",\n \"apple_maps_remove_favorite\",\n \"apple_maps_save_place\",\n \"apple_maps_remove_saved_place\",\n \"apple_maps_add_place_to_guide\",\n];\n\n/**\n * What a write promises about iCloud, in one sentence, on Voice Memos' pattern\n * (`packages/voice-memos/src/tools/store-writes.ts`).\n *\n * Sync is promised only on a model version whose upload was measured: Maps'\n * model on macOS 27.2 (checksum `CaxhFk…`, listed in the Swift writer's\n * `measuredVersions`), every write seen on a Mac and an iPhone on\n * 2026-11-11, one with Maps quit and mapssyncd exporting alone (`docs/maps.md`,\n * \"Measured 2026-11-11\"). Elsewhere the save still happened, but nobody has\n * watched it reach another device, so the result says so. The two removes say\n * it of a removal.\n */\nexport const syncSentence = (\n w: Pick<LaneWrite, \"changed\" | \"syncMeasured\" | \"modelVersion\">,\n kind: \"save\" | \"remove\" = \"save\",\n) => {\n if (w.changed.length === 0) return \"Nothing to change.\";\n const [done, how] = kind === \"remove\" ? [\"Removed\", \"removes\"] : [\"Saved\", \"saves\"];\n if (w.syncMeasured) {\n return (\n `${done} the way Maps ${how} it. It reaches your other devices through iCloud, even with ` +\n \"Maps closed.\"\n );\n }\n return (\n `${done}, but sync is not yet measured on this macOS ` +\n `(model ${w.modelVersion ?? \"unknown\"}): check the place on another device.`\n );\n};\n\n/** The lane's own fields, plus the sentence. */\nconst laneFields = (w: LaneWrite, kind: \"save\" | \"remove\" = \"save\") => ({\n changed: w.changed,\n modelVersion: w.modelVersion,\n syncMeasured: w.syncMeasured,\n sync: syncSentence(w, kind),\n});\n\n/**\n * The answer when an item already stood there and the lane was never asked: no\n * model version to report, because nothing was saved.\n */\nconst unchanged = { changed: [] as string[], sync: \"Nothing to change.\" };\n\nconst RECENTS_NOTE =\n \"Maps was asked to resolve this place, so it now also appears in the user's Recents. That \" +\n \"is how the place record is obtained and cannot be avoided.\";\n\n/** What follows, in every lane tool's description, what the tool does. */\nconst LANE_TAIL =\n \"the result's `sync` says whether that is measured to reach the user's other Apple devices \" +\n \"on this macOS. Only available when Cupertino hosts this server.\";\n\n/** The three tools that add something say this. */\nconst SAVED_LIKE = `Saved through Maps' own data model inside Cupertino, as a change made in the app is; ${LANE_TAIL}`;\n\n/** The two removes say this: what they take away goes the way the app takes it away. */\nconst REMOVED_LIKE = `Removed through Maps' own data model inside Cupertino, as a removal made in the app is; ${LANE_TAIL}`;\n\n/** The three tools that may need a place record Maps has not minted yet. */\nconst SEEDS =\n \"SIDE EFFECT: unless the place is already in the store, Maps is asked to resolve it by name \" +\n \"and the place also appears in the user's Recents; there is no way to have the record \" +\n \"without that.\";\n\n/**\n * Where an unpinned place went. Maps does not delete a pin it unpins: it moves\n * the place into the library as a saved place (watched 2026-11-11,\n * `docs/maps.md`), and the lane does the same. `changed` lists `savedPlace`\n * when the lane made one. Only `favorite` has two causes the answer does not\n * tell apart: a saved place already stood at that spot, or the pin carried no\n * place record or coordinate to move. The sentence is true of both.\n */\nconst libraryNote = (changed: string[]): string | undefined => {\n if (!changed.includes(\"favorite\")) return undefined;\n // An existing saved place may be filed in a Guide, so both listings are named.\n const from =\n \"by its ref from apple_maps_list_unfiled_places or apple_maps_list_collection_places.\";\n return changed.includes(\"savedPlace\")\n ? \"Unpinned, and kept in your library as a saved place, as Maps does. \" +\n `apple_maps_remove_saved_place removes it entirely, ${from}`\n : \"Unpinned. No new saved place was made: one already stood at this spot, or the pin \" +\n \"carried no place record to keep. apple_maps_remove_saved_place removes a saved \" +\n `place entirely, ${from}`;\n};\n\nconst WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true } as const;\nconst REMOVE = { ...WRITE, destructiveHint: true } as const;\n\nconst queryArg = z\n .string()\n .min(1)\n .describe(\n \"The place's name, as you would type it into Maps' search field. A bare coordinate does \" +\n \"not identify a place to Maps.\",\n );\nconst latitudeArg = z\n .number()\n .min(-90)\n .max(90)\n .optional()\n .describe(\"Latitude, when known: makes the match exact and can skip asking Maps.\");\nconst longitudeArg = z.number().min(-180).max(180).optional().describe(\"Longitude, when known.\");\nconst nameArg = z\n .string()\n .min(1)\n .optional()\n .describe(\n \"A label of your own, saved as the place's custom name, which the listings show before \" +\n \"the place's own. Left out, the place keeps the name Maps gives it.\",\n );\n\n/** A refusal decided here, before the lane is called, in the lane's own vocabulary. */\nconst refuse = (reason: \"invalid\" | \"notFound\", message: string) => fail(message, { reason });\n\n/**\n * Both halves of a coordinate, or neither. Half of one is a caller's mistake,\n * refused rather than dropped: dropping it would seed by name alone and could\n * save a namesake on the other side of the world.\n */\nconst coordsOf = (\n latitude: number | undefined,\n longitude: number | undefined,\n): { near: { latitude: number; longitude: number } | undefined } | { refusal: ToolResult } => {\n if (latitude !== undefined && longitude !== undefined) return { near: { latitude, longitude } };\n if (latitude === undefined && longitude === undefined) return { near: undefined };\n return { refusal: refuse(\"invalid\", \"Give both latitude and longitude, or neither.\") };\n};\n\n/** Where `find` got the record, as the lane names it. */\nconst fromSource = (s: PlaceSource) => ({ source: s.kind, sourceId: s.id });\n\n/**\n * A lane write that copies a source's record, with the lane's `notFound` for\n * that source said plainly. Between `find` and the save Maps can replace the\n * recent it filed (it does as it refreshes them), and the lane then finds no\n * item with that identifier. Nothing was saved, and a second call finds the\n * record Maps holds now.\n */\nconst copying = async (\n write: Promise<LaneWrite>,\n): Promise<{ w: LaneWrite } | { refusal: ToolResult }> => {\n try {\n return { w: await write };\n } catch (err) {\n if (err instanceof StoreLaneError && err.reason === \"notFound\") {\n return {\n refusal: refuse(\n \"notFound\",\n \"The place record Maps had filed for this place was replaced before it could be \" +\n \"copied: Maps replaces its Recents as it refreshes them. Nothing was saved; repeat \" +\n \"the call.\",\n ),\n };\n }\n throw err;\n }\n};\n\n/**\n * A place in an answer: its ref, and the item's own name and coordinate as the\n * store holds them. Fields the read-back did not find are left out, never\n * filled with what the caller asked for.\n *\n * The read-back comes after the lane committed the save, which is already on\n * its way to the user's other devices, so a read that fails answers the ref\n * alone, as one that finds nothing does, rather than an error for a write that\n * happened.\n */\nconst described = (\n client: AppleMapsClient,\n kind: \"favorite\" | \"collection-item\",\n id: string,\n stored?: StoredPlace | null,\n) => {\n let row: StoredPlace | null;\n try {\n row = stored === undefined ? client.placeSource().describe(kind, id) : stored;\n } catch {\n row = null;\n }\n return compact({\n ref: encodePlaceRef(kind, { uuid: id }),\n name: row?.name ?? undefined,\n latitude: row?.latitude ?? undefined,\n longitude: row?.longitude ?? undefined,\n });\n};\n\n/**\n * A ref from a listing to the identifier the lane fetches by, or a refusal.\n *\n * A ref that does not decode is refused `invalid`, like every other refusal\n * decided here. Null from `identifierOf` is a row with no `ZIDENTIFIER` (a\n * row-id ref), or no row at all: either way the lane, which fetches by uuid\n * only, cannot be given it, so the lane is not called.\n */\nconst identifierFor = (\n client: AppleMapsClient,\n ref: string,\n want: Exclude<PlaceKind, \"history\">,\n verb: \"removed\" | \"filed\",\n): { id: string } | { refusal: ToolResult } => {\n let decoded: { kind: PlaceKind; key: EntityKey };\n try {\n decoded = decodePlaceRef(ref);\n } catch (err) {\n if (err instanceof InvalidMapsRefError) {\n return { refusal: refuse(\"invalid\", err.message) };\n }\n throw err;\n }\n const { kind, key } = decoded;\n const what = want === \"favorite\" ? \"favourite\" : \"saved place\";\n if (kind !== want) {\n const is = kind === \"history\" ? \"recent\" : kind === \"favorite\" ? \"favourite\" : \"saved place\";\n const from =\n want === \"favorite\"\n ? \"apple_maps_list_favorites\"\n : \"apple_maps_list_unfiled_places or apple_maps_list_collection_places\";\n return {\n refusal: refuse(\n \"invalid\",\n `That ref points at a ${is}, not a ${what}. Pass a ref from ${from}.`,\n ),\n };\n }\n const id = client.placeSource().identifierOf(kind, key);\n if (id === null) {\n return {\n refusal: refuse(\n \"notFound\",\n \"uuid\" in key\n ? `No ${what} matched that ref. It may already have been removed; re-run the listing.`\n : `This ${what} has no stable id, so it cannot be ${verb} ` +\n \"through Cupertino (or it is no longer in the store).\",\n ),\n };\n }\n return { id };\n};\n\n/**\n * The store lane's Maps tools, and Maps' only writes. Registered only when\n * writes are on and Cupertino hosts this server (`tools/index.ts`): run from\n * npm, this server registers no write tool at all.\n *\n * This side keeps what only it can do: de-duplicate on the caller's coordinate\n * and name before anything else, find a place record Maps minted (seeding when\n * there is none), and turn a listing's ref into the identifier the lane fetches\n * by. The app validates every argument again and answers with a `reason` on\n * refusal (`invalid`, `notFound`, `incompatible`, `writesOff`, `failed`, or one\n * of the connection's own), which the tool error carries in `details.reason`.\n * Refusals decided here use the same vocabulary.\n *\n * A place in an answer is the item as the store holds it, read back after the\n * lane answers: the de-duplication can match a favourite saved under another\n * name, or ~250 m from the caller's coordinate, and the caller's guess must\n * not be reported as the place.\n *\n * The list does not depend on whether the lane is compatible: MCP clients cache\n * it, so an incompatible lane refuses per call instead.\n */\nexport const registerStoreWriteTools = (\n server: McpServer,\n client: AppleMapsClient,\n lane: MapsLane,\n): void => {\n server.registerTool(\n \"apple_maps_add_favorite\",\n {\n description:\n \"Save a place to Maps' favourites (the Pinned list). Give the place NAME as `query`, \" +\n \"and latitude/longitude when known. \" +\n `${SEEDS} ${SAVED_LIKE} Idempotent: asking twice for the same place returns the ` +\n \"existing favourite rather than creating a second. Needs Full Disk Access.\",\n inputSchema: z.object({\n query: queryArg,\n latitude: latitudeArg,\n longitude: longitudeArg,\n name: nameArg,\n }),\n annotations: WRITE,\n },\n async ({ query, latitude, longitude, name }) =>\n wrapResult(async () => {\n // What the place is called here, for the read-only de-duplication alone: the lane is\n // sent `name` only when the caller gave one.\n const label = name ?? query;\n const coords = coordsOf(latitude, longitude);\n if (\"refusal\" in coords) return coords.refusal;\n const { near } = coords;\n const finder = client.placeSource();\n const existing = near ? finder.existingFavorite({ ...near, name: label }) : null;\n if (existing) {\n return ok({\n favorite: described(client, \"favorite\", existing.id, existing),\n created: false,\n alreadyExisted:\n \"A favourite for this place already existed and was returned unchanged.\",\n ...unchanged,\n });\n }\n const s = await finder.find(near ? { query, ...near } : { query });\n const copied = await copying(lane.addFavorite({ ...fromSource(s), query, name, near }));\n if (\"refusal\" in copied) return copied.refusal;\n const { w } = copied;\n return ok(\n compact({\n favorite: described(client, \"favorite\", w.id),\n created: w.created,\n alreadyExisted: w.created\n ? undefined\n : \"A favourite for this place already existed and was returned unchanged.\",\n ...laneFields(w),\n recentsNote: s.seeded ? RECENTS_NOTE : undefined,\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_remove_favorite\",\n {\n description:\n \"Unpin a place from Maps' favourites (the Pinned list), by a ref from \" +\n \"apple_maps_list_favorites. As in Maps, unpinning keeps the place in the user's \" +\n \"library as a saved place, in no Guide; no new one is made when one already stands \" +\n \"at that spot, or the pin carries no place record. \" +\n \"apple_maps_remove_saved_place removes it entirely. Only pins: the Home, Work and \" +\n \"School slots are refused. It does not touch Guides or Recents. \" +\n `${REMOVED_LIKE} Needs Full Disk Access, and an explicit confirm: the unpin is not ` +\n \"undoable from here.\",\n inputSchema: z.object({ ref: placeRefArg, confirm: confirmArg }),\n annotations: REMOVE,\n },\n async ({ ref }) =>\n wrapResult(async () => {\n const target = identifierFor(client, ref, \"favorite\", \"removed\");\n if (\"refusal\" in target) return target.refusal;\n const w = await lane.removeFavorite(target.id);\n return ok(\n compact({\n removed: w.changed.length > 0,\n id: w.id,\n library: libraryNote(w.changed),\n ...laneFields(w, \"remove\"),\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_save_place\",\n {\n description:\n \"Save a place into Maps' Places library, in no Guide. This is NOT a favourite: the \" +\n \"Pinned list is a different set, written by apple_maps_add_favorite. Give the place \" +\n `NAME as \\`query\\`, and latitude/longitude when known. ${SEEDS} ${SAVED_LIKE} ` +\n \"Idempotent: a place already saved is returned unchanged. Needs Full Disk Access.\",\n inputSchema: z.object({\n query: queryArg,\n latitude: latitudeArg,\n longitude: longitudeArg,\n name: nameArg,\n }),\n annotations: WRITE,\n },\n async ({ query, latitude, longitude, name }) =>\n wrapResult(async () => {\n // What the place is called here, for the read-only de-duplication alone: the lane is\n // sent `name` only when the caller gave one.\n const label = name ?? query;\n const coords = coordsOf(latitude, longitude);\n if (\"refusal\" in coords) return coords.refusal;\n const { near } = coords;\n const finder = client.placeSource();\n const existing = near ? finder.existingSavedPlace({ ...near, name: label }) : null;\n if (existing) {\n return ok({\n place: described(client, \"collection-item\", existing.id, existing),\n saved: true,\n alreadySaved: true,\n created: false,\n ...unchanged,\n });\n }\n const s = await finder.find(near ? { query, ...near } : { query });\n const copied = await copying(lane.savePlace({ ...fromSource(s), query, name, near }));\n if (\"refusal\" in copied) return copied.refusal;\n const { w } = copied;\n return ok(\n compact({\n place: described(client, \"collection-item\", w.id),\n saved: true,\n alreadySaved: !w.created,\n created: w.created,\n ...laneFields(w),\n recentsNote: s.seeded ? RECENTS_NOTE : undefined,\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_remove_saved_place\",\n {\n description:\n \"Remove a place from Maps' Places library, by a ref from \" +\n \"apple_maps_list_unfiled_places or apple_maps_list_collection_places. That takes it \" +\n \"out of every Guide it is filed in. This does NOT touch favourites: use \" +\n `apple_maps_remove_favorite for those. ${REMOVED_LIKE} Needs Full Disk Access, and an ` +\n \"explicit confirm: the removal is not undoable from here.\",\n inputSchema: z.object({ ref: placeRefArg, confirm: confirmArg }),\n annotations: REMOVE,\n },\n async ({ ref }) =>\n wrapResult(async () => {\n const target = identifierFor(client, ref, \"collection-item\", \"removed\");\n if (\"refusal\" in target) return target.refusal;\n const w = await lane.removeSavedPlace(target.id);\n return ok({ removed: w.changed.length > 0, id: w.id, ...laneFields(w, \"remove\") });\n }),\n );\n\n server.registerTool(\n \"apple_maps_add_place_to_guide\",\n {\n description:\n \"File a place into one of Maps' Guides. Give either `ref`, a saved place from \" +\n \"apple_maps_list_unfiled_places or apple_maps_list_collection_places, or `query` \" +\n \"(with latitude/longitude when known) for a place to save and file in one save; not \" +\n \"both. The Guide must already exist, and a name that matches none, or several, is \" +\n \"refused naming the candidates. `filed` comes from reading the Guide back after the \" +\n `save, never from having asked. ${SEEDS} ${SAVED_LIKE} Needs Full Disk Access.`,\n inputSchema: z.object({\n guide: z.string().min(1).describe(\"The Guide's name, as Maps shows it.\"),\n ref: placeRefArg\n .optional()\n .describe(\n \"A saved place's ref, from apple_maps_list_unfiled_places or \" +\n \"apple_maps_list_collection_places. Give this or `query`, not both.\",\n ),\n query: queryArg\n .optional()\n .describe(\n \"The place's name, for a place to save first, as apple_maps_save_place takes it. \" +\n \"Give this or `ref`, not both.\",\n ),\n latitude: latitudeArg.describe(\"Latitude, with `query`, when known.\"),\n longitude: longitudeArg.describe(\"Longitude, with `query`, when known.\"),\n }),\n annotations: WRITE,\n },\n async ({ guide, ref, query, latitude, longitude }) =>\n wrapResult(async () => {\n const hasCoords = latitude !== undefined || longitude !== undefined;\n if ((ref === undefined) === (query === undefined) || (ref !== undefined && hasCoords)) {\n return refuse(\n \"invalid\",\n \"Give either `ref` (a saved place) or `query` with an optional latitude and \" +\n \"longitude (a place to save first): exactly one of the two.\",\n );\n }\n const filedAnswer = (w: LaneWrite, seeded: boolean) =>\n ok(\n compact({\n filed: w.filed,\n // True only when this call saved the place before filing it.\n created: w.created,\n guide,\n place: described(client, \"collection-item\", w.id),\n ...laneFields(w),\n recentsNote: seeded ? RECENTS_NOTE : undefined,\n }),\n );\n\n if (ref !== undefined) {\n const target = identifierFor(client, ref, \"collection-item\", \"filed\");\n if (\"refusal\" in target) return target.refusal;\n return filedAnswer(await lane.fileInGuide({ guide, placeId: target.id }), false);\n }\n\n const q = query as string;\n const coords = coordsOf(latitude, longitude);\n if (\"refusal\" in coords) return coords.refusal;\n const { near } = coords;\n const finder = client.placeSource();\n // The tight coordinate alone, not the 250 m same-name match: filing is the one write\n // here that adds to an existing place, and a chain's next branch shares its name.\n const existing = near ? finder.existingSavedPlace(near) : null;\n if (existing) {\n return filedAnswer(await lane.fileInGuide({ guide, placeId: existing.id }), false);\n }\n const s = await finder.find(near ? { query: q, ...near } : { query: q });\n // No label: this tool takes none, so the query is sent as the query alone.\n const copied = await copying(lane.fileInGuide({ guide, ...fromSource(s), query: q, near }));\n if (\"refusal\" in copied) return copied.refusal;\n return filedAnswer(copied.w, s.seeded);\n }),\n );\n};\n","import { buildBaseDiagnostics } from \"@mgcrea/mcp-apple-core\";\nimport type { McpServer } from \"@modelcontextprotocol/server\";\nimport { z } from \"zod\";\n\nimport { BUILD_INFO } from \"../build-info.js\";\nimport type { LaneStatus } from \"../client/lane.js\";\nimport type { AppleMapsClient } from \"../client/maps.js\";\nimport { STORE_WRITE_TOOLS } from \"./store-writes.js\";\nimport { wrap } from \"./util.js\";\n\n/**\n * The store lane's own answer, asked only when Cupertino hosts this server. A\n * lane that cannot answer is reported as `{ error }`, never as a failed\n * diagnostics call: this report is where a person looks when the lane is the\n * thing that broke. As Voice Memos' diagnostics does.\n */\nconst writeLaneStatus = async (\n client: AppleMapsClient,\n): Promise<LaneStatus | { error: string } | null> => {\n if (!client.lane) return null;\n try {\n return await client.lane.status();\n } catch (err) {\n return { error: err instanceof Error ? err.message : String(err) };\n }\n};\n\n/**\n * Build the report.\n *\n * Split out of the tool registration so the `cupertino://maps/diagnostics`\n * resource can serve the same bytes. Two renderings of one probe: duplicated,\n * the resource and the tool would drift, and the disagreement would surface as\n * \"the diagnostics lied\" — the one thing this file must never do.\n */\nexport const buildDiagnostics = async (\n client: AppleMapsClient,\n): Promise<Record<string, unknown>> => {\n const status = client.status();\n const located = status.located;\n const hosted = client.lane !== null;\n const writeLane = await writeLaneStatus(client);\n const allowWrites = client.config.allowWrites;\n /** The route `tools/index.ts` registered, so this report cannot disagree with it. */\n const route = !allowWrites ? \"off\" : hosted ? \"store lane\" : \"not hosted\";\n const tools = allowWrites && hosted ? [...STORE_WRITE_TOOLS] : [];\n const base = buildBaseDiagnostics({\n build: BUILD_INFO,\n config: client.config,\n allowWrites: client.config.allowWrites,\n });\n return {\n ...base,\n settings: { ...base.settings, seedTimeoutMs: client.config.seedTimeoutMs },\n lanes: {\n summary:\n \"Maps has ONE lane. Maps.app ships no scripting dictionary — there is no .sdef in the \" +\n \"bundle, checked directly — so there is no Apple Events fallback. Without Full Disk \" +\n \"Access this server cannot read anything at all, and it says so rather than returning \" +\n \"empty lists.\",\n fileLane: {\n needs: \"Full Disk Access\",\n answers: \"favourites, collections (guides), recents\",\n working: status.store.opened,\n },\n appleEvents: \"none — Maps is not scriptable\",\n writes: {\n enabled: allowWrites,\n route,\n ...(hosted\n ? {\n lane:\n \"Cupertino's store lane, Maps' only write route: the app saves each write \" +\n \"through Core Data with Maps' own model, so it is recorded in persistent \" +\n \"history like a change made in Maps. This server only reads the store, to \" +\n \"de-duplicate, find a place record to copy, and turn a ref into the \" +\n \"identifier the lane fetches by.\",\n seeding:\n \"A place is only real to Maps if it carries a ZMAPITEMSTORAGE record, which \" +\n \"nothing here can generate. When no record is already in the store near the \" +\n \"coordinate, this server opens maps://?q=<query> (the name alone, no \" +\n \"coordinate) through LaunchServices and waits, read-only, for the recent Maps \" +\n \"files with a record; the lane then copies that record. The place is \" +\n \"therefore left in Recents, and resolving it can take tens of seconds.\",\n blastRadius:\n \"The store is mirrored by NSPersistentCloudKitContainer, and a lane write goes \" +\n \"with it: on the model whose syncMeasured is true, every one of the five was \" +\n \"seen on a Mac and an iPhone on 2026-11-11, one with Maps quit. Each one is \" +\n \"saved by Cupertino through Maps' own model and only ever copies a place \" +\n \"record Maps minted; a model that does not match the store is refused as \" +\n \"incompatible rather than opened.\",\n }\n : {\n lane:\n \"none: run from npm, this server writes nothing to Maps, whatever \" +\n \"APPLE_MAPS_ALLOW_WRITES says. Maps' writes exist only when Cupertino hosts \" +\n \"this server, through its store lane. The route this package wrote through \" +\n \"itself was retired on 2026-11-11: its inserts were watched never to reach \" +\n \"iCloud (docs/maps.md).\",\n }),\n tools,\n },\n writeLane,\n ...(hosted\n ? {}\n : {\n writeLaneNote:\n \"not hosted by Cupertino: the store lane, and the writes that go through it, \" +\n \"need the app\",\n }),\n },\n store: {\n path: located.storePath,\n exists: located.exists,\n readable: located.readable,\n opened: status.store.opened,\n mode: status.store.mode,\n reason: status.store.reason,\n resolvedByScan: located.resolvedByScan,\n ...status.capabilities,\n },\n files: {\n directory: located.directory,\n localCache: {\n path: located.localCache.path,\n exists: located.localCache.exists,\n note:\n \"The device-local cache. Same entities as the sync store and, on the probed \" +\n \"machine, zero rows in every one of them. Located so it is visibly considered, \" +\n \"never opened.\",\n },\n },\n caveats: [\n \"This store was missed three times before it was found, and the reasons are worth \" +\n \"knowing if it ever looks absent: the file has NO EXTENSION (MapsSync_0.0.1), it \" +\n \"lives in the one directory of Maps' container that Full Disk Access gates, and \" +\n \"`group.com.apple.Maps` is a decoy that is EPERM rather than empty.\",\n \"Columns are resolved BY COVERAGE, not by name. ZHISTORYITEM carries both ZLATITUDE \" +\n \"(1 row of 33) and ZLATITUDE1 (19 of 33); picking the first recognised name would \" +\n \"report that Maps holds almost no coordinates. `entities.*.resolved` above shows \" +\n \"which column actually won for each field.\",\n \"Some favourites have no linked place: 3 of 23 on the probed machine, with no name \" +\n \"and no coordinate. Almost certainly the unconfigured Home / Work / School slots. \" +\n \"They are returned with `linked: false` rather than dropped, because silently \" +\n \"omitting rows reads as a deletion.\",\n \"Collection membership is a many-to-many join table, Z_6PLACES(Z_6COLLECTIONS, \" +\n \"Z_7PLACES) on the probed machine, NOT a column on ZCOLLECTIONITEM — which is why \" +\n \"four guessed column names all missed it. It is re-proved at open time by \" +\n \"reproducing ZPLACESCOUNT exactly, never by matching a name, because \" +\n \"ZCOLLECTIONITEM.ZMAPITEM joins 3 of 10 collections by coincidence. When nothing \" +\n \"reproduces those counts, `collectionMembership` is null, collections list \" +\n \"without their places and every result says so.\",\n \"Refs address a local row id. Core Data reuses those after a delete and this store is \" +\n \"mirrored from CloudKit, so a re-sync can renumber rows. A ref is good for the \" +\n \"current session and should not be stored.\",\n \"Timestamps are placed on an epoch DETECTED from the store, never assumed. The same \" +\n \"value read as unix seconds instead of Core Data seconds lands in 1995 and looks \" +\n \"entirely plausible. When detection fails every date reads null rather than guessed.\",\n ],\n };\n};\n\nexport const registerDiagnosticsTools = (server: McpServer, client: AppleMapsClient): void => {\n server.registerTool(\n \"apple_maps_diagnostics\",\n {\n description:\n \"Report whether Maps' store can be read, which columns were resolved for each entity, \" +\n \"and what this server deliberately cannot do. Start here when a read returns nothing — \" +\n \"this surface has no second lane, so a missing grant means no data at all rather than \" +\n \"slower data.\",\n inputSchema: z.object({}),\n annotations: { readOnlyHint: true },\n },\n async () => wrap(() => buildDiagnostics(client)),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/server\";\nimport { z } from \"zod\";\n\nimport type { AppleMapsClient } from \"../client/maps.js\";\nimport { decodeCollectionRef, decodePlaceRef } from \"../client/ref.js\";\nimport {\n collectionRefArg,\n compact,\n fail,\n limitArg,\n ok,\n placeRefArg,\n queryArg,\n resolveLimit,\n wrapResult,\n} from \"./util.js\";\n\n/**\n * The place tools.\n *\n * Every description states the permission fact plainly. On this surface it is\n * not the usual \"slower without the grant\" — there is no second lane, so\n * without Full Disk Access these tools have nothing to read. Saying so in the\n * description is what stops a model concluding, from an error it half-read,\n * that the person simply has not saved any places.\n */\nexport const registerPlaceTools = (server: McpServer, client: AppleMapsClient): void => {\n server.registerTool(\n \"apple_maps_list_favorites\",\n {\n description:\n \"List the places saved as favourites in Maps, with coordinates, address and the label \" +\n \"the user gave them. Needs Full Disk Access — Maps is not scriptable, so without the \" +\n \"grant this returns an error rather than an empty list. Some entries have no linked \" +\n \"place (`linked: false`); those are the unconfigured Home/Work/School slots, not \" +\n \"broken rows. This is everything SAVED: Maps' own Pinned panel applies display rules \" +\n \"that are not in the store and can show fewer.\",\n inputSchema: z.object({ limit: limitArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ limit }) =>\n wrapResult(async () => {\n const capped = resolveLimit(limit, client.config.maxResults);\n const result = client.places(\"favorite\", { limit: capped });\n const unlinked = result.places.filter((p) => !p.linked).length;\n return ok(\n compact({\n favorites: result.places,\n count: result.places.length,\n unlinked: unlinked\n ? `${unlinked} entr${unlinked === 1 ? \"y has\" : \"ies have\"} no linked place — ` +\n `these are Maps' unconfigured Home/Work/School slots. They are returned rather ` +\n `than dropped, because silently omitting rows reads as a deletion.`\n : undefined,\n /**\n * MEASURED, and the reason the note above no longer claims this count\n * matches the app: on a real store Maps' Pinned panel showed 17 while\n * this tool returned 24. Three extras were the unlinked slots; four\n * were ordinary favourites with names, addresses and coordinates, one\n * an exact duplicate of a shown entry.\n *\n * No column in ZFAVORITEITEM separates them — ZHIDDEN, ZSOURCE, ZTYPE\n * and ZVERSION were all cross-tabulated and none yields a group of\n * four. `ZVERSION = 2` has exactly 17 rows and is a COINCIDENCE OF\n * TOTALS: 16 of them are linked while all 17 shown entries are. So\n * Maps applies display rules this server cannot see — de-duplication\n * is the visible one — and no filter written here could reproduce\n * them. Saying so beats guessing, and beats the old note, which\n * asserted the opposite of what was measured. See docs/maps.md.\n */\n mayExceedApp:\n \"Maps' own Pinned panel can show FEWER places than this. It applies display \" +\n \"rules — de-duplication at least — that are not recorded in the store, so this \" +\n \"is everything saved, not everything shown.\",\n truncated: result.truncated\n ? `More favourites exist beyond limit=${capped}.`\n : undefined,\n datesUnavailable: result.datesAvailable\n ? undefined\n : \"Timestamps could not be placed on a known epoch, so every date reads null. \" +\n \"They are withheld rather than guessed — see apple_maps_diagnostics.\",\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_list_collections\",\n {\n description:\n \"List the collections (Guides) in Maps. Each carries Maps' own count of the places in \" +\n \"it. Use apple_maps_list_collection_places to enumerate one. Needs Full Disk Access.\",\n inputSchema: z.object({ limit: limitArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ limit }) =>\n wrapResult(async () => {\n const capped = resolveLimit(limit, client.config.maxResults);\n const result = client.collections({ limit: capped });\n return ok(\n compact({\n collections: result.collections,\n count: result.collections.length,\n // The guides do not account for every saved place, and silence\n // about that reads as \"there are no others\".\n unfiled:\n result.unfiled && result.unfiled > 0\n ? `${result.unfiled} saved place(s) are in no collection. ` +\n `List them with apple_maps_list_unfiled_places.`\n : undefined,\n // The honest version of a capability this server may not have.\n itemsUnavailable: result.itemsEnumerable\n ? undefined\n : \"This store does not expose how an item belongs to a collection, so the places \" +\n \"inside a collection cannot be listed. `placesCount` is Maps' own number and is \" +\n \"still accurate; apple_maps_list_collection_places will return nothing.\",\n truncated: result.truncated\n ? `More collections exist beyond limit=${capped}.`\n : undefined,\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_list_collection_places\",\n {\n description:\n \"List the places filed in one collection, by its ref. Needs Full Disk Access. Returns \" +\n \"nothing when this store does not expose collection membership — check \" +\n \"apple_maps_diagnostics, which reports whether the key was resolved.\",\n inputSchema: z.object({ ref: collectionRefArg, limit: limitArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ ref, limit }) =>\n wrapResult(async () => {\n const collectionId = client.collectionRowId(decodeCollectionRef(ref));\n // A ref that resolves to no row is a REFUSAL, not \"no filter\".\n //\n // `null ?? undefined` dropped the membership clause entirely, and\n // `places()` only applies it when the id is defined — so a stale or\n // mistyped ref listed every place from every guide as though they all\n // belonged to this one.\n if (collectionId === null) {\n return fail(\n `No collection matches ${ref}. Refs come from apple_maps_list_collections and go ` +\n \"stale when a guide is deleted or renamed away.\",\n );\n }\n const capped = resolveLimit(limit, client.config.maxResults);\n const result = client.places(\"collection-item\", { limit: capped, collectionId });\n const collections = client.collections({ limit: 1_000 });\n if (!collections.itemsEnumerable) {\n return fail(\n \"This store does not expose which collection an item belongs to, so its places \" +\n \"cannot be listed. The collection itself and its place count are still readable \" +\n \"through apple_maps_list_collections.\",\n );\n }\n return ok(\n compact({\n places: result.places,\n count: result.places.length,\n truncated: result.truncated ? `More places exist beyond limit=${capped}.` : undefined,\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_list_unfiled_places\",\n {\n description:\n \"List saved places that are in no collection. Maps files a saved place into a Guide \" +\n \"through a join table, and a place can exist with no row there — 12 of 30 on the probed \" +\n \"machine, 7 of which appear nowhere else in the store: not as a favourite, not in \" +\n \"another Guide, not in recents. Those are reachable through no other tool. Needs Full \" +\n \"Disk Access. Returns nothing when collection membership could not be resolved, which \" +\n \"apple_maps_diagnostics reports.\",\n inputSchema: z.object({ limit: limitArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ limit }) =>\n wrapResult(async () => {\n const collections = client.collections({ limit: 1 });\n if (!collections.itemsEnumerable) {\n return fail(\n \"This store does not expose which collection an item belongs to, so places in no \" +\n \"collection cannot be told apart from places in one. \" +\n \"apple_maps_list_collections still works.\",\n );\n }\n const capped = resolveLimit(limit, client.config.maxResults);\n const result = client.places(\"collection-item\", {\n limit: capped,\n unfiled: true,\n });\n return ok(\n compact({\n places: result.places,\n count: result.places.length,\n truncated: result.truncated ? `More places exist beyond limit=${capped}.` : undefined,\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_list_recents\",\n {\n description:\n \"List the places recently looked at in Maps, newest first. This is Maps' Recents list, \" +\n \"not a search history: it holds places, directions and searches the user actually \" +\n \"opened. Needs Full Disk Access.\",\n inputSchema: z.object({ limit: limitArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ limit }) =>\n wrapResult(async () => {\n const capped = resolveLimit(limit, client.config.maxResults);\n const result = client.places(\"history\", { limit: capped });\n const named = result.places.filter((p) => p.name).length;\n return ok(\n compact({\n recents: result.places,\n count: result.places.length,\n // MEASURED: 1 of 33 rows carried a name. A recent's place name\n // lives in the linked map item's undecoded blob, not in a column,\n // so most rows have coordinates and no label. Saying so stops a\n // caller reporting \"33 unnamed places\" as if the data were damaged.\n namesUnavailable:\n result.places.length > 0 && named * 4 < result.places.length\n ? `Only ${named} of ${result.places.length} entries carry a name. Maps keeps a ` +\n `recent's place name in an encoded record this server does not decode, so most ` +\n `rows have coordinates and dates but no label. This is the store's shape, not ` +\n `missing data.`\n : undefined,\n truncated: result.truncated ? `More entries exist beyond limit=${capped}.` : undefined,\n datesUnavailable: result.datesAvailable\n ? undefined\n : \"Timestamps could not be placed on a known epoch, so every date reads null.\",\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_search_places\",\n {\n description:\n \"Search every saved place — favourites, collection entries and recents — by name, by \" +\n \"the label the user gave it, or by address. Returns each match with the kind of entry \" +\n \"it came from. Needs Full Disk Access. This searches what is SAVED on this Mac; it \" +\n \"does not search Apple's map of the world.\",\n inputSchema: z.object({ query: queryArg, limit: limitArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ query, limit }) =>\n wrapResult(async () => {\n const capped = resolveLimit(limit, client.config.maxResults);\n const result = client.search({ query, limit: capped });\n return ok(\n compact({\n places: result.places,\n count: result.places.length,\n truncated: result.truncated ? `More matches exist beyond limit=${capped}.` : undefined,\n }),\n );\n }),\n );\n\n server.registerTool(\n \"apple_maps_get_place\",\n {\n description:\n \"Get one saved place by its ref, with coordinates, address and dates. Needs Full Disk \" +\n \"Access.\",\n inputSchema: z.object({ ref: placeRefArg }),\n annotations: { readOnlyHint: true, idempotentHint: true },\n },\n async ({ ref }) =>\n wrapResult(async () => {\n const { kind, key } = decodePlaceRef(ref);\n const place = client.place(kind, key);\n if (!place) {\n return fail(\n \"uuid\" in key\n ? `No place for that ref. It was removed in Maps, or it belongs to a different ` +\n `store than the one being read.`\n : `No place for that ref. It may have been removed in Maps, or iCloud may have ` +\n `re-synced the store and renumbered the rows since the listing ran — this ref ` +\n `carries a row id, which only this store's current numbering can resolve. ` +\n `Re-run the listing for a current ref.`,\n );\n }\n return ok({ place });\n }),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/server\";\n\nimport type { AppleMapsClient } from \"../client/maps.js\";\nimport { registerDiagnosticsTools } from \"./diagnostics.js\";\nimport { registerPlaceTools } from \"./places.js\";\nimport { registerStoreWriteTools } from \"./store-writes.js\";\n\nexport type ToolContext = {\n /**\n * Gates the mutating tools, which are NOT registered when it is false, so a\n * host that has not opted in is never told they exist.\n *\n * It is necessary and not sufficient. Maps has no scripting dictionary and\n * no App Intents to write through, so its one write route is Cupertino's\n * store lane, which saves with Maps' own Core Data model; on 2026-11-11 every\n * one of its five writes was seen on a Mac and an iPhone, one with Maps quit.\n * Run from npm there is no lane, and this server registers no write tool\n * whatever this says. The SQL and Accessibility routes it once had were\n * retired the same day: the watch found the SQL inserts never mirrored to\n * iCloud, and saw Maps convert favourites that look like them (no mirror\n * row, no `shortcutIdentifier`, a small `positionIndex`) into saved places.\n * `docs/maps.md` carries\n * the measurements. The rule that outlived them: never fabricate a place\n * record, only copy one Maps wrote itself.\n */\n allowWrites: boolean;\n};\n\n/**\n * Register the Apple Maps tools.\n *\n * The registered set does NOT vary with whether the store opened. That is a\n * runtime condition and MCP clients cache the tool list, so a list that shrank\n * without Full Disk Access would stay shrunk after the grant was given. Every\n * tool is registered on a machine with no grant at all; each fails with an\n * error that says which permission is missing.\n */\nexport const registerTools = (\n server: McpServer,\n client: AppleMapsClient,\n ctx: ToolContext,\n): void => {\n registerDiagnosticsTools(server, client);\n registerPlaceTools(server, client);\n if (!ctx.allowWrites) return;\n // The store lane exists only when Cupertino hosts this server. Without it\n // there is no write route, and registering tools that could only refuse\n // would tell a host about a capability it does not have.\n //\n // Whether the lane is compatible is not asked here: MCP clients cache the\n // list, and opening the lane connects nothing. An incompatible lane refuses\n // per call, naming the mismatch.\n const lane = client.lane;\n if (lane) registerStoreWriteTools(server, client, lane);\n};\n","import { type Logger, registerSurfaceResources, withLazyTools } from \"@mgcrea/mcp-apple-core\";\nimport { McpServer } from \"@modelcontextprotocol/server\";\n\nimport { BUILD_INFO } from \"./build-info.js\";\nimport { AppleMapsClient } from \"./client/maps.js\";\nimport type { Config } from \"./config.js\";\nimport { MAPS_GUIDE } from \"./guide.js\";\nimport { registerPrompts } from \"./prompts.js\";\nimport { buildDiagnostics } from \"./tools/diagnostics.js\";\nimport { registerTools } from \"./tools/index.js\";\n\nexport const SERVER_NAME = BUILD_INFO.name;\nexport const SERVER_VERSION = BUILD_INFO.version;\n\nexport type CreateServerOptions = {\n config: Config;\n logger?: Logger;\n /** Injected by tests so discovery never reaches the developer's real home. */\n home?: string;\n};\n\nexport type CreatedServer = {\n server: McpServer;\n client: AppleMapsClient;\n};\n\n/**\n * Build the server. Side-effect free: it opens no database and reads no file,\n * so a test can construct it freely and every external dependency arrives\n * through an option.\n *\n * There is no `osascript` seam here, unlike every other surface. This server\n * never spawns one — Maps is not scriptable, so there is no Apple Events lane\n * to inject a fake for. Its absence is the point.\n */\nexport const createServer = (opts: CreateServerOptions): CreatedServer => {\n const { config } = opts;\n const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });\n\n const client = new AppleMapsClient({\n config,\n ...(opts.logger ? { logger: opts.logger } : {}),\n ...(opts.home ? { home: opts.home } : {}),\n });\n\n withLazyTools(\n server,\n {\n surface: \"maps\",\n displayName: \"Maps\",\n lazy: config.lazyTools,\n allowWrites: config.allowWrites,\n },\n (target, allowWrites) => registerTools(target, client, { allowWrites }),\n );\n /*\n * One flag, both primitives — see `exposePrompts` in core's config. A prompt\n * embeds its surface guide, so registering prompts without the resources\n * would leave every expansion naming a `cupertino://maps/guide` that this\n * server does not serve.\n */\n if (config.exposePrompts) {\n registerPrompts(server);\n registerSurfaceResources(server, {\n surface: \"maps\",\n displayName: \"Maps\",\n guide: MAPS_GUIDE,\n diagnostics: () => buildDiagnostics(client),\n // No inventory. Favourites, collections and recents are three queries\n // rather than three named containers, and a caller does not address them\n // by name the way they address a mailbox or a folder.\n });\n }\n\n return { server,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,eAAe,GAAG;EACxC,MAAM,QAAQ,OAAO,MAAM,MAAM,GAAG;EACpC,IAAI,CAAC,OACH,OAAO,KACL,UAAU,MACN,+GAEA,yQAIN;EAEF,OAAO,GAAG,EAAE,MAAM,CAAC;CACrB,CAAC,CACL;AACF;;;;;;;;;;;;ACrQA,MAAa,iBACX,QACA,QACA,QACS;CACT,yBAAyB,QAAQ,MAAM;CACvC,mBAAmB,QAAQ,MAAM;CACjC,IAAI,CAAC,IAAI,aAAa;CAQtB,MAAM,OAAO,OAAO;CACpB,IAAI,MAAM,wBAAwB,QAAQ,QAAQ,IAAI;AACxD;;;AC3CA,MAAa,cAAc,WAAW;AACtC,MAAa,iBAAiB,WAAW;;;;;;;;;;AAuBzC,MAAa,gBAAgB,SAA6C;CACxE,MAAM,EAAE,WAAW;CACnB,MAAM,SAAS,IAAI,UAAU;EAAE,MAAM;EAAa,SAAS;CAAe,CAAC;CAE3E,MAAM,SAAS,IAAI,gBAAgB;EACjC;EACA,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;EAC7C,GAAI,KAAK,OAAO,EAAE,MAAM,KAAK,KAAK,IAAI,CAAC;CACzC,CAAC;CAED,cACE,QACA;EACE,SAAS;EACT,aAAa;EACb,MAAM,OAAO;EACb,aAAa,OAAO;CACtB,IACC,QAAQ,gBAAgB,cAAc,QAAQ,QAAQ,EAAE,YAAY,CAAC,CACxE;CAOA,IAAI,OAAO,eAAe;EACxB,gBAAgB,MAAM;EACtB,yBAAyB,QAAQ;GAC/B,SAAS;GACT,aAAa;GACb,OAAO;GACP,mBAAmB,iBAAiB,MAAM;EAI5C,CAAC;CACH;CAEA,OAAO;EAAE;EAAQ;CAAO;AAC1B"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mgcrea/mcp-apple-maps",
3
- "version": "1.38.0",
4
- "description": "Read and act on Apple Maps — favourites, Guides and recents, writes off by default",
3
+ "version": "1.42.0",
4
+ "description": "Read Apple Maps — favourites, Guides and recents; writes only when Cupertino hosts it",
5
5
  "keywords": [
6
6
  "apple",
7
7
  "apple-maps",
@@ -49,7 +49,7 @@
49
49
  "dependencies": {
50
50
  "@modelcontextprotocol/server": "^2.4.0",
51
51
  "zod": "^4.5.4",
52
- "@mgcrea/mcp-apple-core": "^1.38.0"
52
+ "@mgcrea/mcp-apple-core": "^1.42.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@modelcontextprotocol/client": "^2.4.0",