7timer-mcp 1.0.0 → 1.0.1

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
@@ -18,3 +18,22 @@ node dist/index.js
18
18
  ```
19
19
 
20
20
  Data comes from the public 7Timer API.
21
+
22
+ <!-- paywall -->
23
+ ## Premium tools
24
+
25
+ These tools need a license key:
26
+
27
+ * `forecast_summary`
28
+ * `daily_outlook`
29
+
30
+ Buy a key at https://mcp-marketplace.io/server/io-github-mrfentmen-7timer-mcp and set it in your MCP client config:
31
+
32
+ ```json
33
+ "env": { "MCP_LICENSE_KEY": "mcp_live_..." }
34
+ ```
35
+
36
+ The key is checked against MCP Marketplace, cached for 24 hours, and keeps
37
+ working offline once one check has succeeded. Every other tool on this server
38
+ stays free.
39
+ <!-- /paywall -->
package/dist/api.js CHANGED
@@ -25,3 +25,156 @@ export async function forecast(args) {
25
25
  return `+${s('timepoint')}h | ${icon} | ${s('temp2m')}C | precip ${s('prec_type')} | ${s('rh2m')}% RH`;
26
26
  }).join('\n');
27
27
  }
28
+ // ---- muxF tools:
29
+ const PLACE_BASE = 'https://nominatim.openstreetmap.org';
30
+ const CONDITIONS = {
31
+ clear: 'clear',
32
+ pcloudy: 'partly cloudy',
33
+ cloudy: 'cloudy',
34
+ cloudynight: 'cloudy at night',
35
+ cloudyday: 'cloudy by day',
36
+ lightrain: 'light rain',
37
+ rainday: 'rain by day',
38
+ rainnight: 'rain at night',
39
+ rain: 'rain',
40
+ snow: 'snow',
41
+ snowday: 'snow by day',
42
+ snownight: 'snow at night',
43
+ tstorm: 'thunderstorm',
44
+ tstormday: 'thunderstorm by day',
45
+ tstormnight: 'thunderstorm at night',
46
+ humid: 'humid',
47
+ fog: 'fog',
48
+ windy: 'windy',
49
+ };
50
+ async function product(name, lat, lon) {
51
+ const params = new URLSearchParams({ lon: String(lon), lat: String(lat), product: name, output: 'json' });
52
+ const res = await fetch(`${BASE}?${params.toString()}`, {
53
+ headers: { 'User-Agent': 'mrfentmen-7timer-mcp/1.0', Accept: 'application/json' },
54
+ signal: AbortSignal.timeout(20000),
55
+ });
56
+ if (!res.ok)
57
+ throw new Error(`7Timer returned ${res.status}`);
58
+ return (await res.json());
59
+ }
60
+ function coords(args) {
61
+ const lat = Number(args.lat);
62
+ const lon = Number(args.lon);
63
+ if (!Number.isFinite(lat) || !Number.isFinite(lon))
64
+ throw new Error('Provide valid latitude and longitude.');
65
+ if (lat < -90 || lat > 90)
66
+ throw new Error('Latitude must be between -90 and 90.');
67
+ if (lon < -180 || lon > 180)
68
+ throw new Error('Longitude must be between -180 and 180.');
69
+ return { lat, lon };
70
+ }
71
+ function num(value, min, max, fallback) {
72
+ const n = Number(value);
73
+ if (!Number.isFinite(n))
74
+ return fallback;
75
+ return Math.max(min, Math.min(n, max));
76
+ }
77
+ function condition(name) {
78
+ const key = typeof name === 'string' ? name : '';
79
+ return CONDITIONS[key] ?? key ?? 'not reported';
80
+ }
81
+ /** What the whole 7Timer series adds up to: extremes and when they land, rain totals, wind and cloud trend. */
82
+ export async function forecastSummary(args) {
83
+ const { lat, lon } = coords(args);
84
+ const data = (await product('civil', lat, lon));
85
+ const rows = data.dataseries ?? [];
86
+ if (!rows.length)
87
+ throw new Error('7Timer returned no civil dataseries for that point.');
88
+ const temps = rows.map((r) => Number(r.temp2m)).filter((n) => Number.isFinite(n));
89
+ const rain = rows.filter((r) => r.prec_type && r.prec_type !== 'none');
90
+ const rainTotal = rows.reduce((sum, r) => sum + (Number(r.prec_amount) || 0), 0);
91
+ const winds = rows.map((r) => Number(r.wind10m?.speed) || 0);
92
+ const clouds = rows.map((r) => Number(r.cloudcover) || 0);
93
+ const lifted = rows.map((r) => Number(r.lifted_index)).filter((n) => Number.isFinite(n));
94
+ const coldest = rows.reduce((a, b) => ((Number(b.temp2m) || 0) < (Number(a.temp2m) || 0) ? b : a), rows[0]);
95
+ const hottest = rows.reduce((a, b) => ((Number(b.temp2m) || 0) > (Number(a.temp2m) || 0) ? b : a), rows[0]);
96
+ const cloudiest = rows.reduce((a, b) => ((Number(b.cloudcover) || 0) > (Number(a.cloudcover) || 0) ? b : a), rows[0]);
97
+ const windiest = rows.reduce((a, b) => ((Number(b.wind10m?.speed) || 0) > (Number(a.wind10m?.speed) || 0) ? b : a), rows[0]);
98
+ const mean = (values) => (values.length ? (values.reduce((x, y) => x + y, 0) / values.length).toFixed(1) : 'not reported');
99
+ return [
100
+ `7Timer civil series for ${lat}, ${lon}, initialised ${String(data.init ?? 'not reported')}`,
101
+ `Periods in the series: ${rows.length}, 3 hours apart, first at +${String(rows[0].timepoint ?? '?')}h`,
102
+ `Temperature: coldest ${String(coldest.temp2m ?? 'n/a')}C at +${String(coldest.timepoint ?? '?')}h, warmest ${String(hottest.temp2m ?? 'n/a')}C at +${String(hottest.timepoint ?? '?')}h, mean ${mean(temps)}C, range ${temps.length ? (Math.max(...temps) - Math.min(...temps)).toFixed(1) : 'not reported'}C`,
103
+ `Precipitation: ${rain.length} of ${rows.length} period(s) forecast some, ${rainTotal} mm in total across the series`,
104
+ `Conditions named: ${[...new Set(rows.map((r) => condition(r.weather)))].slice(0, 8).join(', ') || 'not reported'}`,
105
+ `Wind at 10 m: mean ${mean(winds)} m/s, strongest ${String(windiest.wind10m?.speed ?? 'n/a')} m/s from ${String(windiest.wind10m?.direction ?? 'not reported')} at +${String(windiest.timepoint ?? '?')}h`,
106
+ `Cloud cover: mean ${mean(clouds)} of 9 oktas, thickest ${String(cloudiest.cloudcover ?? 'n/a')} at +${String(cloudiest.timepoint ?? '?')}h`,
107
+ lifted.length ? `Lifted index: mean ${mean(lifted)} (7Timer reports it per period; positive values indicate a stable layer)` : 'Lifted index: not reported',
108
+ ].join('\n');
109
+ }
110
+ /** The 7Timer daily product: one row per day with the day's weather, its temperature range and peak wind. */
111
+ export async function dailyOutlook(args) {
112
+ const { lat, lon } = coords(args);
113
+ const limit = num(args.limit, 1, 7, 7);
114
+ const payload = (await product('civillight', lat, lon));
115
+ const rows = payload.dataseries ?? [];
116
+ if (!rows.length)
117
+ throw new Error('7Timer returned no daily series for that point.');
118
+ const shown = rows.slice(0, limit);
119
+ const ranges = shown.map((r) => (Number(r.temp2m?.max) || 0) - (Number(r.temp2m?.min) || 0));
120
+ const winds = shown.map((r) => Number(r.wind10m_max) || 0);
121
+ const highs = shown.map((r) => Number(r.temp2m?.max)).filter((n) => Number.isFinite(n));
122
+ const lows = shown.map((r) => Number(r.temp2m?.min)).filter((n) => Number.isFinite(n));
123
+ const wet = shown.filter((r) => /rain|snow|storm/.test(String(r.weather ?? ''))).length;
124
+ return [
125
+ `7Timer daily outlook for ${lat}, ${lon}, initialised ${String(payload.init ?? 'not reported')}`,
126
+ `Days returned: ${rows.length}, showing ${shown.length}`,
127
+ ...shown.map((r) => {
128
+ const date = Number(r.date ?? 0);
129
+ const stamp = date ? String(date).replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3') : 'date not reported';
130
+ const min = Number(r.temp2m?.min);
131
+ const max = Number(r.temp2m?.max);
132
+ return `- ${stamp}: ${condition(r.weather)}, ${Number.isFinite(min) ? `${min}C` : 'min not reported'} to ${Number.isFinite(max) ? `${max}C` : 'max not reported'}, peak wind ${String(r.wind10m_max ?? 'not reported')} m/s`;
133
+ }),
134
+ `Across these days: highs up to ${highs.length ? Math.max(...highs) : 'n/a'}C, lows down to ${lows.length ? Math.min(...lows) : 'n/a'}C, mean daily range ${ranges.length ? (ranges.reduce((a, b) => a + b, 0) / ranges.length).toFixed(1) : 'n/a'}C`,
135
+ `Days 7Timer calls wet: ${wet} of ${shown.length}`,
136
+ winds.length ? `Peak wind across the period: ${Math.max(...winds)} m/s` : 'Peak wind: not reported',
137
+ ].join('\n');
138
+ }
139
+ /** Look a place up by name, then give the 7Timer civil forecast for the first place that matches. */
140
+ export async function forecastByPlace(args) {
141
+ const place = (args.place ?? '').trim();
142
+ if (!place)
143
+ return 'Provide a place name, for example Reykjavik or Wellington.';
144
+ const limit = num(args.limit, 1, 5, 3);
145
+ const url = `${PLACE_BASE}/search?${new URLSearchParams({ q: place, format: 'json', limit: String(limit) }).toString()}`;
146
+ const res = await fetch(url, {
147
+ headers: { 'User-Agent': 'mrfentmen-7timer-mcp/1.0', Accept: 'application/json' },
148
+ signal: AbortSignal.timeout(25000),
149
+ });
150
+ if (!res.ok)
151
+ throw new Error(`Place lookup returned ${res.status}`);
152
+ const places = (await res.json());
153
+ if (!Array.isArray(places) || !places.length)
154
+ return `No place matched "${place}".`;
155
+ const lines = [`Place lookup for "${place}" (OpenStreetMap Nominatim), then 7Timer for the first match:`];
156
+ places.forEach((p, i) => {
157
+ const lat = Number(p.lat);
158
+ const lon = Number(p.lon);
159
+ const tag = [p.type, p.country].filter(Boolean).join(", ");
160
+ lines.push(`${i + 1}. ${String(p.display_name ?? 'name not reported').slice(0, 160)}${tag ? ` (${tag})` : ""}`);
161
+ lines.push(` ${Number.isFinite(lat) ? lat.toFixed(4) : 'lat not reported'}, ${Number.isFinite(lon) ? lon.toFixed(4) : 'lon not reported'}`);
162
+ });
163
+ const first = places[0];
164
+ const lat = Number(first?.lat);
165
+ const lon = Number(first?.lon);
166
+ if (!Number.isFinite(lat) || !Number.isFinite(lon)) {
167
+ lines.push('The first match had no usable coordinates, so no forecast was fetched.');
168
+ return lines.join('\n');
169
+ }
170
+ const data = (await product('civil', lat, lon));
171
+ const rows = data.dataseries ?? [];
172
+ lines.push(`7Timer civil series for that point, initialised ${String(data.init ?? 'not reported')}, ${rows.length} period(s):`);
173
+ for (const r of rows.slice(0, 8)) {
174
+ const rh = typeof r.rh2m === 'string' ? r.rh2m : r.rh2m == null ? 'not reported' : `${String(r.rh2m)}%`;
175
+ lines.push(`+${String(r.timepoint ?? '?')}h | ${condition(r.weather)} | ${String(r.temp2m ?? 'n/a')}C | wind ${String(r.wind10m?.direction ?? '?')} ${String(r.wind10m?.speed ?? '?')} m/s | cloud ${String(r.cloudcover ?? '?')}/9 | RH ${rh}`);
176
+ }
177
+ if (rows.length > 8)
178
+ lines.push(`... and ${rows.length - 8} more period(s) in the series.`);
179
+ return lines.join('\n');
180
+ }
@@ -0,0 +1,79 @@
1
+ // Premium tools on this server need a license key bought from MCP Marketplace.
2
+ // Buyers put the key in their MCP client config as MCP_LICENSE_KEY. Every tool
3
+ // that is not listed in PREMIUM keeps working without a key.
4
+ const SLUG = "7timer-mcp";
5
+ // Tools that need a key. Everything else is free.
6
+ const PREMIUM = new Set([
7
+ "forecast_summary",
8
+ "daily_outlook",
9
+ ]);
10
+ const BUY_URL = `https://mcp-marketplace.io/server/io-github-mrfentmen-${SLUG}`;
11
+ // The license check calls the marketplace's verify endpoint directly instead of
12
+ // using @mcp_marketplace/license. That SDK sends no `apikey` header, so every
13
+ // check it makes is rejected by Supabase before it reaches the function. The
14
+ // publishable key below is public by design - it ships in mcp-marketplace.io's
15
+ // own JavaScript and only ever reaches their licence check.
16
+ const DEFAULT_VERIFY_URL = "https://virupvwhtkpkjsiskckg.supabase.co/functions/v1/verify-key";
17
+ const PUBLISHABLE_KEY = "sb_publishable_BuqlW96Ke8C_zzJG-LQv1Q_YHi_r_4h";
18
+ const OK_CACHE_MS = 60 * 60 * 1000;
19
+ const BAD_CACHE_MS = 60 * 1000;
20
+ const seen = new Map();
21
+ const REASONS = {
22
+ missing_key: "no key is set",
23
+ invalid_format: "that key is not a valid MCP Marketplace key",
24
+ not_found: "that key was not found",
25
+ revoked: "that key has been revoked",
26
+ rotated: "that key was rotated, use your new one",
27
+ expired: "that key has expired, renew it",
28
+ rate_limited: "there were too many checks just now, try again shortly",
29
+ network_error: "the license server could not be reached",
30
+ };
31
+ function blocked(tool, reason) {
32
+ const why = REASONS[reason] ?? `the license server answered "${reason}"`;
33
+ return `"${tool}" needs a license key, but ${why}. ` +
34
+ `Set MCP_LICENSE_KEY in your MCP client config. Get a key: ${BUY_URL}`;
35
+ }
36
+ async function verify(key) {
37
+ const res = await fetch(process.env.MCP_LICENSE_VERIFY_URL || DEFAULT_VERIFY_URL, {
38
+ method: "POST",
39
+ headers: {
40
+ apikey: PUBLISHABLE_KEY,
41
+ Authorization: `Bearer ${PUBLISHABLE_KEY}`,
42
+ "Content-Type": "application/json",
43
+ },
44
+ body: JSON.stringify({ key, slug: SLUG }),
45
+ // an unusable key answers 400 with a JSON body, so read the body either way
46
+ signal: AbortSignal.timeout(15000),
47
+ });
48
+ const data = (await res.json());
49
+ if (typeof data?.valid !== "boolean")
50
+ return { valid: false, reason: "unexpected_response" };
51
+ return data;
52
+ }
53
+ /**
54
+ * Returns null when the caller may run the tool, or a short message telling
55
+ * them how to get a key.
56
+ *
57
+ * A good key is remembered for an hour, so a busy session does not hit the
58
+ * license server on every call and keeps working through a brief outage.
59
+ */
60
+ export async function premiumRequired(tool) {
61
+ if (!PREMIUM.has(tool))
62
+ return null;
63
+ const key = process.env.MCP_LICENSE_KEY;
64
+ if (!key)
65
+ return blocked(tool, "missing_key");
66
+ const hit = seen.get(key);
67
+ if (hit && Date.now() - hit.at < (hit.valid ? OK_CACHE_MS : BAD_CACHE_MS)) {
68
+ return hit.valid ? null : blocked(tool, hit.reason ?? "invalid");
69
+ }
70
+ let result;
71
+ try {
72
+ result = await verify(key);
73
+ }
74
+ catch {
75
+ result = { valid: false, reason: "network_error" };
76
+ }
77
+ seen.set(key, { ...result, at: Date.now() });
78
+ return result.valid ? null : blocked(tool, result.reason ?? "invalid");
79
+ }
package/dist/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { z } from "zod";
3
- import { forecast } from "./api.js";
3
+ import { forecast, forecastSummary, dailyOutlook, forecastByPlace } from "./api.js";
4
+ import { premiumRequired } from "./license.js";
4
5
  const text = (value) => ({ content: [{ type: "text", text: value }] });
5
6
  const textError = (t) => ({ content: [{ type: "text", text: t }], isError: true });
6
7
  const READ_ONLY = { readOnlyHint: true, openWorldHint: true };
@@ -20,5 +21,54 @@ export function createServer() {
20
21
  return textError(error(e));
21
22
  }
22
23
  });
24
+ server.registerTool("forecast_summary", {
25
+ title: "Forecast summary",
26
+ description: "What the whole 7Timer 3-hourly series adds up to: when the coldest and warmest periods land and by how much, how much precipitation the series carries, mean and peak wind, mean and thickest cloud, and the lifted index.",
27
+ inputSchema: z.object({ lat: z.number().describe("Latitude."), lon: z.number().describe("Longitude.") }),
28
+ annotations: READ_ONLY,
29
+ }, async (args) => {
30
+ // ---- paywall: forecast_summary ----
31
+ const paywallMessage = await premiumRequired("forecast_summary");
32
+ if (paywallMessage)
33
+ return { content: [{ type: "text", text: paywallMessage }], isError: true };
34
+ // ---- paywall: end ----
35
+ try {
36
+ return text(await forecastSummary(args));
37
+ }
38
+ catch (e) {
39
+ return textError(error(e));
40
+ }
41
+ });
42
+ server.registerTool("daily_outlook", {
43
+ title: "Daily outlook",
44
+ description: "The 7Timer daily product: one row per day with that day's condition, its low and high, the size of its temperature range and its peak wind, plus the period's overall extremes.",
45
+ inputSchema: z.object({ lat: z.number().describe("Latitude."), lon: z.number().describe("Longitude."), limit: z.number().describe("Days to show, 1-7.").optional() }),
46
+ annotations: READ_ONLY,
47
+ }, async (args) => {
48
+ // ---- paywall: daily_outlook ----
49
+ const paywallMessage = await premiumRequired("daily_outlook");
50
+ if (paywallMessage)
51
+ return { content: [{ type: "text", text: paywallMessage }], isError: true };
52
+ // ---- paywall: end ----
53
+ try {
54
+ return text(await dailyOutlook(args));
55
+ }
56
+ catch (e) {
57
+ return textError(error(e));
58
+ }
59
+ });
60
+ server.registerTool("forecast_by_place", {
61
+ title: "Forecast by place name",
62
+ description: "Look a place up by name with OpenStreetMap Nominatim, show the candidate matches with their coordinates, then give the 7Timer civil series for the first match.",
63
+ inputSchema: z.object({ place: z.string().describe("Place name, e.g. Reykjavik or Wellington."), limit: z.number().describe("Candidate places to list, 1-5.").optional() }),
64
+ annotations: READ_ONLY,
65
+ }, async (args) => {
66
+ try {
67
+ return text(await forecastByPlace(args));
68
+ }
69
+ catch (e) {
70
+ return textError(error(e));
71
+ }
72
+ });
23
73
  return server;
24
74
  }
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.0",
2
+ "version": "1.0.1",
3
3
  "type": "module",
4
4
  "repository": {
5
5
  "type": "git",