dwelldelta-mcp 0.7.0 → 0.9.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.
package/README.md CHANGED
@@ -17,9 +17,11 @@ Six read-only tools, and one that adds the user's own rent when they ask:
17
17
  | `contribute_rent` | adds the user's own rent, anonymously, to DwellDelta's suburb benchmarks - only when the user asks, and only after they have read and agreed to the consent wording (from 0.5.0) |
18
18
 
19
19
  It runs on your own machine over stdio. It records nothing and sends nothing about you unless you choose to add
20
- your rent. At start it fetches the week's indicators from tools.dwelldelta.com.au - one request for one public
21
- file; nothing about you or your questions is sent - and otherwise uses the copy it ships with. Set
22
- `DWELLDELTA_OFFLINE=1` and that fetch is not made. Nothing it says is a forecast, a valuation or advice.
20
+ your rent. At start it fetches DwellDelta's published files from tools.dwelldelta.com.au - the week's indicators,
21
+ the rents and sale prices it answers from, and (from 0.9.0) the ABS rents index behind `rent_check`, nine public
22
+ files in all, the same for everyone; nothing about you or your questions is sent - and otherwise uses the copies it
23
+ ships with. Set `DWELLDELTA_OFFLINE=1` and none of those nine files is fetched; adding a rent with `contribute_rent` still sends it, as you asked. Nothing it says is a
24
+ forecast, a valuation or advice.
23
25
 
24
26
  ## Adding a rent (from 0.5.0)
25
27
 
@@ -40,7 +42,9 @@ type, because a sale price without it answers nobody's question, and carries the
40
42
  its limits. DCJ reports a quarter when about 80% of its sales have been notified, so the counts are incomplete
41
43
  and the sales quarter runs behind the rents quarter. DCJ's own table has rows that a few very large sales, or
42
44
  many sales at one identical price, have set: the answer marks those lines UNUSUAL and says not to quote them as
43
- a going price. Prices in the structured result stay in DCJ's unit, thousands of dollars, and `unit` says so.
45
+ a going price. Where the published file notes that a total is mostly the sales of such a row (its
46
+ `unusual_part` field), releases from 0.8.0 say so on that total's line, and say only that its median and its
47
+ change may be moved by that row's sales. Prices in the structured result stay in DCJ's unit, thousands of dollars, and `unit` says so.
44
48
  The feed is public at <https://tools.dwelldelta.com.au/market/nsw-sales.json>.
45
49
 
46
50
  ## Use it
@@ -76,6 +80,25 @@ https://tools.dwelldelta.com.au/market/nsw-rents.json, `qld-rents.json` and `wa-
76
80
  at start the way it reads the indicators, and `DWELLDELTA_STATE_RENTS_DIR` points it at a folder of copies.
77
81
  Victoria, measured differently again, stays in `vic_rents`.
78
82
 
83
+ ### By dwelling type and bedrooms (from 0.8.0)
84
+
85
+ Give `area_rents` a `dwelling_type`, a number of `bedrooms`, or both, and for NSW and Queensland it answers with
86
+ the publisher's own figure for that kind of home - a two-bedroom unit, a three-bedroom house - under the
87
+ publisher's own label. One of the two is enough: a type gives every size the publisher reports for it, a size
88
+ every type. A combination with no published median is said to have none; it is never filled from the
89
+ all-dwellings figure, a neighbouring area or a wider group. Many of these figures rest on few bonds, and each
90
+ small sample is marked. The Residential Tenancies Authority does not define its labels: reading "Flat 2" as a
91
+ two-bedroom flat is DwellDelta's reading, and every Queensland answer says so. WA's bond records carry neither
92
+ dwelling type nor bedrooms, so WA has no such figures. DCJ's largest size is "4 or more Bedrooms": a number above
93
+ four is answered under that label, and the answer says it is not for that number alone. A number followed by a
94
+ plus means "or more", which only that one size has; anything else with a plus is refused, not answered as exactly
95
+ that many.
96
+
97
+ The two files (https://tools.dwelldelta.com.au/market/nsw-rents-by-type.json and `qld-rents-by-type.json`) are
98
+ large and are not bundled. The server asks for them once at start, without waiting for them, and never in
99
+ response to a question. Offline, put copies in the folder `DWELLDELTA_STATE_RENTS_DIR` names; without them a
100
+ by-type question fails with the next step, and every other answer is unaffected.
101
+
79
102
  It is listed in the MCP registry as `au.com.dwelldelta/dwelldelta`.
80
103
 
81
104
  ## What an agent gets back
@@ -92,6 +115,63 @@ ships with, and the bundled copy when offline. Once a snapshot is more than 10 d
92
115
  words and in the structured result, rather than passing an old figure off as current. Set `DWELLDELTA_INDICATORS`
93
116
  to read another snapshot file.
94
117
 
118
+ The ABS rents index behind `rent_check` is DwellDelta's copy at
119
+ https://tools.dwelldelta.com.au/rent/data/rents-index.json, updated with each monthly ABS release. Up to 0.8.0 the
120
+ server read only the copy bundled when the package was made, so `rent_check` answered only to that copy's latest
121
+ month and nothing in the answer said the index had moved on. From 0.9.0 it fetches the published copy once at
122
+ start, like every other file, and uses it when it is well formed (source, attribution, licence and release named;
123
+ every city the bundled copy has, each a run of contiguous months with positive index values), covers the bundled
124
+ copy city by city (each city's series starts no later and ends no earlier than in the bundled copy) and has no month
125
+ later than the current one; otherwise, or with `DWELLDELTA_OFFLINE=1`, the bundled copy answers.
126
+ `data_as_of` and the `Cite:` line's period say which month the answer runs to.
127
+
128
+ ### Checkable provenance (from 0.9.0)
129
+
130
+ Every answer that gives a figure ends with a `Cite:` line to quote with it: the source, the period, the licence id
131
+ (SPDX, e.g. `CC-BY-4.0`), n (the number of bonds, leases or sales the figure rests on, or why there is none), the
132
+ source's URL (or, where the file names only one, the publisher's copyright notice, labelled so), and DwellDelta's
133
+ published data file. The structured result says the same, in new fields; every field above keeps its meaning:
134
+
135
+ - each entry of `sources` adds `licence_id`, `licence_url`, `source_url`, `source_notice_url`, `feed_url` and
136
+ `period`. `source_url` is only ever an address of the data's own page that the data file itself holds: for WA
137
+ the National Housing Data Exchange dataset page, for Victoria the DataVic page in its source line. It is null
138
+ where the file holds none - DCJ's files (NSW rents, rents by type, sale prices), the RTA's (Queensland), the ABS
139
+ rents index and the indicators snapshot. DCJ's and the RTA's files name only a copyright notice
140
+ (https://dcj.nsw.gov.au/statements/copyright-and-disclaimer.html, which DCJ's attribution also names, and
141
+ https://www.rta.qld.gov.au/copyright; the RTA's attribution names no URL): that is `source_notice_url`, and the
142
+ `Cite:` line labels it `copyright notice`, never `source URL`. `feed_url` is the file at tools.dwelldelta.com.au
143
+ the figure came from, to fetch and check.
144
+ - `stale` and `stale_reason` keep the meaning they have had since 0.2.0: the weekly indicators snapshot is more
145
+ than 10 days old. They are `false` / `null` on every answer without a snapshot (rents, sale prices,
146
+ `rent_check`). `stale_after` is the day the snapshot turns stale (null without one); `cadence` is `weekly`,
147
+ `quarterly` or `monthly`.
148
+ - `period_due_by`, `period_overdue` and `period_overdue_reason` (new) come from the data's own release cadence:
149
+ `period_due_by` is the day by which the release after this period was due, and `period_overdue` is true once it
150
+ has passed with no newer file. A quarterly rents file is overdue once its quarter ended more than seven months
151
+ ago (the next quarter, plus the publisher's lag), NSW sale prices after ten (DCJ's sales run a quarter behind its
152
+ rents), and the ABS monthly rents index two months after its latest month. An overdue answer opens with a
153
+ `STALE:` line giving the reason, and its `Cite:` line ends `; STALE.` - as an old snapshot's does.
154
+ - `figures` (`area_rents`, with or without `dwelling_type` and `bedrooms`, `vic_rents`, `nsw_sale_prices`): one
155
+ entry per figure of the answer, with `n`, `n_band` (where the publisher withholds the exact count), `unit`,
156
+ `small_sample` and `refusal`. `refusals` lists the refused ones, `all_refused` says whether anything may be
157
+ quoted, and `sample_rule` is the publisher's rule.
158
+ - A figure that rests on too few records is a refusal, never a weak number: `{ refused: true, type:
159
+ "too_few_records", reason, n, n_band, unit, min_n, rule }` (`type` is `not_published` for a combination the
160
+ publisher does not list). The rules are each file's own: DCJ reports nothing for 10 or fewer bonds or sales
161
+ (`min_n` 11), a WA locality needs 10 bonds, and the RTA and Homes Victoria withhold small medians without
162
+ stating a number. A median the file gives below its rule is refused in the text as well; the file's own figure
163
+ is left as it is in the structured rows.
164
+ - Each structured row says on itself whether the text refused its figure (from 0.9.0; additions only - no field a
165
+ row had is changed or removed): `refused: true` and `refusal_type` (`too_few_records` or `not_published`, the same
166
+ as the refusal's `type`) on a refused row, `refused: false` and `refusal_type: null` on a row whose figure is
167
+ given. The rows are `area_rents`' `state_total`, `regions`, `councils` and `areas` (every state), its by-type
168
+ `rows` (NSW and Queensland), `vic_rents`' `regions` and `suburb_groups`, and in `nsw_sale_prices` each place's
169
+ `total`, `non_strata` and `strata` row. So a refused row's weak `median_weekly_rent_aud` (or `median_price_k_aud`)
170
+ is never read as a figure by an agent that reads only the rows. A sale-prices dwelling type with no row in DCJ's
171
+ table stays `null`, as the file has it - there is no figure on it to misread - and its `not_published` refusal is
172
+ in `refusals`.
173
+ - `rent_check` and `market_indicators` say `sample_size: null` and why: an index and these indicators have no count.
174
+
95
175
  ## Licence
96
176
 
97
177
  The code is MIT (see LICENSE). The data is not: each figure keeps its source's licence and attribution, which every
@@ -100,5 +180,6 @@ answer states - for example ABS data is CC BY 4.0, "Based on Australian Bureau o
100
180
  ## Development
101
181
 
102
182
  `npm test` here starts the server and calls the six read-only tools, and the first (consent) call of
103
- `contribute_rent`, over MCP; the repository's root `npm test` holds the
183
+ `contribute_rent`, over MCP, and `test/provenance.test.mjs` holds the provenance above on the vendored files and
184
+ fixtures; the repository's root `npm test` holds the
104
185
  tool answers themselves and checks that `vendor/` matches its sources. `npm pack` runs `scripts/vendor.mjs` first.
@@ -11,11 +11,15 @@
11
11
  * else the published file (fetched once at start - one public file each; nothing about the user or their questions is
12
12
  * sent - and used if well formed, for the right state, and not older than the bundled copy), else the copy bundled at
13
13
  * pack time. DWELLDELTA_OFFLINE=1 never fetches. The data changes once a quarter, so every answer states its quarter.
14
+ *
15
+ * With dwelling_type or bedrooms (from 0.8.0) NSW and Queensland answer from their by-type
16
+ * files instead - see "by dwelling type and bedrooms" at the end of this file.
14
17
  */
15
18
  import { existsSync } from "node:fs";
16
19
  import { fileURLToPath } from "node:url";
17
20
  import { dirname, join } from "node:path";
18
- import { loadJson, envelope, ToolError, FOOTER, FETCH_TIMEOUT_MS } from "./tools.mjs";
21
+ import { loadJson, envelope, ToolError, FOOTER, FETCH_TIMEOUT_MS, feedSource, CADENCE, SAMPLE_RULES, judgeFigure,
22
+ figureFields, nWords, citeLine, staleNote, flagged, refusalMark } from "./tools.mjs";
19
23
  import { quarterKey } from "./vic-rents-tool.mjs";
20
24
 
21
25
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -28,10 +32,14 @@ export const STATES = {
28
32
  QLD: { file: "qld-rents.json", name: "Queensland",
29
33
  hint: "Queensland rents are by suburb, as the RTA names it (area: \"Acacia Ridge\"; part of a name works), " +
30
34
  "or by council (council: \"Brisbane\")." },
31
- WA: { file: "wa-rents.json", name: "Western Australia",
35
+ // WA's source_notice is the Housing Data Exchange page of the bond records themselves, so it is the source's URL.
36
+ // NSW's and Queensland's are DCJ's and the RTA's copyright notices: a notice, never called the source URL.
37
+ WA: { file: "wa-rents.json", name: "Western Australia", notice_is_data: true,
32
38
  hint: "WA rents are by locality (area: \"Fremantle\"; part of a name works). There are no councils in the " +
33
39
  "bond records." },
34
40
  };
41
+ /** Each state's small-sample rule (tools.mjs SAMPLE_RULES): below it a figure is refused, never given. */
42
+ export const RULES = { NSW: SAMPLE_RULES.NSW_RENTS, QLD: SAMPLE_RULES.QLD_RENTS, WA: SAMPLE_RULES.WA_RENTS };
35
43
  /** Rows shown in one answer; a wider match says how many more there are instead of dropping them silently. */
36
44
  export const MAX_ROWS = 25;
37
45
 
@@ -71,15 +79,24 @@ export async function loadAllAreaRents(opts) {
71
79
 
72
80
  // Exported for sale-prices-tool.mjs (0.7.0), which matches names and words figures the same way.
73
81
  export const norm = (s) => String(s).trim().toLowerCase();
74
- export const dollars = (v) => `$${v.toLocaleString("en-AU")}`;
82
+ // Cents as two digits ($872.50, a WA median between two bonds), whole dollars as $650 - as the site prints them
83
+ // since tools #27 (2026-10-17).
84
+ export const dollars = (v) => { const n = Number(v); return `$${n.toLocaleString("en-AU", Number.isInteger(n) ? {} : { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; };
75
85
  export const signed = (v) => `${v >= 0 ? "+" : ""}${v}%`;
76
86
 
77
- function line(r, name) {
78
- if (r.median_weekly_rent_aud == null) {
79
- const why = r.withheld ?? (r.new_bonds == null ? "too few bonds"
80
- : `${r.new_bonds} new bond${r.new_bonds === 1 ? "" : "s"} - too few for a median`);
81
- return `${name}: no median (${why}).`;
82
- }
87
+ /** Why a row has no median, in the words the answer has always used. */
88
+ const whyNone = (r) => r.withheld ?? (r.new_bonds == null ? "too few bonds"
89
+ : `${r.new_bonds} new bond${r.new_bonds === 1 ? "" : "s"} - too few for a median`);
90
+
91
+ /** One figure's sample and, if it rests on too few bonds, its refusal (see judgeFigure in tools.mjs). */
92
+ export const rentFigure = (r, name, rule) => judgeFigure(r, { name, median: "median_weekly_rent_aud", count: "new_bonds",
93
+ band: "new_bonds_band", rule, why: r && r.median_weekly_rent_aud == null ? whyNone(r) : null });
94
+
95
+ function line(r, name, rule = null) {
96
+ if (r.median_weekly_rent_aud == null) return `${name}: no median (${whyNone(r)}).`;
97
+ // A median below the publisher's own rule is refused, not printed: never a weak number.
98
+ const refusal = rule ? rentFigure(r, name, rule).refusal : null;
99
+ if (refusal) return `${name}: no median (${refusal.reason}).`;
83
100
  const bonds = r.new_bonds_band ? ` from ${r.new_bonds_band} new bonds (the publisher withholds the count)`
84
101
  : r.new_bonds == null ? "" : ` from ${r.new_bonds.toLocaleString("en-AU")} new bonds`;
85
102
  const change = r.change_pct == null ? ""
@@ -110,8 +127,13 @@ export function nswPostcodes(wanted, suburbs, feed) {
110
127
  return found.slice(0, 5).map((m) => `${m[1]} is in postcode ${m[2]}`);
111
128
  }
112
129
 
113
- /** area_rents: one state; an area (postcode, suburb or locality), a council, or neither for the state's own row. */
114
- export function areaRentsResult({ state, area, council } = {}, feeds, now = new Date(), { nswSuburbs = [] } = {}) {
130
+ /**
131
+ * area_rents: one state; an area (postcode, suburb or locality), a council, or neither for the state's own row.
132
+ * With dwelling_type or bedrooms the answer comes from that state's by-type file instead (byType[state], loaded at
133
+ * start by loadAllRentsByType) - see byTypeResult below.
134
+ */
135
+ export function areaRentsResult({ state, area, council, dwelling_type, bedrooms } = {}, feeds, now = new Date(),
136
+ { nswSuburbs = [], byType = {} } = {}) {
115
137
  const info = STATES[state];
116
138
  if (!info) {
117
139
  throw new ToolError(`No area rents for ${JSON.stringify(state)}.`,
@@ -143,6 +165,9 @@ export function areaRentsResult({ state, area, council } = {}, feeds, now = new
143
165
  }
144
166
  }
145
167
  const whole = !areas.length && !councils.length;
168
+ if (wantsByType({ dwelling_type, bedrooms })) {
169
+ return byTypeResult({ state, info, feed, dwelling_type, bedrooms, whole, areas, councils, file: byType[state] }, now);
170
+ }
146
171
  if (whole) regions = feed.regions;
147
172
  const dropped = [];
148
173
  for (const [label, rows] of [[kind, areas], ["council", councils]]) {
@@ -150,15 +175,24 @@ export function areaRentsResult({ state, area, council } = {}, feeds, now = new
150
175
  }
151
176
  areas = areas.slice(0, MAX_ROWS);
152
177
  councils = councils.slice(0, MAX_ROWS);
153
- const env = envelope({ sources: [{ source: feed.source, licence: feed.licence, attribution: feed.attribution }],
154
- dataAsOf: feed.quarter, origin: feed.origin ?? null }, now);
178
+ const rule = RULES[state];
179
+ const feedUrl = PUBLISHED_BASE + info.file;
180
+ const env = envelope({ sources: [feedSource(feed, feedUrl, feed.quarter, { noticeIsData: info.notice_is_data === true })],
181
+ dataAsOf: feed.quarter,
182
+ origin: feed.origin ?? null, cadence: CADENCE.rents_quarterly }, now);
183
+ // Every line, in the order the answer gives them: its name, its row.
184
+ const shown = [...(whole ? [[`${info.name} (whole state)`, feed.state_total]] : []),
185
+ ...regions.map((r) => [`${r.region} (region)`, r]), ...councils.map((r) => [`${r.council} (council)`, r]),
186
+ ...areas.map((r) => [`${r.area} (${kind})`, r])];
187
+ const figures = shown.map(([name, r]) => rentFigure(r, name, rule));
188
+ // Each row as the file gives it, plus its own refusal marker (a copy: the loaded feed is never written to).
189
+ const judged = new Map(shown.map(([, r], i) => [r, figures[i]]));
190
+ const marked = (r) => ({ ...r, ...refusalMark(judged.get(r)) });
155
191
  const text = [
192
+ ...staleNote(env),
156
193
  `${feed.what}. Quarter: ${feed.quarter}, against ${feed.compared_with}.`,
157
194
  "",
158
- ...(whole ? [line(feed.state_total, `${info.name} (whole state)`)] : []),
159
- ...regions.map((r) => line(r, `${r.region} (region)`)),
160
- ...councils.map((r) => line(r, `${r.council} (council)`)),
161
- ...areas.map((r) => line(r, `${r.area} (${kind})`)),
195
+ ...shown.map(([name, r]) => line(r, name, rule)),
162
196
  ...dropped,
163
197
  ...(whole ? ["", `${feed.areas.length.toLocaleString("en-AU")} ${kind} rows` +
164
198
  `${feed.councils.length ? ` and ${feed.councils.length} councils` : ""} are available: call again with area` +
@@ -169,10 +203,269 @@ export function areaRentsResult({ state, area, council } = {}, feeds, now = new
169
203
  "",
170
204
  `Source: ${feed.attribution}`,
171
205
  `What DwellDelta changed: ${feed.changes_made}`,
206
+ citeLine({ source: feed.source, period: `${feed.quarter} (against ${feed.compared_with})`, licence: feed.licence,
207
+ n: nWords(figures, rule.unit), url: env.sources[0].source_url, notice: env.sources[0].source_notice_url,
208
+ feedUrl, stale: flagged(env) }),
172
209
  FOOTER,
173
210
  ].join("\n");
174
211
  return { text, structured: { ...env, state, state_name: info.name, area_kind: kind, quarter: feed.quarter,
175
212
  compared_with: feed.compared_with, derived: feed.derived === true,
176
- state_total: whole ? feed.state_total : null, regions, councils, areas,
177
- truncated: dropped.length > 0, limits: feed.limits, changes_made: feed.changes_made } };
213
+ state_total: whole ? marked(feed.state_total) : null, regions: regions.map(marked),
214
+ councils: councils.map(marked), areas: areas.map(marked),
215
+ truncated: dropped.length > 0, limits: feed.limits, changes_made: feed.changes_made,
216
+ ...figureFields(figures), sample_rule: rule } };
217
+ }
218
+
219
+ // --- by dwelling type and bedrooms --------------------------------------------------------------------------------
220
+ // From 0.8.0 (prepared 2026-10-10; not in 0.7.0). "What does a two-bedroom unit rent for there?" is the
221
+ // question people ask, and the feeds above answer only for all dwellings together. NSW and Queensland publish a
222
+ // companion file each (market/{nsw,qld}-rents-by-type.json); WA's bond records carry neither dwelling type nor
223
+ // bedrooms, so WA has none.
224
+ //
225
+ // The files are large (1.3 MB and 0.4 MB) and are not bundled: they load from DWELLDELTA_STATE_RENTS_DIR, the
226
+ // owner's live store, or the published address - asked for once, at start, like every other file and never in
227
+ // response to a question, so a request still says nothing about the user or what they asked. The server does not
228
+ // wait for them: the first by-type question does. Offline, with no folder of copies, a by-type question fails with
229
+ // the next step, and the all-dwellings answer is unaffected.
230
+ //
231
+ // Every figure is the publisher's cell under the publisher's own label. A combination the file does not list has NO
232
+ // published median - it is said, with the file's own words for what that means, and never filled from a
233
+ // neighbouring area, a wider group or the all-dwellings figure. The RTA does not define "Flat 2": reading it as a
234
+ // two-bedroom flat is DwellDelta's reading, and the answer carries the file's sentence saying so.
235
+ export const BY_TYPE = { NSW: "nsw-rents-by-type.json", QLD: "qld-rents-by-type.json" };
236
+ export const BY_TYPE_TIMEOUT_MS = 20000;
237
+ /** Places answered by type in one call: each can run to a dozen lines. */
238
+ export const MAX_TYPE_PLACES = 5;
239
+
240
+ export const wantsByType = ({ dwelling_type, bedrooms } = {}) =>
241
+ [dwelling_type, bedrooms].some((v) => v != null && String(v).trim() !== "");
242
+
243
+ const wellFormedByType = (f, state) => f && f.state === state && f.detail === "dwelling_type_and_bedrooms"
244
+ && quarterKey(f.quarter) > 0 && Array.isArray(f.areas) && f.areas.length > 0 && Array.isArray(f.councils)
245
+ && f.state_total && f.state_total.breakdown && Array.isArray(f.limits) && f.licence && f.attribution
246
+ && f.changes_made && f.absent_means && f.labels;
247
+
248
+ /** One state's by-type file and where it came from ("env", "live" or "published"); { feed: null } if none. */
249
+ export async function loadRentsByType(state, { env = process.env, fetchImpl = globalThis.fetch, liveDir = LIVE_DIR } = {}) {
250
+ const file = BY_TYPE[state];
251
+ const read = (path) => loadJson(path).then((f) => (wellFormedByType(f, state) ? f : null)).catch(() => null);
252
+ if (env.DWELLDELTA_STATE_RENTS_DIR) return { feed: await read(join(env.DWELLDELTA_STATE_RENTS_DIR, file)), origin: "env" };
253
+ if (existsSync(join(liveDir, file))) return { feed: await read(join(liveDir, file)), origin: "live" };
254
+ if (env.DWELLDELTA_OFFLINE !== "1" && typeof fetchImpl === "function") {
255
+ try {
256
+ const res = await fetchImpl(PUBLISHED_BASE + file, { signal: AbortSignal.timeout(BY_TYPE_TIMEOUT_MS) });
257
+ const got = res.ok ? await res.json() : null;
258
+ if (wellFormedByType(got, state)) return { feed: got, origin: "published" };
259
+ } catch {
260
+ // Offline, blocked or slow: there is no bundled copy, and a by-type question will say what to do.
261
+ }
262
+ }
263
+ return { feed: null, origin: null };
264
+ }
265
+
266
+ /** Both states' by-type files: { NSW: file-with-origin | null, QLD: ... }. It never rejects. */
267
+ export async function loadAllRentsByType(opts) {
268
+ const states = Object.keys(BY_TYPE);
269
+ const loaded = await Promise.all(states.map((s) => loadRentsByType(s, opts).catch(() => ({ feed: null }))));
270
+ return Object.fromEntries(states.map((s, i) => [s, loaded[i].feed ? { ...loaded[i].feed, origin: loaded[i].origin } : null]));
271
+ }
272
+
273
+ const NSW_TYPES = ["House", "Townhouse", "Flat/Unit", "Other", "Total"];
274
+ const NSW_SIZES = ["Bedsitter", "1 Bedroom", "2 Bedrooms", "3 Bedrooms", "4 or more Bedrooms", "Not Specified", "Total"];
275
+ // Words people use for the publishers' labels. Each maps to ONE label, and the answer always prints the label itself.
276
+ const TYPE_WORDS = { unit: "Flat/Unit", units: "Flat/Unit", flat: "Flat/Unit", flats: "Flat/Unit", apartment: "Flat/Unit",
277
+ apartments: "Flat/Unit", houses: "House", "town house": "Townhouse", townhouses: "Townhouse",
278
+ all: "Total", any: "Total", "all dwellings": "Total" };
279
+ const QLD_KINDS = { unit: "Flat", units: "Flat", flats: "Flat", apartment: "Flat", apartments: "Flat", houses: "House",
280
+ "town house": "Townhouse", townhouses: "Townhouse" };
281
+ const known = (present, order) => [...order.filter((l) => present.has(l)), ...[...present].filter((l) => !order.includes(l))];
282
+
283
+ /** The one label a word names: the label itself, a known word for it, or the only label containing it. */
284
+ function label(wanted, labels, words, what, state) {
285
+ const w = norm(wanted).replace(/\s+/g, " ");
286
+ const found = labels.find((l) => norm(l) === w) ?? (labels.includes(words[w]) ? words[w] : null);
287
+ if (found) return found;
288
+ const part = labels.filter((l) => norm(l).includes(w));
289
+ if (part.length === 1) return part[0];
290
+ throw new ToolError(`No ${STATES[state].name} ${what} matches ${JSON.stringify(wanted)}.`,
291
+ `The publisher's ${what} labels are: ${labels.join(", ")}. Call again with one of them.`);
292
+ }
293
+
294
+ /**
295
+ * A number of bedrooms as someone writes it - "2", "2 bed", "2br", "4+", "studio" - or null if it is not one.
296
+ * orMore is the plus: "that many or more" is a different question from "exactly that many", and is answered only
297
+ * where the publisher has a label that means it. (It used to be dropped, so "3+" was answered as three.)
298
+ */
299
+ function bedroomsAsked(wanted) {
300
+ const w = norm(wanted).replace(/\s+/g, " ");
301
+ if (["studio", "bedsit", "bedsitter"].includes(w)) return { n: 0, orMore: false };
302
+ const m = /^(\d{1,2})\s*(\+)?\s*(?:bed(?:room)?s?|br)?$/.exec(w);
303
+ return m ? { n: Number(m[1]), orMore: Boolean(m[2]) } : null;
304
+ }
305
+
306
+ /** NSW: which of DCJ's dwelling types and sizes were asked for (null = every one), as DCJ labels them. */
307
+ function nswAsked(file, dwelling_type, bedrooms) {
308
+ const cells = file.state_total.breakdown;
309
+ const types = known(new Set(Object.keys(cells)), NSW_TYPES);
310
+ const sizes = known(new Set(Object.values(cells).flatMap((c) => Object.keys(c))), NSW_SIZES);
311
+ const type = wantsByType({ dwelling_type }) ? label(dwelling_type, types, TYPE_WORDS, "dwelling type", "NSW") : null;
312
+ let size = null;
313
+ const notes = [];
314
+ if (wantsByType({ bedrooms })) {
315
+ const b = bedroomsAsked(bedrooms);
316
+ // DCJ's one "or more" size is "4 or more Bedrooms". Below that, "N or more" has no figure of its own.
317
+ if (b && b.orMore && b.n < 4) {
318
+ throw new ToolError(`DCJ reports no figure for ${b.n} or more bedrooms.`,
319
+ `Its sizes are: ${sizes.join(", ")}. Call again with bedrooms "${b.n}" for exactly that many, or "4+" for DCJ's ` +
320
+ `"4 or more Bedrooms".`);
321
+ }
322
+ const n = b ? b.n : null;
323
+ const counted = n === null ? null
324
+ : n === 0 ? "Bedsitter" : n >= 4 ? "4 or more Bedrooms" : sizes.find((s) => s.startsWith(`${n} Bedroom`));
325
+ size = counted && sizes.includes(counted) ? counted
326
+ : label(bedrooms, sizes, { all: "Total", any: "Total", "all sizes": "Total" }, "bedrooms", "NSW");
327
+ // Five, six or "5+" lie inside "4 or more Bedrooms", the only figure DCJ has for them - but it is the figure for
328
+ // every home of four or more, which is not what was asked. Answered, and said. (It used to be answered and not said.)
329
+ if (b && b.n > 4 && size === "4 or more Bedrooms") {
330
+ notes.push(`You asked for ${b.n}${b.orMore ? " or more" : ""} bedrooms. DCJ's largest size is "4 or more Bedrooms": the figures ` +
331
+ "here are for every home of four bedrooms or more together, and DCJ reports nothing narrower. Say so when you give them.");
332
+ }
333
+ }
334
+ const wanted = [];
335
+ for (const t of type ? [type] : types) {
336
+ for (const s of size ? [size] : sizes) {
337
+ // Total and Total is the all-dwellings figure: shown only when both were asked for by name.
338
+ if (t === "Total" && s === "Total" && !(type && size)) continue;
339
+ wanted.push({ dwelling_type: t, bedrooms: s, words: `${t === "Total" ? "All dwellings" : t}, ${s === "Total" ? "all sizes" : s}`,
340
+ cell: (group) => group?.breakdown?.[t]?.[s] ?? null });
341
+ }
342
+ }
343
+ return { wanted, asked: { dwelling_type: type, bedrooms: size }, notes };
344
+ }
345
+
346
+ /** Queensland: which of the RTA's labels ("Flat 2", "House 3") were asked for. */
347
+ function qldAsked(file, dwelling_type, bedrooms) {
348
+ const labels = Object.keys(file.state_total.breakdown).filter((l) => l !== "All dwellings");
349
+ const parsed = labels.map((l) => ({ l, m: /^([A-Za-z ]+?) (\d)$/.exec(l) })).filter((x) => x.m)
350
+ .map((x) => ({ label: x.l, kind: x.m[1], n: Number(x.m[2]) }));
351
+ const kinds = [...new Set(parsed.map((p) => p.kind))];
352
+ let chosen = parsed, kind = null, n = null, full = null;
353
+ if (wantsByType({ dwelling_type })) {
354
+ const whole = labels.find((l) => norm(l) === norm(dwelling_type)); // a label given in full: "Flat 2"
355
+ if (whole) {
356
+ // With its own number, where it has one: "Flat 2" and bedrooms "2" agree. (It used to carry none, so any
357
+ // bedrooms at all emptied the answer and the refusal said the RTA publishes no label for 2 bedrooms.)
358
+ full = parsed.find((p) => p.label === whole) ?? { label: whole, kind: whole, n: null };
359
+ chosen = [full];
360
+ } else {
361
+ kind = label(dwelling_type, kinds, QLD_KINDS, "dwelling type", "QLD");
362
+ chosen = chosen.filter((p) => p.kind === kind);
363
+ }
364
+ }
365
+ if (wantsByType({ bedrooms })) {
366
+ const b = bedroomsAsked(bedrooms);
367
+ if (b === null) {
368
+ throw new ToolError(`${JSON.stringify(bedrooms)} is not a number of bedrooms.`,
369
+ `The RTA's labels are: ${labels.join(", ")}. Give bedrooms as a number, or dwelling_type as one of the labels.`);
370
+ }
371
+ if (b.orMore) {
372
+ throw new ToolError(`The RTA publishes no "${b.n} or more" figure.`,
373
+ `Each of these labels carries one number, which DwellDelta reads as that many bedrooms: ` +
374
+ `${parsed.map((p) => p.label).join(", ")}. Call again with bedrooms as a plain number.`);
375
+ }
376
+ n = b.n;
377
+ if (full && full.n === null) {
378
+ throw new ToolError(`The RTA's label ${JSON.stringify(full.label)} carries no number of bedrooms.`,
379
+ `Call again without bedrooms: dwelling_type ${JSON.stringify(full.label)} is one figure.`);
380
+ }
381
+ if (full && full.n !== n) {
382
+ throw new ToolError(`${JSON.stringify(full.label)} is the label DwellDelta reads as ${full.n} bedroom${full.n === 1 ? "" : "s"}, ` +
383
+ `and bedrooms was given as ${n}.`,
384
+ `Give dwelling_type ${JSON.stringify(full.label)} on its own, or a dwelling type and bedrooms that agree. The RTA's ` +
385
+ `labels are: ${labels.join(", ")}.`);
386
+ }
387
+ chosen = chosen.filter((p) => p.n === n);
388
+ }
389
+ if (!chosen.length) {
390
+ const what = [kind, n === null ? null : `${n} bedroom${n === 1 ? "" : "s"}`].filter(Boolean).join(", ");
391
+ throw new ToolError(`The RTA publishes no label for ${what}.`, `Its labels are: ${labels.join(", ")}.`);
392
+ }
393
+ return { wanted: chosen.map((p) => ({ label: p.label, words: p.label, cell: (group) => group?.breakdown?.[p.label] ?? null })),
394
+ asked: { dwelling_type: kind, bedrooms: n, labels: chosen.map((p) => p.label) } };
395
+ }
396
+
397
+ /** area_rents with dwelling_type or bedrooms: the publisher's own cells for the places matched, and no others. */
398
+ function byTypeResult({ state, info, feed, dwelling_type, bedrooms, whole, areas, councils, file }, now) {
399
+ if (!BY_TYPE[state]) {
400
+ throw new ToolError(`${info.name} rents are not published by dwelling type or bedrooms.`,
401
+ "WA's bond records carry neither. Call area_rents for WA without dwelling_type and bedrooms: every WA figure " +
402
+ "is all dwellings together.");
403
+ }
404
+ if (!file) {
405
+ throw new ToolError(`The ${info.name} rents by dwelling type file is not on this machine.`,
406
+ `It is read once at start from ${PUBLISHED_BASE}${BY_TYPE[state]}. Offline, point DWELLDELTA_STATE_RENTS_DIR at ` +
407
+ "a folder holding a copy. Without dwelling_type and bedrooms, area_rents still answers for all dwellings together.");
408
+ }
409
+ if (file.quarter !== feed.quarter) {
410
+ throw new ToolError(`The ${info.name} by-type file is for ${file.quarter} and the rents feed for ${feed.quarter}.`,
411
+ "They are published together and must be the same quarter. Call area_rents without dwelling_type and bedrooms " +
412
+ "for the all-dwellings figure, and restart the server to read both again.");
413
+ }
414
+ const { wanted, asked, notes = [] } = state === "NSW" ? nswAsked(file, dwelling_type, bedrooms) : qldAsked(file, dwelling_type, bedrooms);
415
+ const kind = feed.area_kind;
416
+ const places = whole ? [{ name: `${info.name} (whole state)`, place: info.name, place_kind: "state", group: file.state_total }]
417
+ : [...councils.map((r) => ({ name: `${r.council} (council)`, place: r.council, place_kind: "council",
418
+ group: file.councils.find((g) => g.council === r.council) })),
419
+ ...areas.map((r) => ({ name: `${r.area} (${kind})`, place: r.area, place_kind: kind,
420
+ group: file.areas.find((g) => g.area === r.area) }))];
421
+ const shown = places.slice(0, MAX_TYPE_PLACES);
422
+ const rule = RULES[state];
423
+ const lines = [], rows = [], figures = [];
424
+ for (const p of shown) {
425
+ const absent = [];
426
+ for (const w of wanted) {
427
+ const cell = w.cell(p.group);
428
+ const name = `${p.name}, ${w.words}`;
429
+ const fig = cell ? rentFigure(cell, name, rule)
430
+ : judgeFigure(null, { name, median: "median_weekly_rent_aud", count: "new_bonds", rule, why: file.absent_means });
431
+ figures.push(fig);
432
+ rows.push({ place: p.place, place_kind: p.place_kind,
433
+ ...(state === "NSW" ? { dwelling_type: w.dwelling_type, bedrooms: w.bedrooms } : { label: w.label }), figure: cell,
434
+ ...refusalMark(fig) });
435
+ if (cell) lines.push(line(cell, name, rule));
436
+ else absent.push(w.words);
437
+ }
438
+ if (absent.length) lines.push(`${p.name}: no published median for ${absent.join("; ")}.`);
439
+ }
440
+ const truncated = places.length > shown.length;
441
+ if (truncated) lines.push(`${places.length - shown.length} more places match: narrow the name.`);
442
+ const feedUrl = PUBLISHED_BASE + BY_TYPE[state];
443
+ const env = envelope({ sources: [feedSource(file, feedUrl, file.quarter)], dataAsOf: file.quarter,
444
+ origin: file.origin ?? null, cadence: CADENCE.rents_quarterly }, now);
445
+ const text = [
446
+ ...staleNote(env),
447
+ `${file.what}. Quarter: ${file.quarter}, against ${file.compared_with}.`,
448
+ "",
449
+ ...notes.flatMap((n) => [n, ""]),
450
+ ...lines,
451
+ "",
452
+ ...(rows.some((r) => !r.figure) ? [`Where there is no published median: ${file.absent_means}`,
453
+ "Do not fill a gap from a neighbouring area, a wider group, an earlier quarter or the all-dwellings figure " +
454
+ "without saying that you have.", ""] : []),
455
+ `Labels: ${file.labels}`,
456
+ "",
457
+ "Limits:",
458
+ ...file.limits.map((l) => "- " + l),
459
+ "",
460
+ `Source: ${file.attribution}`,
461
+ `What DwellDelta changed: ${file.changes_made}`,
462
+ citeLine({ source: file.source, period: `${file.quarter} (against ${file.compared_with})`, licence: file.licence,
463
+ n: nWords(figures, rule.unit), url: env.sources[0].source_url, notice: env.sources[0].source_notice_url,
464
+ feedUrl, stale: flagged(env) }),
465
+ FOOTER,
466
+ ].join("\n");
467
+ return { text, structured: { ...env, state, state_name: info.name, area_kind: kind, quarter: file.quarter,
468
+ compared_with: file.compared_with, detail: file.detail, asked, notes, rows, truncated,
469
+ absent_means: file.absent_means, labels: file.labels, limits: file.limits,
470
+ changes_made: file.changes_made, ...figureFields(figures), sample_rule: rule } };
178
471
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dwelldelta-mcp",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "Is an Australian rent fair? A rent check on the ABS rents index, rents by area for four states, NSW median sale prices, and sourced property and lending indicators, for AI agents.",
5
5
  "mcpName": "au.com.dwelldelta/dwelldelta",
6
6
  "license": "MIT",