wikimedia-commons-mcp 1.0.1 → 1.0.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.
package/README.md CHANGED
@@ -25,18 +25,18 @@ Public free APIs only. See `src/api.ts` for exact endpoints.
25
25
  <!-- paywall -->
26
26
  ## Premium tools
27
27
 
28
- These tools need a license key:
28
+ These tools need a licence key:
29
29
 
30
30
  * `file_categories`
31
31
  * `file_thumbnail`
32
32
 
33
- Buy a key at https://mcp-marketplace.io/server/io-github-mrfentmen-wikimedia-commons-mcp and set it in your MCP client config:
33
+ The tool bodies run on our gateway, not inside this package, so the key is what buys access. Buy one at https://buy.polar.sh/polar_cl_mrO7rS5LZxpqM7oAFFEA10i9121J240U40IIj4JRZO4 and set it in your MCP client config:
34
34
 
35
35
  ```json
36
- "env": { "MCP_LICENSE_KEY": "mcp_live_..." }
36
+ "env": { "MCP_LICENSE_KEY": "polar_..." }
37
37
  ```
38
38
 
39
- The key is checked against MCP Marketplace, cached for 24 hours, and keeps
40
- working offline once one check has succeeded. Every other tool on this server
39
+ The gateway checks the key against Polar and gives every key 1,000 free premium
40
+ calls a month before per-call billing starts. Every other tool on this server
41
41
  stays free.
42
42
  <!-- /paywall -->
package/dist/api.js CHANGED
@@ -116,42 +116,6 @@ async function commonsGet(url) {
116
116
  throw new CommonsLookupError(`Wikimedia Commons returned HTTP ${res.status}`);
117
117
  return res.json();
118
118
  }
119
- function commonsTitle(args) {
120
- const title = (args.title ?? "").trim();
121
- if (!title)
122
- throw new CommonsLookupError("Provide a file title like File:Example.jpg");
123
- return title.startsWith("File:") ? title : `File:${title}`;
124
- }
125
- /** The categories a file sits in, which is how Commons files are browsed. */
126
- export async function fileCategories(args) {
127
- const title = commonsTitle(args);
128
- const limit = Math.max(1, Math.min(args.limit ?? 15, 50));
129
- const d = await commonsGet(`${COMMONS_BASE}?action=query&titles=${encodeURIComponent(title)}&prop=categories&cllimit=${limit}&format=json&origin=*`);
130
- const pages = Object.values(d?.query?.pages ?? {});
131
- const page = pages[0];
132
- if (!page || page.missing !== undefined)
133
- throw new CommonsLookupError(`File not found: ${title}`);
134
- const cats = page.categories ?? [];
135
- if (!cats.length)
136
- return `${page.title} is in no categories.`;
137
- return `Categories for ${page.title} (${cats.length}${cats.length >= limit ? "+, capped by limit" : ""}):\n` +
138
- cats.map((c, i) => `${i + 1}. ${c.title}${c.hidden === true ? " (hidden)" : ""}`).join("\n");
139
- }
140
- /** A thumbnail URL at a chosen width, so a client can fetch a sized copy. */
141
- export async function fileThumbnail(args) {
142
- const title = commonsTitle(args);
143
- const width = Math.max(20, Math.min(args.width ?? 320, 2000));
144
- const d = await commonsGet(`${COMMONS_BASE}?action=query&titles=${encodeURIComponent(title)}&prop=imageinfo&iiprop=url|size|mime&iiurlwidth=${width}&format=json&origin=*`);
145
- const pages = Object.values(d?.query?.pages ?? {});
146
- const info = pages[0]?.imageinfo?.[0];
147
- if (!info)
148
- throw new CommonsLookupError(`No image info for ${title}`);
149
- return [
150
- `File: ${pages[0]?.title ?? title}`,
151
- `Original: ${info.url ?? "not reported"} (${info.width ?? "?"}x${info.height ?? "?"}, ${info.mime ?? "?"})`,
152
- `Thumbnail at ${width}px: ${info.thumburl ?? "not offered by Commons for this file"}`,
153
- ].join("\n");
154
- }
155
119
  /** Browse a Commons category and list the media files inside it. */
156
120
  export async function categoryFiles(args) {
157
121
  const raw = (args.category ?? "").trim();
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Thin client for the premium gateway.
3
+ *
4
+ * The premium tools do not run in this package any more. Their bodies live on
5
+ * the gateway, which checks a Polar licence key before it does any work, so
6
+ * deleting anything here buys nothing: the answer only exists behind the gate.
7
+ *
8
+ * Set `MCP_LICENSE_KEY` to a Polar licence key. `MCP_GATEWAY_URL` overrides the
9
+ * endpoint, which is only useful for testing.
10
+ */
11
+ const DEFAULT_GATEWAY_URL = 'https://mcp-gateway.contactae2000.workers.dev/mcp';
12
+ const DEFAULT_TIMEOUT_MS = 25000;
13
+ const USER_AGENT = 'mrfentmen-mcp/1.0';
14
+ /** Raised when a premium call cannot be completed. `message` is safe to show. */
15
+ export class GatewayError extends Error {
16
+ refused;
17
+ constructor(message, refused) {
18
+ super(message);
19
+ this.refused = refused;
20
+ this.name = 'GatewayError';
21
+ }
22
+ }
23
+ export async function premiumTool(tool, args) {
24
+ const key = (process.env.MCP_LICENSE_KEY ?? '').trim();
25
+ if (!key) {
26
+ throw new GatewayError(`"${tool}" is a premium tool and no licence key is set. Set MCP_LICENSE_KEY in your MCP client config.`, true);
27
+ }
28
+ const url = (process.env.MCP_GATEWAY_URL ?? DEFAULT_GATEWAY_URL).trim();
29
+ const controller = new AbortController();
30
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS);
31
+ let response;
32
+ try {
33
+ response = await fetch(url, {
34
+ method: 'POST',
35
+ headers: {
36
+ 'content-type': 'application/json',
37
+ accept: 'application/json',
38
+ 'user-agent': USER_AGENT,
39
+ authorization: `Bearer ${key}`,
40
+ },
41
+ body: JSON.stringify({
42
+ jsonrpc: '2.0',
43
+ id: 1,
44
+ method: 'tools/call',
45
+ params: { name: tool, arguments: args },
46
+ }),
47
+ signal: controller.signal,
48
+ });
49
+ }
50
+ catch {
51
+ throw new GatewayError(`"${tool}" could not reach the licence gateway. Check your connection and try again.`, false);
52
+ }
53
+ finally {
54
+ clearTimeout(timer);
55
+ }
56
+ if (!response.ok) {
57
+ throw new GatewayError(`"${tool}" could not reach the licence gateway (HTTP ${response.status}).`, false);
58
+ }
59
+ let body;
60
+ try {
61
+ body = (await response.json());
62
+ }
63
+ catch {
64
+ throw new GatewayError(`"${tool}" got an unreadable answer from the licence gateway.`, false);
65
+ }
66
+ if (body.error) {
67
+ throw new GatewayError(`"${tool}" was refused by the licence gateway: ${body.error.message ?? 'unknown error'}`, false);
68
+ }
69
+ const result = body.result ?? {};
70
+ const text = (result.content ?? [])
71
+ .map((part) => part.text ?? '')
72
+ .join('\n')
73
+ .trim();
74
+ if (result.isError) {
75
+ // The gateway marks a licence refusal structurally, so a missing or rejected
76
+ // key is told apart from a tool that failed after the gate let it through.
77
+ if (result.structuredContent?.licenceRefusal) {
78
+ throw new GatewayError(text || `"${tool}" needs a valid licence key.`, true);
79
+ }
80
+ throw new GatewayError(text || `"${tool}" failed on the licence gateway.`, false);
81
+ }
82
+ if (!text)
83
+ throw new GatewayError(`"${tool}" returned no data.`, false);
84
+ return text;
85
+ }
package/dist/server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { z } from 'zod';
3
- import { m0_file, m0_search, m1_random, fileCategories, fileThumbnail, categoryFiles } from './api.js';
4
- import { premiumRequired } from "./license.js";
3
+ import { m0_file, m0_search, m1_random, categoryFiles } from "./api.js";
4
+ import { premiumTool } from "./gateway.js";
5
5
  const text = (value) => ({ content: [{ type: 'text', text: value }] });
6
6
  const textError = (t) => ({ content: [{ type: "text", text: t }], isError: true });
7
7
  const READ_ONLY = { readOnlyHint: true, openWorldHint: true };
@@ -55,12 +55,10 @@ export function createServer() {
55
55
  annotations: READ_ONLY,
56
56
  }, async (args) => {
57
57
  // ---- paywall: file_categories ----
58
- const paywallMessage = await premiumRequired("file_categories");
59
- if (paywallMessage)
60
- return { content: [{ type: "text", text: paywallMessage }], isError: true };
58
+ // The body runs on the gateway, behind the licence gate.
61
59
  // ---- paywall: end ----
62
60
  try {
63
- return text(await fileCategories(args));
61
+ return text(await premiumTool("mcp_wikimedia_commons_file_categories", args));
64
62
  }
65
63
  catch (e) {
66
64
  return textError(error(e));
@@ -73,12 +71,10 @@ export function createServer() {
73
71
  annotations: READ_ONLY,
74
72
  }, async (args) => {
75
73
  // ---- paywall: file_thumbnail ----
76
- const paywallMessage = await premiumRequired("file_thumbnail");
77
- if (paywallMessage)
78
- return { content: [{ type: "text", text: paywallMessage }], isError: true };
74
+ // The body runs on the gateway, behind the licence gate.
79
75
  // ---- paywall: end ----
80
76
  try {
81
- return text(await fileThumbnail(args));
77
+ return text(await premiumTool("mcp_wikimedia_commons_file_thumbnail", args));
82
78
  }
83
79
  catch (e) {
84
80
  return textError(error(e));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wikimedia-commons-mcp",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Wikimedia Commons file search.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/src/api.ts CHANGED
@@ -67,7 +67,6 @@ return { CommonsError, file, search };
67
67
  const m1 = (() => {
68
68
  const BASE = 'https://commons.wikimedia.org/w/api.php';
69
69
 
70
-
71
70
  async function random(args: m1_RandomArgs): Promise<string> {
72
71
  const limit = Math.max(1, Math.min(args.limit ?? 5, 15));
73
72
  const params = new URLSearchParams({
@@ -128,45 +127,6 @@ async function commonsGet(url: string): Promise<any> {
128
127
  return res.json()
129
128
  }
130
129
 
131
- function commonsTitle(args: { title?: string }): string {
132
- const title = (args.title ?? "").trim()
133
- if (!title) throw new CommonsLookupError("Provide a file title like File:Example.jpg")
134
- return title.startsWith("File:") ? title : `File:${title}`
135
- }
136
-
137
- /** The categories a file sits in, which is how Commons files are browsed. */
138
- export async function fileCategories(args: { title?: string; limit?: number }): Promise<string> {
139
- const title = commonsTitle(args)
140
- const limit = Math.max(1, Math.min(args.limit ?? 15, 50))
141
- const d = await commonsGet(
142
- `${COMMONS_BASE}?action=query&titles=${encodeURIComponent(title)}&prop=categories&cllimit=${limit}&format=json&origin=*`,
143
- )
144
- const pages = Object.values(d?.query?.pages ?? {}) as any[]
145
- const page = pages[0]
146
- if (!page || page.missing !== undefined) throw new CommonsLookupError(`File not found: ${title}`)
147
- const cats = page.categories ?? []
148
- if (!cats.length) return `${page.title} is in no categories.`
149
- return `Categories for ${page.title} (${cats.length}${cats.length >= limit ? "+, capped by limit" : ""}):\n` +
150
- cats.map((c: any, i: number) => `${i + 1}. ${c.title}${c.hidden === true ? " (hidden)" : ""}`).join("\n")
151
- }
152
-
153
- /** A thumbnail URL at a chosen width, so a client can fetch a sized copy. */
154
- export async function fileThumbnail(args: { title?: string; width?: number }): Promise<string> {
155
- const title = commonsTitle(args)
156
- const width = Math.max(20, Math.min(args.width ?? 320, 2000))
157
- const d = await commonsGet(
158
- `${COMMONS_BASE}?action=query&titles=${encodeURIComponent(title)}&prop=imageinfo&iiprop=url|size|mime&iiurlwidth=${width}&format=json&origin=*`,
159
- )
160
- const pages = Object.values(d?.query?.pages ?? {}) as any[]
161
- const info = pages[0]?.imageinfo?.[0]
162
- if (!info) throw new CommonsLookupError(`No image info for ${title}`)
163
- return [
164
- `File: ${pages[0]?.title ?? title}`,
165
- `Original: ${info.url ?? "not reported"} (${info.width ?? "?"}x${info.height ?? "?"}, ${info.mime ?? "?"})`,
166
- `Thumbnail at ${width}px: ${info.thumburl ?? "not offered by Commons for this file"}`,
167
- ].join("\n")
168
- }
169
-
170
130
  /** Browse a Commons category and list the media files inside it. */
171
131
  export async function categoryFiles(args: { category?: string; limit?: number }): Promise<string> {
172
132
  const raw = (args.category ?? "").trim()
package/src/gateway.ts ADDED
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Thin client for the premium gateway.
3
+ *
4
+ * The premium tools do not run in this package any more. Their bodies live on
5
+ * the gateway, which checks a Polar licence key before it does any work, so
6
+ * deleting anything here buys nothing: the answer only exists behind the gate.
7
+ *
8
+ * Set `MCP_LICENSE_KEY` to a Polar licence key. `MCP_GATEWAY_URL` overrides the
9
+ * endpoint, which is only useful for testing.
10
+ */
11
+
12
+ const DEFAULT_GATEWAY_URL = 'https://mcp-gateway.contactae2000.workers.dev/mcp'
13
+ const DEFAULT_TIMEOUT_MS = 25000
14
+ const USER_AGENT = 'mrfentmen-mcp/1.0'
15
+
16
+ /** Raised when a premium call cannot be completed. `message` is safe to show. */
17
+ export class GatewayError extends Error {
18
+ constructor(message: string, readonly refused: boolean) {
19
+ super(message)
20
+ this.name = 'GatewayError'
21
+ }
22
+ }
23
+
24
+ interface ContentPart {
25
+ text?: string
26
+ }
27
+
28
+ interface CallResult {
29
+ content?: ContentPart[]
30
+ isError?: boolean
31
+ structuredContent?: { licenceRefusal?: boolean }
32
+ }
33
+
34
+ interface JsonRpcResponse {
35
+ result?: CallResult
36
+ error?: { message?: string }
37
+ }
38
+
39
+ export async function premiumTool(tool: string, args: Record<string, unknown>): Promise<string> {
40
+ const key = (process.env.MCP_LICENSE_KEY ?? '').trim()
41
+ if (!key) {
42
+ throw new GatewayError(
43
+ `"${tool}" is a premium tool and no licence key is set. Set MCP_LICENSE_KEY in your MCP client config.`,
44
+ true,
45
+ )
46
+ }
47
+
48
+ const url = (process.env.MCP_GATEWAY_URL ?? DEFAULT_GATEWAY_URL).trim()
49
+ const controller = new AbortController()
50
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT_MS)
51
+ let response: Response
52
+ try {
53
+ response = await fetch(url, {
54
+ method: 'POST',
55
+ headers: {
56
+ 'content-type': 'application/json',
57
+ accept: 'application/json',
58
+ 'user-agent': USER_AGENT,
59
+ authorization: `Bearer ${key}`,
60
+ },
61
+ body: JSON.stringify({
62
+ jsonrpc: '2.0',
63
+ id: 1,
64
+ method: 'tools/call',
65
+ params: { name: tool, arguments: args },
66
+ }),
67
+ signal: controller.signal,
68
+ })
69
+ } catch {
70
+ throw new GatewayError(`"${tool}" could not reach the licence gateway. Check your connection and try again.`, false)
71
+ } finally {
72
+ clearTimeout(timer)
73
+ }
74
+
75
+ if (!response.ok) {
76
+ throw new GatewayError(`"${tool}" could not reach the licence gateway (HTTP ${response.status}).`, false)
77
+ }
78
+
79
+ let body: JsonRpcResponse
80
+ try {
81
+ body = (await response.json()) as JsonRpcResponse
82
+ } catch {
83
+ throw new GatewayError(`"${tool}" got an unreadable answer from the licence gateway.`, false)
84
+ }
85
+
86
+ if (body.error) {
87
+ throw new GatewayError(`"${tool}" was refused by the licence gateway: ${body.error.message ?? 'unknown error'}`, false)
88
+ }
89
+
90
+ const result = body.result ?? {}
91
+ const text = (result.content ?? [])
92
+ .map((part) => part.text ?? '')
93
+ .join('\n')
94
+ .trim()
95
+
96
+ if (result.isError) {
97
+ // The gateway marks a licence refusal structurally, so a missing or rejected
98
+ // key is told apart from a tool that failed after the gate let it through.
99
+ if (result.structuredContent?.licenceRefusal) {
100
+ throw new GatewayError(text || `"${tool}" needs a valid licence key.`, true)
101
+ }
102
+ throw new GatewayError(text || `"${tool}" failed on the licence gateway.`, false)
103
+ }
104
+ if (!text) throw new GatewayError(`"${tool}" returned no data.`, false)
105
+ return text
106
+ }
package/src/server.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
2
2
  import { z } from 'zod'
3
- import { m0_file, m0_search, m1_random, fileCategories, fileThumbnail, categoryFiles } from './api.js'
4
- import { premiumRequired } from "./license.js"
5
3
 
4
+ import { m0_file, m0_search, m1_random, categoryFiles } from "./api.js"
5
+ import { premiumTool } from "./gateway.js"
6
6
  const text = (value: string) => ({ content: [{ type: 'text' as const, text: value }] })
7
7
  const textError = (t: string) => ({ content: [{ type: "text" as const, text: t }], isError: true as const })
8
8
  const READ_ONLY = { readOnlyHint: true, openWorldHint: true } as const
@@ -57,10 +57,9 @@ server.registerTool(
57
57
  },
58
58
  async (args) => {
59
59
  // ---- paywall: file_categories ----
60
- const paywallMessage = await premiumRequired("file_categories")
61
- if (paywallMessage) return { content: [{ type: "text" as const, text: paywallMessage }], isError: true }
60
+ // The body runs on the gateway, behind the licence gate.
62
61
  // ---- paywall: end ----
63
- try { return text(await fileCategories(args)) } catch (e) { return textError(error(e)) }
62
+ try { return text(await premiumTool("mcp_wikimedia_commons_file_categories", args)) } catch (e) { return textError(error(e)) }
64
63
  }
65
64
  )
66
65
 
@@ -74,10 +73,9 @@ server.registerTool(
74
73
  },
75
74
  async (args) => {
76
75
  // ---- paywall: file_thumbnail ----
77
- const paywallMessage = await premiumRequired("file_thumbnail")
78
- if (paywallMessage) return { content: [{ type: "text" as const, text: paywallMessage }], isError: true }
76
+ // The body runs on the gateway, behind the licence gate.
79
77
  // ---- paywall: end ----
80
- try { return text(await fileThumbnail(args)) } catch (e) { return textError(error(e)) }
78
+ try { return text(await premiumTool("mcp_wikimedia_commons_file_thumbnail", args)) } catch (e) { return textError(error(e)) }
81
79
  }
82
80
  )
83
81
 
package/dist/license.js DELETED
@@ -1,79 +0,0 @@
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 = "wikimedia-commons-mcp";
5
- // Tools that need a key. Everything else is free.
6
- const PREMIUM = new Set([
7
- "file_categories",
8
- "file_thumbnail",
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/src/license.ts DELETED
@@ -1,89 +0,0 @@
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 = "wikimedia-commons-mcp"
5
-
6
- // Tools that need a key. Everything else is free.
7
- const PREMIUM = new Set<string>([
8
- "file_categories",
9
- "file_thumbnail",
10
- ])
11
-
12
- const BUY_URL = `https://mcp-marketplace.io/server/io-github-mrfentmen-${SLUG}`
13
-
14
- // The license check calls the marketplace's verify endpoint directly instead of
15
- // using @mcp_marketplace/license. That SDK sends no `apikey` header, so every
16
- // check it makes is rejected by Supabase before it reaches the function. The
17
- // publishable key below is public by design - it ships in mcp-marketplace.io's
18
- // own JavaScript and only ever reaches their licence check.
19
- const DEFAULT_VERIFY_URL = "https://virupvwhtkpkjsiskckg.supabase.co/functions/v1/verify-key"
20
- const PUBLISHABLE_KEY = "sb_publishable_BuqlW96Ke8C_zzJG-LQv1Q_YHi_r_4h"
21
-
22
- const OK_CACHE_MS = 60 * 60 * 1000
23
- const BAD_CACHE_MS = 60 * 1000
24
-
25
- type Check = { valid: boolean; reason?: string }
26
-
27
- const seen = new Map<string, Check & { at: number }>()
28
-
29
- const REASONS: Record<string, string> = {
30
- missing_key: "no key is set",
31
- invalid_format: "that key is not a valid MCP Marketplace key",
32
- not_found: "that key was not found",
33
- revoked: "that key has been revoked",
34
- rotated: "that key was rotated, use your new one",
35
- expired: "that key has expired, renew it",
36
- rate_limited: "there were too many checks just now, try again shortly",
37
- network_error: "the license server could not be reached",
38
- }
39
-
40
- function blocked(tool: string, reason: string): string {
41
- const why = REASONS[reason] ?? `the license server answered "${reason}"`
42
- return `"${tool}" needs a license key, but ${why}. ` +
43
- `Set MCP_LICENSE_KEY in your MCP client config. Get a key: ${BUY_URL}`
44
- }
45
-
46
- async function verify(key: string): Promise<Check> {
47
- const res = await fetch(process.env.MCP_LICENSE_VERIFY_URL || DEFAULT_VERIFY_URL, {
48
- method: "POST",
49
- headers: {
50
- apikey: PUBLISHABLE_KEY,
51
- Authorization: `Bearer ${PUBLISHABLE_KEY}`,
52
- "Content-Type": "application/json",
53
- },
54
- body: JSON.stringify({ key, slug: SLUG }),
55
- // an unusable key answers 400 with a JSON body, so read the body either way
56
- signal: AbortSignal.timeout(15000),
57
- })
58
- const data = (await res.json()) as Check
59
- if (typeof data?.valid !== "boolean") return { valid: false, reason: "unexpected_response" }
60
- return data
61
- }
62
-
63
- /**
64
- * Returns null when the caller may run the tool, or a short message telling
65
- * them how to get a key.
66
- *
67
- * A good key is remembered for an hour, so a busy session does not hit the
68
- * license server on every call and keeps working through a brief outage.
69
- */
70
- export async function premiumRequired(tool: string): Promise<string | null> {
71
- if (!PREMIUM.has(tool)) return null
72
-
73
- const key = process.env.MCP_LICENSE_KEY
74
- if (!key) return blocked(tool, "missing_key")
75
-
76
- const hit = seen.get(key)
77
- if (hit && Date.now() - hit.at < (hit.valid ? OK_CACHE_MS : BAD_CACHE_MS)) {
78
- return hit.valid ? null : blocked(tool, hit.reason ?? "invalid")
79
- }
80
-
81
- let result: Check
82
- try {
83
- result = await verify(key)
84
- } catch {
85
- result = { valid: false, reason: "network_error" }
86
- }
87
- seen.set(key, { ...result, at: Date.now() })
88
- return result.valid ? null : blocked(tool, result.reason ?? "invalid")
89
- }