@cyanheads/geonames-mcp-server 0.0.0-stage → 0.1.2

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.
Files changed (91) hide show
  1. package/AGENTS.md +439 -0
  2. package/CLAUDE.md +439 -0
  3. package/Dockerfile +177 -0
  4. package/LICENSE +201 -0
  5. package/README.md +344 -2
  6. package/changelog/0.1.x/0.1.0.md +9 -0
  7. package/changelog/0.1.x/0.1.1.md +22 -0
  8. package/changelog/0.1.x/0.1.2.md +26 -0
  9. package/changelog/template.md +151 -0
  10. package/dist/config/server-config.d.ts +13 -0
  11. package/dist/config/server-config.d.ts.map +1 -0
  12. package/dist/config/server-config.js +21 -0
  13. package/dist/config/server-config.js.map +1 -0
  14. package/dist/index.d.ts +8 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +30 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/mcp-server/tools/definitions/find-postal-codes.tool.d.ts +96 -0
  19. package/dist/mcp-server/tools/definitions/find-postal-codes.tool.d.ts.map +1 -0
  20. package/dist/mcp-server/tools/definitions/find-postal-codes.tool.js +274 -0
  21. package/dist/mcp-server/tools/definitions/find-postal-codes.tool.js.map +1 -0
  22. package/dist/mcp-server/tools/definitions/get-children.tool.d.ts +90 -0
  23. package/dist/mcp-server/tools/definitions/get-children.tool.d.ts.map +1 -0
  24. package/dist/mcp-server/tools/definitions/get-children.tool.js +287 -0
  25. package/dist/mcp-server/tools/definitions/get-children.tool.js.map +1 -0
  26. package/dist/mcp-server/tools/definitions/get-countries.tool.d.ts +90 -0
  27. package/dist/mcp-server/tools/definitions/get-countries.tool.d.ts.map +1 -0
  28. package/dist/mcp-server/tools/definitions/get-countries.tool.js +217 -0
  29. package/dist/mcp-server/tools/definitions/get-countries.tool.js.map +1 -0
  30. package/dist/mcp-server/tools/definitions/get-hierarchy.tool.d.ts +64 -0
  31. package/dist/mcp-server/tools/definitions/get-hierarchy.tool.d.ts.map +1 -0
  32. package/dist/mcp-server/tools/definitions/get-hierarchy.tool.js +168 -0
  33. package/dist/mcp-server/tools/definitions/get-hierarchy.tool.js.map +1 -0
  34. package/dist/mcp-server/tools/definitions/get-place.tool.d.ts +108 -0
  35. package/dist/mcp-server/tools/definitions/get-place.tool.d.ts.map +1 -0
  36. package/dist/mcp-server/tools/definitions/get-place.tool.js +300 -0
  37. package/dist/mcp-server/tools/definitions/get-place.tool.js.map +1 -0
  38. package/dist/mcp-server/tools/definitions/index.d.ts +760 -0
  39. package/dist/mcp-server/tools/definitions/index.d.ts.map +1 -0
  40. package/dist/mcp-server/tools/definitions/index.js +23 -0
  41. package/dist/mcp-server/tools/definitions/index.js.map +1 -0
  42. package/dist/mcp-server/tools/definitions/list-reference.tool.d.ts +103 -0
  43. package/dist/mcp-server/tools/definitions/list-reference.tool.d.ts.map +1 -0
  44. package/dist/mcp-server/tools/definitions/list-reference.tool.js +233 -0
  45. package/dist/mcp-server/tools/definitions/list-reference.tool.js.map +1 -0
  46. package/dist/mcp-server/tools/definitions/reverse-geocode.tool.d.ts +142 -0
  47. package/dist/mcp-server/tools/definitions/reverse-geocode.tool.d.ts.map +1 -0
  48. package/dist/mcp-server/tools/definitions/reverse-geocode.tool.js +421 -0
  49. package/dist/mcp-server/tools/definitions/reverse-geocode.tool.js.map +1 -0
  50. package/dist/mcp-server/tools/definitions/search-places.tool.d.ts +145 -0
  51. package/dist/mcp-server/tools/definitions/search-places.tool.d.ts.map +1 -0
  52. package/dist/mcp-server/tools/definitions/search-places.tool.js +385 -0
  53. package/dist/mcp-server/tools/definitions/search-places.tool.js.map +1 -0
  54. package/dist/mcp-server/tools/shared-inputs.d.ts +140 -0
  55. package/dist/mcp-server/tools/shared-inputs.d.ts.map +1 -0
  56. package/dist/mcp-server/tools/shared-inputs.js +240 -0
  57. package/dist/mcp-server/tools/shared-inputs.js.map +1 -0
  58. package/dist/services/geonames/country-codes.d.ts +26 -0
  59. package/dist/services/geonames/country-codes.d.ts.map +1 -0
  60. package/dist/services/geonames/country-codes.js +284 -0
  61. package/dist/services/geonames/country-codes.js.map +1 -0
  62. package/dist/services/geonames/feature-codes.d.ts +27 -0
  63. package/dist/services/geonames/feature-codes.d.ts.map +1 -0
  64. package/dist/services/geonames/feature-codes.js +723 -0
  65. package/dist/services/geonames/feature-codes.js.map +1 -0
  66. package/dist/services/geonames/geonames-service.d.ts +103 -0
  67. package/dist/services/geonames/geonames-service.d.ts.map +1 -0
  68. package/dist/services/geonames/geonames-service.js +561 -0
  69. package/dist/services/geonames/geonames-service.js.map +1 -0
  70. package/dist/services/geonames/response-cache.d.ts +24 -0
  71. package/dist/services/geonames/response-cache.d.ts.map +1 -0
  72. package/dist/services/geonames/response-cache.js +44 -0
  73. package/dist/services/geonames/response-cache.js.map +1 -0
  74. package/dist/services/geonames/response-parsers.d.ts +38 -0
  75. package/dist/services/geonames/response-parsers.d.ts.map +1 -0
  76. package/dist/services/geonames/response-parsers.js +369 -0
  77. package/dist/services/geonames/response-parsers.js.map +1 -0
  78. package/dist/services/geonames/types.d.ts +226 -0
  79. package/dist/services/geonames/types.d.ts.map +1 -0
  80. package/dist/services/geonames/types.js +10 -0
  81. package/dist/services/geonames/types.js.map +1 -0
  82. package/dist/services/geonames/upstream-errors.d.ts +54 -0
  83. package/dist/services/geonames/upstream-errors.d.ts.map +1 -0
  84. package/dist/services/geonames/upstream-errors.js +187 -0
  85. package/dist/services/geonames/upstream-errors.js.map +1 -0
  86. package/dist/utils/inline-text.d.ts +25 -0
  87. package/dist/utils/inline-text.d.ts.map +1 -0
  88. package/dist/utils/inline-text.js +60 -0
  89. package/dist/utils/inline-text.js.map +1 -0
  90. package/package.json +108 -4
  91. package/server.json +120 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"feature-codes.js","sourceRoot":"","sources":["../../../src/services/geonames/feature-codes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,oDAAoD;AACpD,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAA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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6qBZ,CAAC;AAEF,4EAA4E;AAC5E,MAAM,CAAC,MAAM,aAAa,GAA2B,IAAI,CAAC,IAAI,EAAE;KAC7D,KAAK,CAAC,IAAI,CAAC;KACX,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;IACX,MAAM,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAK5D,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AAC/E,CAAC,CAAC,CAAC;AAEL,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;AAE3E,6FAA6F;AAC7F,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC"}
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @fileoverview GeoNamesService: one method per GeoNames JSON endpoint behind a shared
3
+ * pipeline — account resolution, a cross-caller cache keyed without the account,
4
+ * per-account single-flight, a retry ladder with a total deadline, a per-account
5
+ * pacer, and a plain-fetch boundary with an accept-list and a byte ceiling.
6
+ * @module services/geonames/geonames-service
7
+ */
8
+ import type { Context } from '@cyanheads/mcp-ts-core';
9
+ import { createPacer } from '@cyanheads/mcp-ts-core/utils';
10
+ import type { AccountSource, ChildHierarchy, ChildrenResult, CountryInfo, NearbyFeaturesParams, NearbyPlacesParams, Ocean, PlaceRecord, PostalCode, PostalCountry, PostalNearbyParams, PostalSearchParams, SearchParams, SearchResult, Subdivision, TimezoneInfo, Toponym } from './types.js';
11
+ /** The fetch signature the service calls; global `fetch` and test fakes both satisfy it. */
12
+ export type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
13
+ /** Constructor seams (see the design's Test Boundary). */
14
+ export interface GeoNamesServiceOptions {
15
+ baseUrl?: string;
16
+ createPacer?: typeof createPacer;
17
+ fetch?: FetchLike;
18
+ now?: () => number;
19
+ /** The operator's `GEONAMES_USERNAME`, used when a call passes none. */
20
+ serverUsername?: string | undefined;
21
+ }
22
+ /**
23
+ * The GeoNames account a call spends. The username is a private field read through a
24
+ * prototype getter, so serializing the account (a log record, error data) carries
25
+ * only `source` and the hashed `key`.
26
+ */
27
+ export declare class GeoNamesAccount {
28
+ #private;
29
+ /** `server`, or `caller:` plus the first 16 hex characters of SHA-256(username). */
30
+ readonly key: string;
31
+ readonly source: AccountSource;
32
+ constructor(source: AccountSource, username: string);
33
+ /** The raw username: for the request URL and message scrubbing only. */
34
+ get username(): string;
35
+ }
36
+ /** Upstream access for every GeoNames tool. Construct through {@link initGeoNamesService}. */
37
+ export declare class GeoNamesService {
38
+ #private;
39
+ constructor(options?: GeoNamesServiceOptions);
40
+ /** True when the operator configured `GEONAMES_USERNAME`. */
41
+ get hasServerAccount(): boolean;
42
+ /**
43
+ * The account a call spends: the caller's `geonamesUsername` when given, else the
44
+ * server's. Throws `username_required` before any I/O when neither exists.
45
+ */
46
+ resolveAccount(callerUsername: string | undefined): GeoNamesAccount;
47
+ /** Disposes every pacer, rejecting queued waiters. Wired through `teardown`. */
48
+ dispose(): void;
49
+ /** `searchJSON` (1 credit, cached 1 h). */
50
+ search(params: SearchParams, account: GeoNamesAccount, ctx: Context): Promise<SearchResult>;
51
+ /** `getJSON` (1 credit, cached 24 h); `undefined` when GeoNames has no such feature. */
52
+ getPlace(geonameId: string, account: GeoNamesAccount, ctx: Context): Promise<PlaceRecord | undefined>;
53
+ /**
54
+ * `hierarchyJSON` (1 credit, cached 24 h): Earth first, the feature last. An unknown id
55
+ * answers an Earth-only chain, so `undefined` whenever the chain does not end at it.
56
+ */
57
+ hierarchy(geonameId: string, account: GeoNamesAccount, ctx: Context): Promise<Toponym[] | undefined>;
58
+ /**
59
+ * `childrenJSON` (1 credit, cached 24 h), fetched whole (up to 1,000 rows) because
60
+ * GeoNames ignores `startRow` here. `undefined` for an unknown id (status 11); a leaf
61
+ * (status 15 or an empty list) is an empty result.
62
+ */
63
+ children(geonameId: string, hierarchy: ChildHierarchy, account: GeoNamesAccount, ctx: Context): Promise<ChildrenResult | undefined>;
64
+ /**
65
+ * `countrySubdivisionJSON?level=5` (1 credit, cached 24 h). `undefined` when no country
66
+ * contains the point (status 15) — a result, cached like any other. A `bufferKm` above 0
67
+ * is sent as `radius`, matching the nearest country within it; at 0 no `radius` is sent,
68
+ * so the request and its cache key are the unbuffered ones. `maxRows` is never sent:
69
+ * beside `radius` it switches the response to a list of subdivisions.
70
+ */
71
+ subdivision(lat: number, lng: number, account: GeoNamesAccount, ctx: Context, options?: {
72
+ bufferKm?: number;
73
+ }): Promise<Subdivision | undefined>;
74
+ /**
75
+ * `oceanJSON` (1 credit, cached 24 h). `undefined` when GeoNames knows no water body
76
+ * there either (status 15). `deadlineMs` narrows the ladder for a follow-up call.
77
+ */
78
+ ocean(lat: number, lng: number, account: GeoNamesAccount, ctx: Context, options?: {
79
+ deadlineMs?: number;
80
+ }): Promise<Ocean | undefined>;
81
+ /** `findNearbyPlaceNameJSON` (3 credits, cached 24 h): nearest populated places. */
82
+ nearbyPlaces(params: NearbyPlacesParams, account: GeoNamesAccount, ctx: Context): Promise<Toponym[]>;
83
+ /** `findNearbyJSON` (4 credits, cached 24 h): nearest features of the given classes/codes. */
84
+ nearbyFeatures(params: NearbyFeaturesParams, account: GeoNamesAccount, ctx: Context): Promise<Toponym[]>;
85
+ /**
86
+ * `timezoneJSON` (1 credit, never cached: it carries the current local time).
87
+ * `undefined` when GeoNames answers status 15.
88
+ */
89
+ timezone(lat: number, lng: number, account: GeoNamesAccount, ctx: Context): Promise<TimezoneInfo | undefined>;
90
+ /** `postalCodeSearchJSON` (1 credit, cached 24 h): by postal code or by place name. */
91
+ postalSearch(params: PostalSearchParams, account: GeoNamesAccount, ctx: Context): Promise<PostalCode[]>;
92
+ /** `findNearbyPostalCodesJSON` (2 credits, cached 24 h), nearest first. */
93
+ postalNearby(params: PostalNearbyParams, account: GeoNamesAccount, ctx: Context): Promise<PostalCode[]>;
94
+ /** `countryInfoJSON` with no filter (1 credit, cached 24 h): all 250 countries. */
95
+ countries(account: GeoNamesAccount, ctx: Context): Promise<CountryInfo[]>;
96
+ /** `postalCodeCountryInfoJSON` (1 credit, cached 24 h): the countries with postal data. */
97
+ postalCountries(account: GeoNamesAccount, ctx: Context): Promise<PostalCountry[]>;
98
+ }
99
+ /** Builds the process-wide service; called from `setup()`. */
100
+ export declare function initGeoNamesService(options?: GeoNamesServiceOptions): GeoNamesService;
101
+ /** The process-wide service. Throws when `setup()` has not run. */
102
+ export declare function getGeoNamesService(): GeoNamesService;
103
+ //# sourceMappingURL=geonames-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"geonames-service.d.ts","sourceRoot":"","sources":["../../../src/services/geonames/geonames-service.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAEtD,OAAO,EACL,WAAW,EAMZ,MAAM,8BAA8B,CAAC;AAgBtC,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EACd,cAAc,EACd,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,KAAK,EACL,WAAW,EACX,UAAU,EACV,aAAa,EACb,kBAAkB,EAClB,kBAAkB,EAClB,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,OAAO,EACR,MAAM,YAAY,CAAC;AAmCpB,4FAA4F;AAC5F,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,C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AED,2EAA2E;IAC3E,YAAY,CACV,MAAM,EAAE,kBAAkB,EAC1B,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,OAAO,GACX,OAAO,CAAC,UAAU,EAAE,CAAC,CAiBvB;IAED,mFAAmF;IACnF,SAAS,CAAC,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAWxE;IAED,2FAA2F;IAC3F,eAAe,CAAC,OAAO,EAAE,eAAe,EAAE,GAAG,EAAE,OAAO,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAWhF;CAuNF;AAMD,8DAA8D;AAC9D,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,sBAA2B,GAAG,eAAe,CAIzF;AAED,mEAAmE;AACnE,wBAAgB,kBAAkB,IAAI,eAAe,CAKpD"}
@@ -0,0 +1,561 @@
1
+ /**
2
+ * @fileoverview GeoNamesService: one method per GeoNames JSON endpoint behind a shared
3
+ * pipeline — account resolution, a cross-caller cache keyed without the account,
4
+ * per-account single-flight, a retry ladder with a total deadline, a per-account
5
+ * pacer, and a plain-fetch boundary with an accept-list and a byte ceiling.
6
+ * @module services/geonames/geonames-service
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ import { McpError } from '@cyanheads/mcp-ts-core/errors';
10
+ import { createPacer, defaultIsTransient, logger, withExtra, withRetry, } from '@cyanheads/mcp-ts-core/utils';
11
+ import { ResponseCache } from './response-cache.js';
12
+ import { isRecord, parseChildren, parseCountries, parseOcean, parsePlace, parsePostalCodes, parsePostalCountries, parseSearch, parseSubdivision, parseTimezone, parseToponyms, } from './response-parsers.js';
13
+ import { mapStatus, quotaFromShed, reasonOf, upstreamDeadlineExceeded, upstreamHttpError, upstreamTimedOut, upstreamUnreachable, upstreamUnreadable, usernameRequired, } from './upstream-errors.js';
14
+ const DEFAULT_BASE_URL = 'https://secure.geonames.org';
15
+ const ATTEMPT_TIMEOUT_MS = 10_000;
16
+ const LADDER_DEADLINE_MS = 20_000;
17
+ const MAX_QUEUE_WAIT_MS = 10_000;
18
+ const MAX_BODY_BYTES = 2 * 1024 * 1024;
19
+ const MAX_CALLER_PACERS = 256;
20
+ const HOUR_MS = 3_600_000;
21
+ const DAY_MS = 24 * HOUR_MS;
22
+ /** Earth's geonameId: its hierarchy is the Earth-only chain an unknown id also returns. */
23
+ const EARTH_GEONAME_ID = 6_295_630;
24
+ /** HTTP statuses whose body is read as a GeoNames payload (status 10 → 401, 11 → 404). */
25
+ const READABLE_STATUSES = new Set([200, 401, 404]);
26
+ /**
27
+ * The Unicode Tags block: invisible to people, readable by models, and never part of a
28
+ * place name, so no decoded GeoNames string keeps one.
29
+ */
30
+ const TAG_CHARACTERS = /[\u{e0000}-\u{e007f}]/gu;
31
+ /**
32
+ * The GeoNames account a call spends. The username is a private field read through a
33
+ * prototype getter, so serializing the account (a log record, error data) carries
34
+ * only `source` and the hashed `key`.
35
+ */
36
+ export class GeoNamesAccount {
37
+ #username;
38
+ /** `server`, or `caller:` plus the first 16 hex characters of SHA-256(username). */
39
+ key;
40
+ source;
41
+ constructor(source, username) {
42
+ this.#username = username;
43
+ this.source = source;
44
+ this.key =
45
+ source === 'server'
46
+ ? 'server'
47
+ : `caller:${createHash('sha256').update(username).digest('hex').slice(0, 16)}`;
48
+ }
49
+ /** The raw username: for the request URL and message scrubbing only. */
50
+ get username() {
51
+ return this.#username;
52
+ }
53
+ }
54
+ /** Returns the body for a `body` payload; a result status yields `onMiss`. */
55
+ function bodyOr(payload, onMiss, parse) {
56
+ return payload.kind === 'miss' ? onMiss : parse(payload.body);
57
+ }
58
+ /** Endpoint + sorted params: the account never enters a cache key. */
59
+ function cacheKeyOf(endpoint, params) {
60
+ const sorted = params.toSorted(([a, av], [b, bv]) => a.localeCompare(b) || av.localeCompare(bv));
61
+ return `${endpoint}?${new URLSearchParams(sorted.map(([k, v]) => [k, v])).toString()}`;
62
+ }
63
+ /** `withRetry` predicate: the framework default, except a spent quota fails at once. */
64
+ const isTransient = (error) => reasonOf(error) !== 'quota_exhausted' && defaultIsTransient(error);
65
+ /** Upstream access for every GeoNames tool. Construct through {@link initGeoNamesService}. */
66
+ export class GeoNamesService {
67
+ #baseUrl;
68
+ #cache;
69
+ #createPacer;
70
+ #fetch;
71
+ #flights = new Map();
72
+ /** Caller-account pacers, least recently used first. */
73
+ #pacers = new Map();
74
+ #serverAccount;
75
+ #serverPacer;
76
+ constructor(options = {}) {
77
+ this.#baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
78
+ this.#createPacer = options.createPacer ?? createPacer;
79
+ this.#fetch = options.fetch ?? ((url, init) => fetch(url, init));
80
+ this.#cache = new ResponseCache({
81
+ maxBytes: 32 * 1024 * 1024,
82
+ maxEntries: 5_000,
83
+ now: options.now ?? Date.now,
84
+ });
85
+ this.#serverAccount =
86
+ options.serverUsername === undefined
87
+ ? undefined
88
+ : new GeoNamesAccount('server', options.serverUsername);
89
+ }
90
+ /** True when the operator configured `GEONAMES_USERNAME`. */
91
+ get hasServerAccount() {
92
+ return this.#serverAccount !== undefined;
93
+ }
94
+ /**
95
+ * The account a call spends: the caller's `geonamesUsername` when given, else the
96
+ * server's. Throws `username_required` before any I/O when neither exists.
97
+ */
98
+ resolveAccount(callerUsername) {
99
+ if (callerUsername !== undefined)
100
+ return new GeoNamesAccount('caller', callerUsername);
101
+ if (this.#serverAccount)
102
+ return this.#serverAccount;
103
+ throw usernameRequired();
104
+ }
105
+ /** Disposes every pacer, rejecting queued waiters. Wired through `teardown`. */
106
+ dispose() {
107
+ this.#serverPacer?.dispose();
108
+ this.#serverPacer = undefined;
109
+ for (const pacer of this.#pacers.values())
110
+ pacer.dispose();
111
+ this.#pacers.clear();
112
+ }
113
+ /** `searchJSON` (1 credit, cached 1 h). */
114
+ search(params, account, ctx) {
115
+ const query = [];
116
+ if (params.query !== undefined) {
117
+ switch (params.match ?? 'name_required') {
118
+ case 'name_required':
119
+ query.push(['q', params.query], ['isNameRequired', 'true']);
120
+ break;
121
+ case 'any_field':
122
+ query.push(['q', params.query]);
123
+ break;
124
+ case 'exact_name':
125
+ query.push(['name_equals', params.query]);
126
+ break;
127
+ case 'name_prefix':
128
+ query.push(['name_startsWith', params.query]);
129
+ break;
130
+ }
131
+ }
132
+ for (const country of params.countries ?? [])
133
+ query.push(['country', country]);
134
+ for (const featureClass of params.featureClasses ?? [])
135
+ query.push(['featureClass', featureClass]);
136
+ for (const featureCode of params.featureCodes ?? [])
137
+ query.push(['featureCode', featureCode]);
138
+ if (params.cities)
139
+ query.push(['cities', params.cities]);
140
+ if (params.boundingBox) {
141
+ const { north, south, east, west } = params.boundingBox;
142
+ query.push(['north', String(north)], ['south', String(south)], ['east', String(east)], ['west', String(west)]);
143
+ }
144
+ if (params.orderBy === 'population')
145
+ query.push(['orderby', 'population']);
146
+ query.push(['maxRows', String(params.limit)], ['startRow', String(params.offset)]);
147
+ return this.#call({
148
+ endpoint: 'searchJSON',
149
+ params: query,
150
+ ttlMs: HOUR_MS,
151
+ parse: (payload) => bodyOr(payload, { places: [], totalCount: 0 }, parseSearch),
152
+ }, account, ctx);
153
+ }
154
+ /** `getJSON` (1 credit, cached 24 h); `undefined` when GeoNames has no such feature. */
155
+ getPlace(geonameId, account, ctx) {
156
+ return this.#call({
157
+ endpoint: 'getJSON',
158
+ params: [['geonameId', geonameId]],
159
+ ttlMs: DAY_MS,
160
+ parse: (payload) => bodyOr(payload, undefined, parsePlace),
161
+ cacheable: (place) => place !== undefined,
162
+ }, account, ctx);
163
+ }
164
+ /**
165
+ * `hierarchyJSON` (1 credit, cached 24 h): Earth first, the feature last. An unknown id
166
+ * answers an Earth-only chain, so `undefined` whenever the chain does not end at it.
167
+ */
168
+ hierarchy(geonameId, account, ctx) {
169
+ const id = Number(geonameId);
170
+ return this.#call({
171
+ endpoint: 'hierarchyJSON',
172
+ params: [['geonameId', geonameId]],
173
+ ttlMs: DAY_MS,
174
+ parse: (payload) => {
175
+ const chain = bodyOr(payload, [], (body) => parseToponyms(body, 'hierarchyJSON'));
176
+ return chain.at(-1)?.geonameId === id || id === EARTH_GEONAME_ID ? chain : undefined;
177
+ },
178
+ cacheable: (chain) => chain !== undefined,
179
+ }, account, ctx);
180
+ }
181
+ /**
182
+ * `childrenJSON` (1 credit, cached 24 h), fetched whole (up to 1,000 rows) because
183
+ * GeoNames ignores `startRow` here. `undefined` for an unknown id (status 11); a leaf
184
+ * (status 15 or an empty list) is an empty result.
185
+ */
186
+ children(geonameId, hierarchy, account, ctx) {
187
+ const params = [
188
+ ['geonameId', geonameId],
189
+ ['maxRows', '1000'],
190
+ ];
191
+ if (hierarchy !== 'administrative')
192
+ params.push(['hierarchy', hierarchy]);
193
+ return this.#call({
194
+ endpoint: 'childrenJSON',
195
+ params,
196
+ ttlMs: DAY_MS,
197
+ parse: (payload) => payload.kind === 'miss'
198
+ ? payload.status === 11
199
+ ? undefined
200
+ : { children: [], totalCount: 0 }
201
+ : parseChildren(payload.body),
202
+ cacheable: (result) => result !== undefined,
203
+ }, account, ctx);
204
+ }
205
+ /**
206
+ * `countrySubdivisionJSON?level=5` (1 credit, cached 24 h). `undefined` when no country
207
+ * contains the point (status 15) — a result, cached like any other. A `bufferKm` above 0
208
+ * is sent as `radius`, matching the nearest country within it; at 0 no `radius` is sent,
209
+ * so the request and its cache key are the unbuffered ones. `maxRows` is never sent:
210
+ * beside `radius` it switches the response to a list of subdivisions.
211
+ */
212
+ subdivision(lat, lng, account, ctx, options = {}) {
213
+ const params = [
214
+ ['lat', String(lat)],
215
+ ['lng', String(lng)],
216
+ ['level', '5'],
217
+ ];
218
+ if (options.bufferKm)
219
+ params.push(['radius', String(options.bufferKm)]);
220
+ return this.#call({
221
+ endpoint: 'countrySubdivisionJSON',
222
+ params,
223
+ ttlMs: DAY_MS,
224
+ parse: (payload) => bodyOr(payload, undefined, parseSubdivision),
225
+ }, account, ctx);
226
+ }
227
+ /**
228
+ * `oceanJSON` (1 credit, cached 24 h). `undefined` when GeoNames knows no water body
229
+ * there either (status 15). `deadlineMs` narrows the ladder for a follow-up call.
230
+ */
231
+ ocean(lat, lng, account, ctx, options = {}) {
232
+ return this.#call({
233
+ endpoint: 'oceanJSON',
234
+ params: [
235
+ ['lat', String(lat)],
236
+ ['lng', String(lng)],
237
+ ],
238
+ ttlMs: DAY_MS,
239
+ parse: (payload) => bodyOr(payload, undefined, parseOcean),
240
+ deadlineMs: options.deadlineMs,
241
+ }, account, ctx);
242
+ }
243
+ /** `findNearbyPlaceNameJSON` (3 credits, cached 24 h): nearest populated places. */
244
+ nearbyPlaces(params, account, ctx) {
245
+ const query = [
246
+ ['lat', String(params.lat)],
247
+ ['lng', String(params.lng)],
248
+ ['radius', String(params.radiusKm)],
249
+ ['maxRows', String(params.limit)],
250
+ ];
251
+ if (params.cities)
252
+ query.push(['cities', params.cities]);
253
+ return this.#call({
254
+ endpoint: 'findNearbyPlaceNameJSON',
255
+ params: query,
256
+ ttlMs: DAY_MS,
257
+ parse: (payload) => bodyOr(payload, [], (body) => parseToponyms(body, 'findNearbyPlaceNameJSON')),
258
+ }, account, ctx);
259
+ }
260
+ /** `findNearbyJSON` (4 credits, cached 24 h): nearest features of the given classes/codes. */
261
+ nearbyFeatures(params, account, ctx) {
262
+ const query = [
263
+ ['lat', String(params.lat)],
264
+ ['lng', String(params.lng)],
265
+ ['radius', String(params.radiusKm)],
266
+ ['maxRows', String(params.limit)],
267
+ ];
268
+ for (const featureClass of params.featureClasses ?? [])
269
+ query.push(['featureClass', featureClass]);
270
+ for (const featureCode of params.featureCodes ?? [])
271
+ query.push(['featureCode', featureCode]);
272
+ return this.#call({
273
+ endpoint: 'findNearbyJSON',
274
+ params: query,
275
+ ttlMs: DAY_MS,
276
+ parse: (payload) => bodyOr(payload, [], (body) => parseToponyms(body, 'findNearbyJSON')),
277
+ }, account, ctx);
278
+ }
279
+ /**
280
+ * `timezoneJSON` (1 credit, never cached: it carries the current local time).
281
+ * `undefined` when GeoNames answers status 15.
282
+ */
283
+ timezone(lat, lng, account, ctx) {
284
+ return this.#call({
285
+ endpoint: 'timezoneJSON',
286
+ params: [
287
+ ['lat', String(lat)],
288
+ ['lng', String(lng)],
289
+ ],
290
+ ttlMs: 0,
291
+ parse: (payload) => bodyOr(payload, undefined, parseTimezone),
292
+ }, account, ctx);
293
+ }
294
+ /** `postalCodeSearchJSON` (1 credit, cached 24 h): by postal code or by place name. */
295
+ postalSearch(params, account, ctx) {
296
+ const query = [];
297
+ if (params.postalCode !== undefined)
298
+ query.push(['postalcode', params.postalCode]);
299
+ if (params.placeName !== undefined)
300
+ query.push(['placename', params.placeName]);
301
+ for (const country of params.countries ?? [])
302
+ query.push(['country', country]);
303
+ query.push(['maxRows', String(params.limit)]);
304
+ return this.#call({
305
+ endpoint: 'postalCodeSearchJSON',
306
+ params: query,
307
+ ttlMs: DAY_MS,
308
+ parse: (payload) => bodyOr(payload, [], (body) => parsePostalCodes(body, 'postalCodeSearchJSON')),
309
+ }, account, ctx);
310
+ }
311
+ /** `findNearbyPostalCodesJSON` (2 credits, cached 24 h), nearest first. */
312
+ postalNearby(params, account, ctx) {
313
+ return this.#call({
314
+ endpoint: 'findNearbyPostalCodesJSON',
315
+ params: [
316
+ ['lat', String(params.lat)],
317
+ ['lng', String(params.lng)],
318
+ ['radius', String(params.radiusKm)],
319
+ ['maxRows', String(params.limit)],
320
+ ],
321
+ ttlMs: DAY_MS,
322
+ parse: (payload) => bodyOr(payload, [], (body) => parsePostalCodes(body, 'findNearbyPostalCodesJSON')),
323
+ }, account, ctx);
324
+ }
325
+ /** `countryInfoJSON` with no filter (1 credit, cached 24 h): all 250 countries. */
326
+ countries(account, ctx) {
327
+ return this.#call({
328
+ endpoint: 'countryInfoJSON',
329
+ params: [],
330
+ ttlMs: DAY_MS,
331
+ parse: (payload) => bodyOr(payload, [], parseCountries),
332
+ }, account, ctx);
333
+ }
334
+ /** `postalCodeCountryInfoJSON` (1 credit, cached 24 h): the countries with postal data. */
335
+ postalCountries(account, ctx) {
336
+ return this.#call({
337
+ endpoint: 'postalCodeCountryInfoJSON',
338
+ params: [],
339
+ ttlMs: DAY_MS,
340
+ parse: (payload) => bodyOr(payload, [], parsePostalCountries),
341
+ }, account, ctx);
342
+ }
343
+ /** Cache → single-flight → retry ladder; stores successes the spec deems cacheable. */
344
+ #call(spec, account, ctx) {
345
+ const cacheKey = cacheKeyOf(spec.endpoint, spec.params);
346
+ if (spec.ttlMs > 0) {
347
+ const hit = this.#cache.get(cacheKey);
348
+ if (hit)
349
+ return Promise.resolve(hit.value);
350
+ }
351
+ return this.#singleFlight(`${account.key} ${cacheKey}`, ctx, async () => {
352
+ const { value, bytes } = await this.#fetchWithRetry(spec, account, ctx);
353
+ if (spec.ttlMs > 0 && (spec.cacheable?.(value) ?? true)) {
354
+ this.#cache.set(cacheKey, value, bytes, spec.ttlMs);
355
+ }
356
+ return value;
357
+ });
358
+ }
359
+ /**
360
+ * Joins an identical in-flight request on the same account, else starts one. A joiner
361
+ * whose leader was cancelled starts its own request instead of inheriting the abort.
362
+ */
363
+ async #singleFlight(key, ctx, run) {
364
+ const existing = this.#flights.get(key);
365
+ if (existing) {
366
+ try {
367
+ return (await existing.promise);
368
+ }
369
+ catch (error) {
370
+ if (!existing.signal.aborted || ctx.signal.aborted)
371
+ throw error;
372
+ }
373
+ }
374
+ const flight = { promise: run(), signal: ctx.signal };
375
+ this.#flights.set(key, flight);
376
+ try {
377
+ return (await flight.promise);
378
+ }
379
+ finally {
380
+ if (this.#flights.get(key) === flight)
381
+ this.#flights.delete(key);
382
+ }
383
+ }
384
+ /** The retry ladder; its total-deadline expiry is restated as `upstream_timeout`. */
385
+ #fetchWithRetry(spec, account, ctx) {
386
+ const pacer = this.#pacerFor(account);
387
+ const ladder = withRetry(async ({ remainingMs, signal }) => {
388
+ try {
389
+ return await pacer.run((taskSignal) => this.#attempt(spec, account, ctx, taskSignal), {
390
+ signal,
391
+ maxWaitMs: Math.min(MAX_QUEUE_WAIT_MS, remainingMs),
392
+ });
393
+ }
394
+ catch (error) {
395
+ if (reasonOf(error) === 'pacer_shed') {
396
+ throw quotaFromShed(error, account.source, pacer.cooldown.remainingMs);
397
+ }
398
+ throw error;
399
+ }
400
+ }, {
401
+ operation: `GeoNamesService.${spec.endpoint}`,
402
+ context: ctx,
403
+ signal: ctx.signal,
404
+ maxRetries: 2,
405
+ baseDelayMs: 1_000,
406
+ maxDelayMs: 5_000,
407
+ deadlineMs: spec.deadlineMs ?? LADDER_DEADLINE_MS,
408
+ isTransient,
409
+ });
410
+ return ladder.catch((error) => {
411
+ throw error instanceof McpError && reasonOf(error) === 'retry_deadline_exceeded'
412
+ ? upstreamDeadlineExceeded(error)
413
+ : error;
414
+ });
415
+ }
416
+ /**
417
+ * One paced attempt: fetch, bounded read, JSON, status mapping, row parse. A failure
418
+ * while the call is cancelled or out of time surfaces as the abort reason, so the
419
+ * runtime's own error, which can carry the request URL, never enters an error chain.
420
+ * The response record goes to the process logger only: through `ctx.log` it would
421
+ * tell the client a cache miss from a hit.
422
+ */
423
+ async #attempt(spec, account, ctx, signal) {
424
+ const timer = AbortSignal.timeout(ATTEMPT_TIMEOUT_MS);
425
+ const attemptSignal = AbortSignal.any([signal, timer]);
426
+ const url = new URL(`${this.#baseUrl}/${spec.endpoint}`);
427
+ for (const [key, value] of spec.params)
428
+ url.searchParams.append(key, value);
429
+ url.searchParams.append('username', account.username);
430
+ let response;
431
+ try {
432
+ response = await this.#fetch(url.href, {
433
+ headers: { accept: 'application/json' },
434
+ redirect: 'manual',
435
+ signal: attemptSignal,
436
+ });
437
+ }
438
+ catch {
439
+ signal.throwIfAborted();
440
+ throw timer.aborted ? upstreamTimedOut() : upstreamUnreachable();
441
+ }
442
+ const { bytes, text } = await this.#readBody(response, signal, timer);
443
+ logger.debug('GeoNames response', withExtra(ctx, {
444
+ endpoint: spec.endpoint,
445
+ httpStatus: response.status,
446
+ bodyBytes: bytes,
447
+ account: account.source,
448
+ }));
449
+ return { bytes, value: spec.parse(this.#toPayload(response.status, text, account)) };
450
+ }
451
+ /**
452
+ * Reads the body under the byte ceiling. A redirect, overflow, or broken stream is
453
+ * unreadable; a failure while the call is cancelled or out of time surfaces as the
454
+ * abort reason, as in `#attempt`.
455
+ */
456
+ async #readBody(response, signal, timer) {
457
+ if (response.status < 200 || (response.status >= 300 && response.status < 400)) {
458
+ await response.body?.cancel().catch(() => undefined);
459
+ throw upstreamUnreadable();
460
+ }
461
+ const reader = response.body?.getReader();
462
+ if (!reader)
463
+ return { bytes: 0, text: '' };
464
+ const chunks = [];
465
+ let bytes = 0;
466
+ try {
467
+ let chunk = await reader.read();
468
+ while (!chunk.done) {
469
+ bytes += chunk.value.byteLength;
470
+ if (bytes > MAX_BODY_BYTES) {
471
+ await reader.cancel().catch(() => undefined);
472
+ throw upstreamUnreadable();
473
+ }
474
+ chunks.push(chunk.value);
475
+ chunk = await reader.read();
476
+ }
477
+ }
478
+ catch (error) {
479
+ if (reasonOf(error) === 'upstream_unreadable')
480
+ throw error;
481
+ signal.throwIfAborted();
482
+ throw timer.aborted ? upstreamTimedOut() : upstreamUnreadable();
483
+ }
484
+ return { bytes, text: new TextDecoder().decode(Buffer.concat(chunks)) };
485
+ }
486
+ /**
487
+ * Classifies a read body: a status envelope by its value, else the HTTP accept-list.
488
+ * Every decoded string loses its Unicode tag characters.
489
+ */
490
+ #toPayload(httpStatus, text, account) {
491
+ let json;
492
+ try {
493
+ json = JSON.parse(text, (_key, value) => typeof value === 'string' ? value.replace(TAG_CHARACTERS, '') : value);
494
+ }
495
+ catch {
496
+ json = undefined;
497
+ }
498
+ const status = isRecord(json) && isRecord(json.status) ? json.status : undefined;
499
+ if (status && typeof status.value === 'number') {
500
+ const message = typeof status.message === 'string' ? status.message : '';
501
+ return {
502
+ kind: 'miss',
503
+ status: mapStatus(status.value, message, account, this.hasServerAccount),
504
+ };
505
+ }
506
+ if (!READABLE_STATUSES.has(httpStatus))
507
+ throw upstreamHttpError(httpStatus);
508
+ if (!isRecord(json))
509
+ throw upstreamUnreadable();
510
+ return { kind: 'body', body: json };
511
+ }
512
+ /**
513
+ * The account's pacer, created on first use. The server's lives outside the caller map
514
+ * and is never evicted. Past 256 callers the least recently used caller pacer leaves the
515
+ * map undisposed: its timers are unref'd, so work already queued on it drains.
516
+ */
517
+ #pacerFor(account) {
518
+ if (account.source === 'server') {
519
+ this.#serverPacer ??= this.#newPacer();
520
+ return this.#serverPacer;
521
+ }
522
+ const existing = this.#pacers.get(account.key);
523
+ if (existing) {
524
+ this.#pacers.delete(account.key);
525
+ this.#pacers.set(account.key, existing);
526
+ return existing;
527
+ }
528
+ if (this.#pacers.size >= MAX_CALLER_PACERS) {
529
+ this.#pacers.delete(this.#pacers.keys().next().value);
530
+ }
531
+ const pacer = this.#newPacer();
532
+ this.#pacers.set(account.key, pacer);
533
+ return pacer;
534
+ }
535
+ /** One account's pacer, built from the design's pacing parameters. */
536
+ #newPacer() {
537
+ return this.#createPacer({
538
+ name: 'geonames',
539
+ maxConcurrent: 4,
540
+ minStartGapMs: 100,
541
+ limits: [{ requests: 1_000, perMs: HOUR_MS }],
542
+ cooldown: { baseMs: 60_000, maxMs: HOUR_MS },
543
+ });
544
+ }
545
+ }
546
+ // --- Init/accessor pattern ---
547
+ let _service;
548
+ /** Builds the process-wide service; called from `setup()`. */
549
+ export function initGeoNamesService(options = {}) {
550
+ _service?.dispose();
551
+ _service = new GeoNamesService(options);
552
+ return _service;
553
+ }
554
+ /** The process-wide service. Throws when `setup()` has not run. */
555
+ export function getGeoNamesService() {
556
+ if (!_service) {
557
+ throw new Error('GeoNamesService not initialized: call initGeoNamesService() in setup()');
558
+ }
559
+ return _service;
560
+ }
561
+ //# sourceMappingURL=geonames-service.js.map