/** Rental intelligence tools. This client never reads private property data. */ export type Household = "single" | "small_hmo" | "large_hmo"; export type Link = { title: string; url: string }; export type RuleStatus = "in_force" | "confirmed_future" | "proposed"; export type RuleSummary = { id: string; title: string; status: RuleStatus; summary: string; url: string }; export type Rule = RuleSummary & { category: string; requirement: string; applies_when: string; legal_basis: Link[]; guidance: Link[]; confidence: "high" | "medium" | "low"; effective_from: string | null; effective_to: string | null; [field: string]: unknown; }; export type RegisterWindow = { region: string; opens: string; deadline: string; earlyRegistrationFrom: string; feeGbp: number }; export type Scheme = { start_date: string | null; end_date: string | null; type: "selective" | "additional" | "mandatory_hmo"; status: "in_force" | "approved_not_started" | "consultation" | "expired" | "quashed" | "revoked"; source_urls: string[]; confidence: "high" | "medium" | "low"; [field: string]: unknown; }; export type CouncilLicensing = | { researched: false; council: { name: string; slug: string; region: string; gss: string }; message: string; register: RegisterWindow | null; registerSources: string[]; registerCheckedAt: string } | { researched: true; authority: string; slug: string; gss: string; researched_at: string; verified_at: string | null; schemes: Scheme[]; url: string; /** A paid REST pull carries applicationEvidence and openQuestionCount. The free connector answer is the full public record, with open_questions. */ applicationEvidence?: CouncilApplicationEvidence; openQuestionCount?: number; open_questions?: string[]; [field: string]: unknown }; export type AddressCheck = { postcode: string; ward: string | null; council: string | null; household: Household; licence: { needed: "yes" | "no" | "check"; summary: string; nationalRuleSource?: string; schemes: { type: Scheme["type"]; status: Scheme["status"]; start: string | null; end: string | null; ceasesOn?: string | null; endDateUncertainUntil?: string | null; confidence: Scheme["confidence"]; apply: string | null; sources: string[]; }[] }; register: RegisterWindow | null; registerSources: string[]; registerCheckedAt: string; planningSource: string; planningAvailability: Record<"floodZone" | "conservationAreas" | "article4", "available" | "unavailable">; /** A paid REST pull carries the three counts. The free connector answer is the full public record, with the lists instead. */ openQuestionCount?: number; openQuestions?: string[]; floodZone: { level: 2 | 3 } | null; conservationAreaCount?: number | null; article4DirectionCount?: number | null; conservationAreas?: string[] | null; article4Directions?: unknown[] | null; councilPage: string | null; researched: string | null; verified: string | null; limitations: string[]; }; /** What the landlord knows about one home. Every answer is optional; never guess one. Dates are YYYY-MM-DD. */ export type PlanAnswers = { household?: Household; letting?: "now" | "next"; tenancy_start?: string; has_gas?: "yes" | "no"; last_gas_check?: string; last_electrical_inspection?: string; next_electrical_inspection?: string; epc_rating?: "A" | "B" | "C" | "D" | "E" | "F" | "G"; epc_expiry?: string; holds_licence?: "yes" | "no"; licence_end?: string; deposit_taken?: "yes" | "no"; deposit_received?: string; deposit_protected_in_time?: "yes" | "no"; right_to_rent_checked?: "yes" | "no"; tenancy_document_given?: "yes" | "late" | "no"; alarms_tested_at_start?: "yes" | "no"; last_rent_increase?: string; rent_period?: "month" | "four_weeks" | "fortnight" | "week"; furnished?: "yes" | "no"; }; export type PlanItem = { id: string; title: string; /** "ok" means on track by the landlord's own answers, not checked against documents. */ status: "action" | "due_soon" | "unknown" | "upcoming" | "ok"; date: string | null; dateLabel: string | null; detail: string; basis: "address" | "answers" | "unanswered"; ongoing: boolean; otherDates: { date: string; label: string }[]; applyUrl: string | null; rules: { id: string; title: string; url: string }[]; }; export type RentalPlan = { postcode: string; ward: string | null; council: string; councilPage: string | null; region: string | null; household: Household; letting: "now" | "next" | null; asOf: string; licence: { needed: "check"; summary: string; sources: string[]; researched: string | null; verified: string | null }; items: PlanItem[]; /** Answers that would make the plan more exact: ask the landlord, then plan again with `argument` set. */ questions: { key: string; parameter: string; argument: keyof PlanAnswers; prompt: string; hint: string | null; kind: "date" | "choice"; options: string[] }[]; answers: Record; links: { plan: string; api: string; calendar: string }; notice: string; }; export type MarketSource = { dataset: string; publisher: string; url: string; files: string[]; released: string; obtained: string; measure: string; licence: string; licenceUrl: string; attribution: string }; export type SalesArea = { code: string; medianPriceGbp: number; sales: number }; export type AreaMarket = { postcode: string; council: string | null; councilCode: string; /** Unavailable means the snapshot has no figure for the area, never zero. Show source.attribution with any figure. */ rent: | { status: "available"; area: { code: string; name: string }; period: string; averageMonthlyRentGbp: number; annualChangePct: number | null; byBedrooms: Record<"one" | "two" | "three" | "fourPlus", number | null>; england: { averageMonthlyRentGbp: number; annualChangePct: number | null } | null; source: MarketSource } | { status: "unavailable"; reason: string; source: MarketSource }; sales: | { status: "available"; district: SalesArea; window: { from: string; to: string }; source: MarketSource } | { status: "unavailable"; reason: string; window: { from: string; to: string }; source: MarketSource }; limitations: string[]; }; /** Snapshot scope and source dates as returned by the general public MCP server. */ export type DataCoverage = { jurisdiction: "England"; propertyHistory: string; asOf: string; councils: { total: number; published: number; held: string[]; researchRange: { earliest: string | null; latest: string | null }; independentCheckRange: { earliest: string | null; latest: string | null }; researchDue: number; independentChecksDue: number; citationAudit: { date: string; urls: number; receipt: string }; researchTargetDays: number; independentCheckTargetDays: number; withOpenQuestions: number; directory: string; }; assessments: { national: string; localCouncils: string[]; catalogue: string }; rules: { published: number; lastReview: { date: string; rules: number; guidanceTemplates: number; sourceUrls: number; scope: string }; directory: string }; forms: { files: number; retrieved: string; checksumsVerified: string; source: string }; geography: { source: string; url: string; retrieved: string; councils: number; wards: number }; market: { rents: { period: string; published: string; retrieved: string; councils: number; missingCouncils: string[]; source: string }; sales: { from: string; to: string; published: string; retrieved: string; districts: number; minimumSales: number; source: string }; }; }; export type FieldSource = { publisher: string; dataset: string; url: string; licence: string | null; licenceUrl: string | null; attribution: string | null; released: string | null; obtained: string | null; note: string }; export type Comparison = { household: Household; postcodes: string[]; addresses: ({ postcode: string; status: "ok"; check: AddressCheck; market: AreaMarket } | { postcode: string; status: "not_found" | "outside_england" | "unavailable"; error: string })[]; /** One row per field. A value of "unknown" means the source cannot settle it; it never means no. */ comparison: { field: string; label: string; source: FieldSource; values: { postcode: string; value: unknown; unknown?: string; detail?: Record }[] }[]; limitations: string[]; }; export type ToolInfo = { name: string; title?: string; description?: string; inputSchema: Record; annotations?: Record }; export class LettanceError extends Error { constructor(message: string, readonly kind: "http" | "rpc" | "tool" | "protocol", readonly status?: number, readonly retryAfter?: string | null, readonly code?: string) { super(message); this.name = "LettanceError"; } } export type Fetcher = (input: RequestInfo | URL, init?: RequestInit) => Promise; export type McpReceipt = { id: string; credits: number; operation: string; issuedAt: string; replayed: boolean }; export type ClientOptions = { token?: string; endpoint?: string; fetch?: Fetcher; timeoutMs?: number }; function object(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } /** A small JSON-response client for this stateless endpoint; use a general MCP SDK for streaming servers. */ export class LettanceClient { private nextId = 0; private ready?: Promise; private protocol = "2025-11-25"; private readonly token?: string; private readonly endpoint: string; private readonly fetcher: Fetcher; private readonly timeout: number; constructor(options: ClientOptions = {}) { this.endpoint = options.endpoint ?? "https://lettance.com/mcp"; this.token = options.token; if (this.token && new URL(this.endpoint).protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(new URL(this.endpoint).hostname)) throw new TypeError("Credentials require an HTTPS MCP endpoint."); this.fetcher = options.fetch ?? globalThis.fetch; this.timeout = options.timeoutMs ?? 25_000; if (!Number.isFinite(this.timeout) || this.timeout <= 0) throw new TypeError("timeoutMs must be positive"); } private async send(method: string, params?: Record, notification = false): Promise { const id = ++this.nextId; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), this.timeout); try { const response = await this.fetcher(this.endpoint, { method: "POST", redirect: "error", headers: { ...(this.token && method === "tools/call" ? { Authorization: "Bearer " + this.token } : {}), "Content-Type": "application/json", Accept: "application/json, text/event-stream", ...(method === "initialize" ? {} : { "MCP-Protocol-Version": this.protocol }) }, body: JSON.stringify({ jsonrpc: "2.0", ...(notification ? {} : { id }), method, ...(params ? { params } : {}) }), signal: controller.signal, credentials: "omit", }); if (!response.ok) throw new LettanceError(`Lettance returned HTTP ${response.status}`, "http", response.status, response.headers.get("retry-after")); if (notification) { if (response.status !== 202) throw new LettanceError("Expected an empty 202 notification acknowledgement", "protocol"); return; } if (!response.headers.get("content-type")?.includes("application/json")) throw new LettanceError("Expected a JSON response from the Lettance endpoint", "protocol"); const message: unknown = await response.json(); if (!object(message) || message.jsonrpc !== "2.0" || message.id !== id) throw new LettanceError("Invalid or mismatched JSON-RPC response", "protocol"); if (object(message.error)) throw new LettanceError(typeof message.error.message === "string" ? message.error.message : "MCP request failed", "rpc"); if (!("result" in message)) throw new LettanceError("Missing JSON-RPC result", "protocol"); return message.result; } finally { clearTimeout(timer); } } private initialize(): Promise { if (!this.ready) { this.ready = (async () => { const result = await this.send("initialize", { protocolVersion: this.protocol, capabilities: {}, clientInfo: { name: "lettance-typescript", version: "0.3.2" } }); if (!object(result) || !["2025-11-25", "2025-06-18", "2025-03-26"].includes(String(result.protocolVersion))) throw new LettanceError("Unsupported negotiated protocol", "protocol"); this.protocol = result.protocolVersion as string; await this.send("notifications/initialized", undefined, true); })().catch((error) => { this.ready = undefined; throw error; }); } return this.ready; } async listTools(): Promise { await this.initialize(); const result = await this.send("tools/list"); if (!object(result) || !Array.isArray(result.tools)) throw new LettanceError("Invalid tools list", "protocol"); return result.tools as ToolInfo[]; } private async tool(name: string, args: Record, valid: (value: Record) => boolean): Promise { await this.initialize(); const result = await this.send("tools/call", { name, arguments: args }); if (!object(result)) throw new LettanceError("Invalid tool response", "protocol"); const texts = Array.isArray(result.content) ? result.content.filter((part): part is Record => object(part) && part.type === "text") : []; const text = texts.map((part) => String(part.text ?? "")).join("\n"); if (result.isError) { const error = object(result.structuredContent) ? result.structuredContent.error : undefined; throw new LettanceError(text || "Lookup failed", "tool", undefined, undefined, typeof error === "string" ? error : undefined); } let value = result.structuredContent; if (!object(value)) { try { value = JSON.parse(text); } catch { throw new LettanceError("Tool did not return structured data", "protocol"); } } if (!object(value) || !valid(value)) throw new LettanceError("Unexpected tool result shape", "protocol"); return value as T; } searchRules(query: string, requestId: string = crypto.randomUUID()): Promise<{ results: RuleSummary[] }> { return this.tool("search_rules", { requestId, query }, (v) => Array.isArray(v.results)); } getRule(id: string, requestId: string = crypto.randomUUID()): Promise { return this.tool("get_rule", { requestId, id }, (v) => typeof v.id === "string" && Array.isArray(v.legal_basis)); } councilLicensing(council: string, requestId: string = crypto.randomUUID()): Promise { return this.tool("council_licensing", { requestId, council }, (v) => v.researched === true ? Array.isArray(v.schemes) && typeof v.authority === "string" : v.researched === false && object(v.council)); } /** A dated plan of what one home needs over the next 12 months, from its postcode and the answers given. */ planRental(postcode: string, answers: PlanAnswers = {}, requestId: string = crypto.randomUUID()): Promise { return this.tool("plan_rental", { requestId, postcode, ...answers }, (v) => typeof v.postcode === "string" && Array.isArray(v.items) && Array.isArray(v.questions)); } /** 2 to 4 postcodes; each counts as one request against the rate limit. Needs the /mcp endpoint. */ compareAddresses(postcodes: string[], household: Household = "single", requestId: string = crypto.randomUUID()): Promise { return this.tool("compare_addresses", { requestId, postcodes, household }, (v) => Array.isArray(v.addresses) && Array.isArray(v.comparison)); } preflightProperty(facts: PropertyFacts): Promise { return this.tool("preflight_property", { facts }, value => typeof value.canAssess === "boolean" && typeof value.availableScope === "string"); } assessProperty(facts: PropertyFacts, requestId: string, acceptNationalOnly = false): Promise { return this.tool("assess_property", { facts, requestId, acceptNationalOnly }, value => typeof value.comparisonFingerprint === "string" && Array.isArray(value.findings) && object(value.receipt)); } councilReviews(query: CouncilReviewQuery = {}): Promise { return this.tool("council_reviews", { ...query }, v => v.schemaVersion === 1 && typeof v.edition === "string" && object(v.pagination) && (Array.isArray(v.councils) || (object(v.council) && Array.isArray(v.sources)))); } dataCoverage(): Promise { return this.tool("data_coverage", {}, (v) => v.jurisdiction === "England" && typeof v.asOf === "string" && object(v.councils) && Array.isArray(v.councils.held) && object(v.assessments) && object(v.rules) && object(v.forms) && object(v.geography) && object(v.market) && object(v.market.rents) && object(v.market.sales)); } propertyHistory(input: PropertyHistoryInput, requestId: string): Promise { return this.tool("property_history", { ...input, requestId }, value => value.version === "property-history-v1" && Array.isArray(value.properties) && Array.isArray(value.needsAttention) && object(value.receipt)); } registerReference(input: RegisterReferenceInput, requestId: string): Promise { return this.tool("register_reference", { ...input, requestId }, value => value.match === "council_reference" && Array.isArray(value.matches) && object(value.source) && object(value.receipt)); } outcomeBenchmark(cohort: OutcomeCohort, requestId: string): Promise { return this.tool("application_outcome_benchmark", { ...cohort, requestId }, value => typeof value.medianDays === "number" && typeof value.sampleSize === "number" && object(value.period) && object(value.receipt)); } areaMarket(postcode: string, requestId: string = crypto.randomUUID()): Promise { return this.tool("area_market", { requestId, postcode }, (v) => typeof v.postcode === "string" && object(v.rent) && object(v.sales)); } checkAddress(postcode: string, household: Household = "single", requestId: string = crypto.randomUUID()): Promise { return this.tool("check_address", { requestId, postcode, household }, (v) => typeof v.postcode === "string" && object(v.licence) && ["yes", "no", "check"].includes(String(v.licence.needed))); } } export type PropertyFacts = { postcode: string; household?: Household | "two_sharers"; address?: string; /** Only supply a ward confirmed for the exact property. */ ward?: string; exemption?: "none_known" | "possible"; building?: "ordinary_house" | "flat" | "unknown"; sharedFacilities?: boolean; evidence?: { schemeType: Scheme["type"]; address: string; startsOn: string; expiresOn: string }; }; export type PropertyCoverageCode = "reviewed" | "unresearched" | "source_review_pending" | "outside_england" | "postcode_unresolved"; export type PendingCouncilEvidence = { field: string; schemeName: string; schemeType: Scheme["type"]; claim: "designation" | "boundary" | "fee"; sourceUrl: string; changedOn: string; lastConfirmedOn: string | null; changeClass: string | null; }; export type PropertyAttentionReason = { code: "designation_uncertain" | "unresolved" | "baseline_unavailable" | "council_evidence_changed" | "property_evidence_changed" | "council_source_pending"; sourceUrls: string[]; detail: string; }; export type PropertyPreflight = { pendingEvidence?: PendingCouncilEvidence[]; asOf: string; coverageCode: PropertyCoverageCode; council: string | null; availableScope: "local_and_national" | "national_only" | "unavailable"; requiredFacts: string[]; factsToConfirm: string[]; canAssess: boolean; requiresNationalOnlyConsent: boolean; assessmentCredits: number; }; export type LicensingAssessment = { pendingEvidence?: PendingCouncilEvidence[]; version: string; asOf: string; comparisonFingerprint: string; status: "required" | "possible" | "no_scheme_identified" | "unknown"; summary: string; coverage: { code: PropertyCoverageCode; council: string | null; reviewedAt: string | null; locationBasis: "postcode_district" | "outside_england" | "unresolved"; locationNote: string }; findings: { id: string; schemeType: Scheme["type"]; scope: "letting" | "building"; state: "applies" | "verify" | "upcoming" | "consultation"; effectiveFrom: string | null; effectiveTo: string | null; reason: string; dependsOn: string[]; boundaryToConfirm?: "ward" | "address"; nextCheck: string; sourceUrls: string[]; reviewedAt: string | null }[]; evidence: { status: "not_provided" | "address_unconfirmed" | "address_mismatch" | "scope_unconfirmed" | "scope_mismatch" | "not_yet_effective" | "expired" | "consistent"; startsOn: string | null; expiresOn: string | null; schemeType: Scheme["type"] | null; nextCheck: string }; nextAction: string; sources: string[]; attributions: string[]; }; /** Occupancy is the caller's observation. Omit unknown facts. */ export type HistoryLetting = Pick & { household: NonNullable }; export type HistoryFeeInput = { scheme: Scheme["type"]; application: "new" | "renewal"; applicationDate?: string; channel?: "online" | "paper"; leedsAccreditedOwner?: boolean; leedsTransferredSchedule?: boolean; licenceExpiryDate?: string; occupants?: number; standardTariffConfirmed?: boolean; brentAccreditedHolder?: boolean; islingtonAccreditedHolder?: boolean; islingtonEpcDiscount?: boolean; islingtonRenewalDiscount?: boolean; yorkQualifiedHolder?: boolean; bedrooms?: number; termYears?: 1 | 2.5 | 5; }; export type HistoryProperty = { uprn: string; fee?: HistoryFeeInput }; /** Supply 1–25 distinct UPRNs for evidence (1 credit) or one with letting facts (10 credits). Dates are UTC YYYY-MM-DD. */ export type PropertyHistoryInput = { properties: readonly (HistoryProperty & { letting?: never })[] | readonly [HistoryProperty & { letting: HistoryLetting }]; since?: string; asOf?: string; mode?: "as_observed" | "reconstructed"; knownOn?: string; }; export type HistoryDesignation = { type: "additional" | "selective"; name: string; startDate: string | null; endDate: string | null; method: string; sourceUrl: string; areaStatus: "inside" | "outside" | "needs_review"; periodStatus: "active" | "date_uncertain"; }; export type HistoryRecordSource = { id: string; kind: "issued_licence" | "planning_decision"; councilCode: string | null; publisher: string; areaCode: string; geography: "region" | "council"; lookupModes: ("exact_uprn" | "council_reference")[]; sourceUrl: string; rightsUrl: string; licence: string; attribution: string; scope: string; }; export type HistoryScheme = { id: string; type: Scheme["type"]; status: Scheme["status"]; startsOn: string | null; endsOn: string | null; recordedFee: { currency: "GBP"; standardPence: number | null; earlyBirdPence: number | null; interpretation: string } | null; uncertainThrough: string | null; area: string; feeScheduleVersion: string; designationVersion: string; applicationUrl: string | null; conditionsUrl: string | null; sources: string[]; }; export type HistoryConsultation = { status: string; closes: string | null; source: string | null }; export type HistoryFee = { status: "calculated" | "facts_required" | "no_reviewed_calculator" | "history_unavailable" | "council_review" | "outside_tariff_scope"; applicability: "outside_recorded_area" | "unconfirmed"; note: string; source?: string; sources?: string[]; currency?: "GBP"; reviewedOn?: string; effectiveFrom?: string; effectiveThrough?: string | null; scope?: string; required?: string[]; reason?: string; firstStagePence?: number; secondStagePence?: number; totalPence?: number; minimumTotalPence?: number; maximumTotalPence?: number | null; }; export type RegisterReferenceInput = { sourceId: string; reference: string; asOf?: string }; export type RegisterReferenceResult = { status: "matched"; match: "council_reference"; matches: PublishedRecord[]; source: HistoryRecordSource; observedOn: string; checkedOn: string | null; sourceDate: string | null; }; export type ApplicationCitation = { sourceUrl: string; publisher: string; sourceTitle: string; observedOn: string; lastCheckedOn: string }; export type CouncilApplicationEvidence = { version: "council-application-evidence-v1"; status: "available" | "no_published_evidence"; asOf: string; councilGss: string; schemeType: string | null; councilReportedMetrics: (ApplicationCitation & { id: string; schemeTypes: string[]; measure: string; value: number; unit: string; periodLabel: string; scopeNote: string })[]; publishedProcedures: (ApplicationCitation & { id: string; schemeTypes: string[]; stage: string; summary: string; requirements: { item: string; condition: string }[] })[]; firstParty: { benchmarkEndpoint: string; contributionEndpoint: string; minimumCases: number; minimumIndependentOrganisations: number; maximumOrganisationShare: number }; }; export type CouncilEvidenceDirectory = { source: string; councils: { name: string; slug: string; gss: string; localAssessment: boolean; firstCouncilObservation: string | null; latestCouncilObservation: string | null; researchedOn: string | null; independentlyCheckedOn: string | null; feeSchedule: string | null; recordSources: {id: string; kind: string; geography: string; areaCode: string; sourceRows: number; checkedOn: string | null; lookupModes: string[]}[]; councilReportedMetrics: number; publishedProcedures: number; }[] }; export type PublishedRecord = { uprn: string | null; planningAuthority?: string; permissionStatusAtSource?: string; outcomeDetail?: string; publishedEntries?: number; mayoralReferral?: { stageTwoDate: string; buildToRentUnits: number | null; londonLivingRentUnits: number | null; discountMarketRentUnits: number | null }; conditionApplication?: {type: "approval_of_details" | "variation_or_removal"; outcome: "granted" | "refused"; parentReference?: string; conditions?: { number: string; subject: string }[]}; reference: string; decision: string; decisionDate: string | null; startsOn: string | null; endsOn: string | null; applicationType: string | null; mentionsHmo: boolean | null; url: string }; export type HistoryPropertyRecord = PublishedRecord & { kind: HistoryRecordSource["kind"]; sourceId: string; councilCode: string }; export type PropertyHistoryPosition = { /** Receipts issued before these fields were introduced retain their original shape. */ attentionReasons?: PropertyAttentionReason[]; pendingEvidence?: PendingCouncilEvidence[]; uprn: string; status: "baseline" | "changed" | "unchanged" | "baseline_unavailable" | "unresolved"; attention: boolean; recordChanges: { day: string; before: HistoryPropertyRecord[]; after: HistoryPropertyRecord[] }[]; fingerprint: string; changes: { field: string; before: unknown; after: unknown }[]; boundary: { status: "matched" | "unresolved" | "history_unavailable"; uprn: string; councilGss: string | null; councilSlug: string | null; wardCode: string | null; wardName: string | null; sourceVersion: string | null; observedOn: string | null; reviewedOn: string | null; sourceUrls: string[]; attribution: string | null; designations: HistoryDesignation[]; localCoverage: "reviewed" | "unreviewed" | "unknown"; sourcePublishedOn: string | null; sourceEdition: string | null; followingEdition: { publishedOn: string; sourceVersion: string; url: string } | null; geographyContinuity: "single_edition" | "consistent_adjacent_editions" | "different_adjacent_editions"; evidenceBasis: "as_observed" | "retrospective_official_edition"; historicalScope: "recorded_catalogue" | "documented_designations_only"; currentIdentity: { councilGss: string; councilSlug: string; observedOn: string } | null }; applicationEvidence: CouncilApplicationEvidence | null; council: { basis: "later_evidence_of_dated_designation" | "dated_property_match" | "current_council_context_only"; code: string; name: string; observedOn: string; researchRevision: string; verifiedOn: string | null; schemes: HistoryScheme[]; consultations: HistoryConsultation[] } | null; rules: { methodology: string; coverage: PropertyCoverageCode; status: LicensingAssessment["status"]; findings: LicensingAssessment["findings"]; nextAction: string; sources: string[]; attributions: string[]; reviewedOn: string | null } | null; fee: HistoryFee | null; records: { status: "matched" | "see_source_coverage" | "coverage_unknown"; matches: HistoryPropertyRecord[]; sources: (HistoryRecordSource & { status: "matched" | "no_published_match" | "history_unavailable"; observedOn: string | null; checkedOn: string | null; sourceDate: string | null })[] }; }; export type PropertyHistoryResult = { version: "property-history-v1"; asOf: string; since: string | null; mode: "as_observed" | "reconstructed"; knownOn: string; properties: PropertyHistoryPosition[]; councilChanges: Record; needsAttention: string[]; comparison: string; }; export type PropertyHistoryCoverage = { version: "property-history-v1"; geography: { firstObservedOn: string; latestObservedOn: string; observationCount: number; sourceVersion: string; sourceEdition: string; englishUprns: number; englishCouncils: number; locallyReviewedCouncils: number; geographicCatalogueCouncils: number; geographyOnlyCouncilSlugs: string[]; reconstructionEditions: { publishedOn: string; observedOn: string; title: string; englishUprns: number }[]; attributionUrl: string; boundaryToleranceMetres: number }; councilDirectory: string; applicationEvidence: { asOf: string; sourceCount: number; councils: { councilGss: string; council: string; reportedMetrics: number; publishedProcedures: number }[]; sources: ApplicationCitation[]; firstPartyMethodology: string }; registerSourceDirections: { id: string; kind: string; councilCode: string | null; publisher: string; sourceUrl: string; officialSearchUrl: string; rightsEvidenceUrl: string; checkedOn: string; reason: string; status: "source_only" }[]; councilHistory: { firstObservation: string; latestCatalogueChange: string; councilsWithHistory: number; retainedObservations: number; source: string }; feeCalculators: { reviewedOn: string; sources: Record }; publishedRecords: (HistoryRecordSource & { historyFrom: string | null; checkedOn: string | null; sourceDate: string | null; editions: number; rows: number })[]; limits: { maxUprns: number; evidenceBatchCredits: number; singleLettingAssessmentCredits: number }; documentation: string; example: string; }; export type OutcomeCohort = { councilGss: string; schemeType: "selective" | "mandatory_hmo" | "additional_hmo" }; export type ApplicationOutcome = OutcomeCohort & { contributionId: string; filedOn: string; decidedOn: string; feePence: number; reuseAgreement: "lettance-aggregate-outcomes-v1"; }; export type OutcomeBenchmark = OutcomeCohort & { period: { from: string; through: string; reportingCutoff: string }; sampleSize: number; organisations: number; medianDays: number; medianFeePence: number; publishedAt: string; currency: "GBP"; source: string; methodology: string; interpretation: string; }; export type PullReceipt = { id: string; credits: number; replayed: boolean }; export type CouncilDirectory = { total: number; researched: number; councils: { name: string; slug: string; gss: string; region: string; researched: boolean; researchedAt: string | null; verifiedAt: string | null; schemeCount: number; openQuestionCount: number; url: string | null }[] }; export type DataResource = "check" | "plan" | "area-market" | "compare" | "councils" | "rules" | `councils/${string}` | `rules/${string}`; export type DataResult = R extends "check" ? AddressCheck : R extends "plan" ? RentalPlan : R extends "area-market" ? AreaMarket : R extends "compare" ? Comparison : R extends "councils" ? CouncilDirectory : R extends `councils/${string}` ? CouncilLicensing : R extends "rules" ? { query: string | null; total: number; rules: RuleSummary[] } : Rule; export type CouncilExampleRow = { slug: string; name: string; region: string; published: boolean; isExample: boolean }; export type CouncilReviewQuery = { council?: string; limit?: number; offset?: number; edition?: string }; export type CouncilReviewSignal = "baseline" | "unchanged" | "changed" | "unavailable" | "deferred"; type ReviewDates = { researchOn: string | null; independentReviewOn: string | null; latestSourceCheckOn: string | null }; type CouncilReviewSummary = ReviewDates & { slug: string; name: string; gss: string; publication: "published" | "held" | "unresearched"; priority: number }; type ReviewSource = { url: string; signal: CouncilReviewSignal; checkedOn: string | null; comparedOn: string | null; firstSeenOn: string | null; lastChangedAt: string | null; latestAttemptUnavailable: boolean; httpStatus: number | null; sourceFingerprint: { algorithm: string; sha256: string } | null; publisherTokens?: { added: { amountsGBP: string[]; dates: string[] }; removed: { amountsGBP: string[]; dates: string[] } }; }; type ReviewCoverage = { totalCouncils: number; publishedCouncils: number; heldCouncils: number; unresearchedCouncils: number; bySignal: Record; uniqueSources: number; independentReviewDueCouncils: number; researchDueCouncils: number; unavailablePublishers: {host: string; failedSources: number; affectedCouncils: number; httpStatuses: Record}[]; [field: string]: unknown }; type ReviewPage = { schemaVersion: 1; edition: string; asOf: string; generatedAt: string; pagination: { offset: number; limit: number; total: number; nextOffset: number | null } }; export type CouncilReviewPage = ReviewPage & { nationalCoverage: ReviewCoverage; councils: (CouncilReviewSummary & { reasons: {code: string; field: string; dueOn: string | null}[]; fields: {field: string; sources: {id: string; changePending: boolean; adjudicatedOn: string | null}[]}[]; [field: string]: unknown })[]; sourceWork: (ReviewSource & { id: string; sharedWith: string[]; [field: string]: unknown })[]; }; export type McpCouncilReviews = ReviewPage & { source: string; credits: 0 } & ( { nationalCoverage: ReviewCoverage; councils: (CouncilReviewSummary & { reasons: string[] })[] } | { council: CouncilReviewSummary & { reasons: string[] }; sources: (ReviewSource & {fields: {field: string; changePending: boolean; adjudicatedOn: string | null}[]})[]; uncoveredFields: string[]; planningLeadCount: number; interpretation: string } ); export type WalletOffer = { available: false } | { available: true; x402Version: 2; method: "POST"; redeliveryHours: number; offer: { url: string; path: string; amount: string; priceUsdc: string; network: string; asset: string; payTo: string }; documentation: string }; export type WalletChallenge = { x402Version: 2; resource: {url: string; description: string}; accepts: { scheme: "exact"; network: string; amount: string; asset: string; payTo: string; maxTimeoutSeconds: number; extra: { name: string; version: string }; }[]; extensions: Record }; export type DataMeta = { sources: string[]; catalogueDate: string; notice: string; links: Record; coverage: string }; export class LettancePullError extends Error { constructor(readonly status: number, readonly code: string, message: string, readonly retryAfter: string | null, readonly preflight?: PropertyPreflight) { super(message); this.name = "LettancePullError"; } } /** Server-side REST client. Persist one request key per intended paid read and reuse it for retries. */ export class LettanceRestClient { private readonly origin: string; private readonly fetcher: Fetcher; constructor(private readonly options: { key?: string; origin?: string; timeoutMs?: number; fetch?: Fetcher } = {}) { const origin = new URL(options.origin ?? "https://lettance.com"); if (options.key && origin.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(origin.hostname)) throw new TypeError("Credentials require an HTTPS REST origin."); this.origin = origin.origin; this.fetcher = options.fetch ?? globalThis.fetch; } private async request(path: string, options: { body?: object; authenticated?: boolean; method?: "DELETE"; requestKey?: string; acceptNationalOnly?: boolean; verifiedContributor?: boolean; expectChallenge?: boolean; paymentSignature?: string; transaction?: string } = {}) { const headers = new Headers({ Accept: "application/json" }); if (options.authenticated || options.requestKey !== undefined) { if (!this.options.key) throw new TypeError("Supply a project key for this request."); headers.set("Authorization", "Bearer " + this.options.key); } if (options.requestKey !== undefined) { if (!/^[!-~]{1,128}$/.test(options.requestKey)) throw new TypeError("Supply an Idempotency-Key of 1 to 128 visible ASCII characters."); headers.set("Idempotency-Key", options.requestKey); } if (options.verifiedContributor) headers.set("X-Lettance-Require-Verified-Contributor", "true"); if (options.paymentSignature !== undefined) { if (!this.origin.startsWith("https://") || !options.paymentSignature) throw new TypeError("A wallet payment requires HTTPS and a signed payment header."); headers.set("PAYMENT-SIGNATURE", options.paymentSignature); if (options.transaction) headers.set("X-PAYMENT-TRANSACTION", options.transaction); } if (options.body) headers.set("Content-Type", "application/json"); if (options.acceptNationalOnly) headers.set("X-Lettance-Accept-National-Only", "true"); const response = await this.fetcher(this.origin + path, { method: options.method ?? (options.body ? "POST" : "GET"), headers, credentials: "omit", redirect: "error", body: options.body ? JSON.stringify(options.body) : undefined, signal: AbortSignal.timeout(this.options.timeoutMs ?? 25_000), }); if (!response.ok && !(options.expectChallenge && response.status === 402 && response.headers.has("PAYMENT-REQUIRED"))) { const body = await response.json().catch(() => null); const code = typeof body?.error === "string" ? body.error : body?.error?.code ?? "http_error"; throw new LettancePullError(response.status, code, body?.message ?? body?.error?.message ?? code, response.headers.get("Retry-After"), body?.preflight); } const id = response.headers.get("X-Lettance-Receipt-Id"); const receipt: PullReceipt | null = id ? { id, credits: Number(response.headers.get("X-Lettance-Credits")), replayed: response.headers.get("X-Lettance-Replayed") === "true" } : null; return { response, receipt, json: () => response.json() as Promise }; } async coverage() { const result = await this.request<{ data: DataCoverage }>("/api/v1/coverage"); return (await result.json()).data; } async councilReviews(query: CouncilReviewQuery = {}) { const params = new URLSearchParams(); for (const [name, value] of Object.entries(query)) if (value !== undefined) params.set(name, String(value)); return (await this.request("/api/intelligence/v1/council-reviews?" + params)).json(); } async catalogue() { return (await this.request<{contract: string; assessmentCouncils: string[]; preflight: string; councilReviews: string; registerExample: string; propertyHistory: string; sandboxFixtures: {id: string; description: string; input: PropertyFacts; sourceUrls: string[]}[]; [field: string]: unknown}>( "/api/intelligence/v1/catalogue")).json(); } async sourceManifest() { return (await this.request<{revision: string; reviewedOn: string; publisher: string; [dataset: string]: unknown}>( "/api/intelligence/v1/source-manifest")).json(); } async creditBalance() { return (await this.request<{ environment: "sandbox" | "production"; balance: number | null; metered: boolean; currency: "GBP"; unitPence: number; assessmentCredits: number }>("/api/intelligence/v1/credits", { authenticated: true })).json(); } async walletAssessmentOffer() { return (await this.request("/api/intelligence/v1/x402/assessment")).json(); } /** Unsigned requests only. Use the platform fetch for a quote; never inject an auto-paying fetch here. */ async walletAssessmentQuote(facts: PropertyFacts, options: { acceptNationalOnly?: boolean } = {}) { const result = await this.request("/api/intelligence/v1/x402/assessment", { body: facts, ...options, expectChallenge: true }); if (result.response.status !== 402) throw new Error("Expected an unpaid x402 challenge."); const challenge = await result.json(); if (challenge.x402Version !== 2 || !challenge.accepts?.length) throw new Error("Incomplete x402 challenge."); return { challenge, paymentRequired: result.response.headers.get("PAYMENT-REQUIRED")! }; } /** Pass an existing wallet-signed x402 v2 header. Reuse identical facts and signature for recovery. */ async redeemWalletAssessment(facts: PropertyFacts, paymentSignature: string, options: { acceptNationalOnly?: boolean; transaction?: string } = {}) { const result = await this.request("/api/intelligence/v1/x402/assessment", { body: facts, paymentSignature, ...options }); const settlement = result.response.headers.get("PAYMENT-RESPONSE"); if (!settlement) throw new Error("Missing x402 settlement receipt. Recover with the identical signed request."); return { data: await result.json(), paymentResponse: settlement }; } async councilExampleDirectory(slug?: string) { const search = slug === undefined ? "" : "?" + new URLSearchParams({ slug }).toString(); return (await this.request<{ data: { councils: CouncilExampleRow[]; preview?: { scheme: string; status: string; verifiedAt: string | null; source: string } }; meta: DataMeta }>("/api/examples/councils" + search)).json(); } async councilExample(slug: string) { if (!/^[a-z0-9-]+$/.test(slug)) throw new TypeError("Supply a council slug marked isExample in the directory."); return (await this.request<{ data: Extract & { sourceManifest: string }; meta: DataMeta }>("/api/examples/councils/" + slug)).json(); } async preflight(facts: PropertyFacts) { return (await this.request("/api/intelligence/v1/preflight", { body: facts })).json(); } async assess(facts: PropertyFacts, requestKey: string, options: { acceptNationalOnly?: boolean } = {}) { const result = await this.request("/api/intelligence/v1/assessments", { body: facts, requestKey, ...options }); return { data: await result.json(), receipt: result.receipt }; } async propertyHistoryCoverage() { return (await this.request("/api/intelligence/v1/property-history/coverage")).json(); } async councilEvidenceDirectory(councilGss?: string) { const query = councilGss ? "?" + new URLSearchParams({ councilGss }) : ""; return (await this.request("/api/intelligence/v1/property-history/councils" + query)).json(); } async registerReferenceExample() { return (await this.request("/api/intelligence/v1/register-reference/example")).json(); } async registerReference(input: RegisterReferenceInput, requestKey: string) { const query = new URLSearchParams({sourceId: input.sourceId, reference: input.reference}); if (input.asOf) query.set("asOf", input.asOf); const result = await this.request("/api/intelligence/v1/register-reference?" + query, {requestKey}); return {data: await result.json(), receipt: result.receipt}; } async propertyHistoryExample(scenario?: "reconstructed") { return (await this.request("/api/intelligence/v1/property-history/example" + (scenario ? "?scenario=reconstructed" : ""))).json(); } async propertyHistory(input: PropertyHistoryInput, requestKey: string) { const result = await this.request("/api/intelligence/v1/property-history", { body: input, requestKey }); return { data: await result.json(), receipt: result.receipt }; } async outcomeBenchmark(cohort: OutcomeCohort, requestKey: string) { const query = new URLSearchParams({ councilGss: cohort.councilGss, schemeType: cohort.schemeType }); const result = await this.request("/api/intelligence/v1/outcome-benchmarks?" + query, { requestKey }); return { data: await result.json(), receipt: result.receipt }; } async contributorStatus() { return (await this.request<{ projectId: string; verified: boolean; reuseAgreement: ApplicationOutcome["reuseAgreement"]; credits: 0 }>( "/api/intelligence/v1/outcomes", { authenticated: true })).json(); } async contributeOutcome(outcome: ApplicationOutcome, options: { requireVerifiedContributor?: boolean } = {}) { return (await this.request<{ contributionId: string; state: "accepted"; replayed: boolean; credits: 0 }>( "/api/intelligence/v1/outcomes", { body: outcome, authenticated: true, verifiedContributor: options.requireVerifiedContributor })).json(); } async withdrawOutcome(contributionId: string) { if (!/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/i.test(contributionId)) throw new TypeError("Supply the original contribution UUIDv4."); return (await this.request<{ contributionId: string; state: "withdrawn"; credits: 0 }>( "/api/intelligence/v1/outcomes/" + contributionId, { method: "DELETE", authenticated: true })).json(); } async calendar(query: URLSearchParams | Record, requestKey: string) { const { response, receipt } = await this.request("/api/v1/plan/calendar?" + new URLSearchParams(query), { requestKey }); return { data: await response.text(), receipt }; } async readData(resource: R, query: URLSearchParams | Record, requestKey: string) { if (!/^(?:check|plan|area-market|compare|(?:councils|rules)(?:\/[a-z0-9-]+)?)$/.test(resource)) throw new TypeError("Unknown data resource. Use a documented slug or rule ID."); const search = new URLSearchParams(query).toString(); const { json, receipt } = await this.request<{ data: DataResult & { sourceManifest: string }; meta: DataMeta }>("/api/v1/" + resource + (search ? "?" + search : ""), { requestKey }); return { ...await json(), receipt }; } }