opedd-mcp 0.6.3 → 0.6.4

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 (2) hide show
  1. package/dist/index.js +546 -534
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,36 +5,33 @@ import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextpro
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { initTelemetry, captureToolCall, shutdownTelemetry } from "./telemetry.js";
7
7
  import { SERVER_VERSION } from "./version.js";
8
- // ─── Configuration ────────────────────────────────────────────────────────────
9
- const API_BASE = process.env.OPEDD_API_URL ??
10
- "https://api.opedd.com";
11
- const BUYER_EMAIL = process.env.OPEDD_BUYER_EMAIL;
12
- const PAYMENT_METHOD_ID = process.env.OPEDD_PAYMENT_METHOD_ID;
13
- // B91 v0.4.0 migration (2026-05-26): canonical Bearer auth.
14
- // OPEDD_PUB_BEARER is the new canonical opedd_pub_<env>_<32-hex> key
15
- // (issued via POST /publishers-api-keys action=create_api_key).
16
- // OPEDD_API_KEY retained as backward-compat alias for legacy op_ keys
17
- // during the dual-mode transition window on the /api endpoint (Phase A
18
- // shipped opedd-backend 2026-05-26). Backend Phase C will drop the
19
- // op_ path entirely; users MUST migrate to OPEDD_PUB_BEARER before
20
- // then. Prefer Bearer if both set.
21
- const PUB_BEARER = process.env.OPEDD_PUB_BEARER; // canonical opedd_pub_<env>_<32-hex>
22
- const API_KEY = process.env.OPEDD_API_KEY; // LEGACY op_<32-hex> — retiring per backend Phase C
23
- const BUYER_TOKEN = process.env.OPEDD_BUYER_TOKEN; // buyer API token (opedd_buyer_live_... or opedd_buyer_test_...)
24
- const ACCESS_KEY = process.env.OPEDD_ACCESS_KEY; // enterprise access key (ent_*); for /enterprise-license GET feed
25
- const BUYER_JWT = process.env.OPEDD_BUYER_JWT; // Supabase JWT; for /buyer-audit + /buyer-compliance-report
8
+ export function envCredentials() {
9
+ return {
10
+ apiBase: process.env.OPEDD_API_URL ?? "https://api.opedd.com",
11
+ buyerEmail: process.env.OPEDD_BUYER_EMAIL,
12
+ paymentMethodId: process.env.OPEDD_PAYMENT_METHOD_ID,
13
+ // B91 v0.4.0 (2026-05-26): OPEDD_PUB_BEARER canonical; OPEDD_API_KEY is
14
+ // the legacy op_ alias during the dual-mode transition window.
15
+ pubBearer: process.env.OPEDD_PUB_BEARER,
16
+ apiKey: process.env.OPEDD_API_KEY,
17
+ buyerToken: process.env.OPEDD_BUYER_TOKEN,
18
+ accessKey: process.env.OPEDD_ACCESS_KEY,
19
+ buyerJwt: process.env.OPEDD_BUYER_JWT,
20
+ };
21
+ }
22
+ const ENV_CREDS = envCredentials();
26
23
  // ─── HTTP helpers ─────────────────────────────────────────────────────────────
27
24
  // 30s cap (2026-07-10 hardening audit): without it a hung api.opedd.com
28
25
  // call hangs the agent's tool call indefinitely — an MCP server must fail
29
26
  // fast so the agent can recover.
30
27
  const FETCH_TIMEOUT_MS = 30_000;
31
- async function opeddFetch(path, options = {}) {
32
- const url = `${API_BASE}${path}`;
28
+ async function opeddFetch(creds, path, options = {}) {
29
+ const url = `${creds.apiBase}${path}`;
33
30
  const headers = {
34
31
  "Content-Type": "application/json",
35
32
  // B91 v0.4.0 (2026-05-26): canonical Bearer preferred; legacy X-API-Key
36
33
  // accepted only as fallback during transition window
37
- ...(PUB_BEARER ? { Authorization: `Bearer ${PUB_BEARER}` } : (API_KEY ? { "X-API-Key": API_KEY } : {})),
34
+ ...(creds.pubBearer ? { Authorization: `Bearer ${creds.pubBearer}` } : (creds.apiKey ? { "X-API-Key": creds.apiKey } : {})),
38
35
  ...(options.headers ?? {}),
39
36
  };
40
37
  const res = await fetch(url, { ...options, headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
@@ -56,12 +53,12 @@ async function opeddFetch(path, options = {}) {
56
53
  // Fetch an NDJSON endpoint and collect parsed lines into an array.
57
54
  // Last line is typically `{"_meta": {...}}`; surfaced as `meta` field on the
58
55
  // returned object so the MCP tool result has both shape pieces inline.
59
- async function opeddFetchNdjson(path, options = {}) {
60
- const url = `${API_BASE}${path}`;
56
+ async function opeddFetchNdjson(creds, path, options = {}) {
57
+ const url = `${creds.apiBase}${path}`;
61
58
  const headers = {
62
59
  Accept: "application/x-ndjson",
63
60
  // B91 v0.4.0 (2026-05-26): canonical Bearer preferred; legacy fallback
64
- ...(PUB_BEARER ? { Authorization: `Bearer ${PUB_BEARER}` } : (API_KEY ? { "X-API-Key": API_KEY } : {})),
61
+ ...(creds.pubBearer ? { Authorization: `Bearer ${creds.pubBearer}` } : (creds.apiKey ? { "X-API-Key": creds.apiKey } : {})),
65
62
  ...(options.headers ?? {}),
66
63
  };
67
64
  const res = await fetch(url, { ...options, headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
@@ -100,525 +97,540 @@ function err(msg) {
100
97
  return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
101
98
  }
102
99
  // ─── Tool definitions ─────────────────────────────────────────────────────────
103
- export const TOOLS = [
104
- {
105
- name: "lookup_content",
106
- description: "Look up a piece of content on the Opedd registry by URL. " +
107
- "Returns the article title, publisher, available license types, and pricing " +
108
- "(human republication price and AI training/inference price). " +
109
- "Always call this first to check if content is licensable and what it costs.",
110
- inputSchema: {
111
- type: "object",
112
- required: ["url"],
113
- properties: {
114
- url: {
115
- type: "string",
116
- description: "The canonical URL of the article or content to look up",
100
+ function buildTools(has) {
101
+ const TOOLS = [
102
+ {
103
+ name: "lookup_content",
104
+ description: "Look up a piece of content on the Opedd registry by URL. " +
105
+ "Returns the article title, publisher, available license types, and pricing " +
106
+ "(human republication price and AI training/inference price). " +
107
+ "Always call this first to check if content is licensable and what it costs.",
108
+ inputSchema: {
109
+ type: "object",
110
+ required: ["url"],
111
+ properties: {
112
+ url: {
113
+ type: "string",
114
+ description: "The canonical URL of the article or content to look up",
115
+ },
117
116
  },
118
117
  },
119
118
  },
120
- },
121
- {
122
- name: "purchase_license",
123
- description: "Purchase a content license from the Opedd protocol using a Stripe payment method. " +
124
- "Returns a license key (format: OP-XXXX-XXXX) and a certificate URL. " +
125
- "The buyer receives a Handshake Email with their license key. " +
126
- "Set OPEDD_BUYER_EMAIL and OPEDD_PAYMENT_METHOD_ID env vars to avoid passing them on every call. " +
127
- "License types: 'human' = republication rights, 'ai' = training dataset rights, 'ai_inference' = inference/RAG rights.",
128
- inputSchema: {
129
- type: "object",
130
- required: ["license_type"],
131
- properties: {
132
- article_url: {
133
- type: "string",
134
- description: "URL of the article to license (use this OR article_id)",
135
- },
136
- article_id: {
137
- type: "string",
138
- description: "Opedd article UUID (use this OR article_url)",
139
- },
140
- license_type: {
141
- type: "string",
142
- enum: ["human", "ai", "ai_inference"],
143
- description: "human = republication/editorial rights, ai = training dataset rights, ai_inference = inference/RAG rights",
144
- },
145
- buyer_email: {
146
- type: "string",
147
- description: "Email address for the license. Falls back to OPEDD_BUYER_EMAIL env var.",
148
- },
149
- buyer_name: {
150
- type: "string",
151
- description: "Full name of the buyer (for the license record and certificate)",
152
- },
153
- buyer_organization: {
154
- type: "string",
155
- description: "Organization or company name (for enterprise/editorial licenses)",
156
- },
157
- intended_use: {
158
- type: "string",
159
- enum: ["personal", "editorial", "commercial", "ai_training", "corporate"],
160
- description: "Intended use of the licensed content",
161
- },
162
- payment_method_id: {
163
- type: "string",
164
- description: "Stripe payment method ID (pm_...). Falls back to OPEDD_PAYMENT_METHOD_ID env var.",
119
+ {
120
+ name: "purchase_license",
121
+ description: "Purchase a content license from the Opedd protocol using a Stripe payment method. " +
122
+ "Returns a license key (format: OP-XXXX-XXXX) and a certificate URL. " +
123
+ "The buyer receives a Handshake Email with their license key. " +
124
+ "Set OPEDD_BUYER_EMAIL and OPEDD_PAYMENT_METHOD_ID env vars to avoid passing them on every call. " +
125
+ "License types: 'human' = republication rights, 'ai' = training dataset rights, 'ai_inference' = inference/RAG rights.",
126
+ inputSchema: {
127
+ type: "object",
128
+ required: ["license_type"],
129
+ properties: {
130
+ article_url: {
131
+ type: "string",
132
+ description: "URL of the article to license (use this OR article_id)",
133
+ },
134
+ article_id: {
135
+ type: "string",
136
+ description: "Opedd article UUID (use this OR article_url)",
137
+ },
138
+ license_type: {
139
+ type: "string",
140
+ enum: ["human", "ai", "ai_inference"],
141
+ description: "human = republication/editorial rights, ai = training dataset rights, ai_inference = inference/RAG rights",
142
+ },
143
+ buyer_email: {
144
+ type: "string",
145
+ description: "Email address for the license. Falls back to OPEDD_BUYER_EMAIL env var.",
146
+ },
147
+ buyer_name: {
148
+ type: "string",
149
+ description: "Full name of the buyer (for the license record and certificate)",
150
+ },
151
+ buyer_organization: {
152
+ type: "string",
153
+ description: "Organization or company name (for enterprise/editorial licenses)",
154
+ },
155
+ intended_use: {
156
+ type: "string",
157
+ enum: ["personal", "editorial", "commercial", "ai_training", "corporate"],
158
+ description: "Intended use of the licensed content",
159
+ },
160
+ payment_method_id: {
161
+ type: "string",
162
+ description: "Stripe payment method ID (pm_...). Falls back to OPEDD_PAYMENT_METHOD_ID env var.",
163
+ },
165
164
  },
166
165
  },
167
166
  },
168
- },
169
- {
170
- name: "verify_license",
171
- description: "Verify the authenticity of an Opedd license key. " +
172
- "Returns license details including: article title, publisher, license type, " +
173
- "issue date, amount paid, buyer info, and blockchain proof status. " +
174
- "Use this to confirm a license is valid before using licensed content.",
175
- inputSchema: {
176
- type: "object",
177
- required: ["license_key"],
178
- properties: {
179
- license_key: {
180
- type: "string",
181
- description: "The license key to verify (format: OP-XXXX-XXXX)",
167
+ {
168
+ name: "verify_license",
169
+ description: "Verify the authenticity of an Opedd license key. " +
170
+ "Returns license details including: article title, publisher, license type, " +
171
+ "issue date, amount paid, buyer info, and blockchain proof status. " +
172
+ "Use this to confirm a license is valid before using licensed content.",
173
+ inputSchema: {
174
+ type: "object",
175
+ required: ["license_key"],
176
+ properties: {
177
+ license_key: {
178
+ type: "string",
179
+ description: "The license key to verify (format: OP-XXXX-XXXX)",
180
+ },
182
181
  },
183
182
  },
184
183
  },
185
- },
186
- {
187
- name: "browse_registry",
188
- description: "Browse the public Opedd license registry. " +
189
- "Returns recently issued licenses and licensable content. " +
190
- "Filter by publisher_id to explore all content from a specific publisher. " +
191
- "Filter by article_id to see all licenses issued for a specific article.",
192
- inputSchema: {
193
- type: "object",
194
- properties: {
195
- publisher_id: {
196
- type: "string",
197
- description: "Filter results to a specific publisher (UUID)",
198
- },
199
- article_id: {
200
- type: "string",
201
- description: "Filter results to a specific article (UUID)",
202
- },
203
- limit: {
204
- type: "number",
205
- description: "Number of results to return (default: 10, max: 50)",
184
+ {
185
+ name: "browse_registry",
186
+ description: "Browse the public Opedd license registry. " +
187
+ "Returns recently issued licenses and licensable content. " +
188
+ "Filter by publisher_id to explore all content from a specific publisher. " +
189
+ "Filter by article_id to see all licenses issued for a specific article.",
190
+ inputSchema: {
191
+ type: "object",
192
+ properties: {
193
+ publisher_id: {
194
+ type: "string",
195
+ description: "Filter results to a specific publisher (UUID)",
196
+ },
197
+ article_id: {
198
+ type: "string",
199
+ description: "Filter results to a specific article (UUID)",
200
+ },
201
+ limit: {
202
+ type: "number",
203
+ description: "Number of results to return (default: 10, max: 50)",
204
+ },
206
205
  },
207
206
  },
208
207
  },
209
- },
210
- // ─── Public buyer-discovery — catalog browse ──────────────────────────────
211
- {
212
- name: "publisher_directory",
213
- description: "Browse the public Opedd publisher catalog via GET /publisher-directory. " +
214
- "Returns paginated publishers with article counts, pricing (per-article + annual + monthly-forward-feed), " +
215
- "plan, and sample articles (RAG-extended metadata). " +
216
- "**The primary discovery surface for AI labs to find Opedd-licensable publishers** — distinct from " +
217
- "`browse_registry` (which lists issued LICENSES, not publishers). " +
218
- "Filter by category (case-insensitive substring), min_articles, or verified status. " +
219
- "Public no-auth — useful pre-purchase scoping before buyers commit to enterprise-license POST.",
220
- inputSchema: {
221
- type: "object",
222
- properties: {
223
- category: {
224
- type: "string",
225
- description: "Case-insensitive substring filter on publisher category (e.g. 'finance', 'AI').",
226
- },
227
- min_articles: {
228
- type: "number",
229
- description: "Filter to publishers with at least this many licensable articles.",
230
- },
231
- verified: {
232
- type: "string",
233
- description: "'true' to show only verified publishers (default), 'false' for unverified.",
234
- },
235
- limit: {
236
- type: "number",
237
- description: "Page size cap.",
238
- },
239
- offset: {
240
- type: "number",
241
- description: "Pagination offset.",
208
+ // ─── Public buyer-discovery — catalog browse ──────────────────────────────
209
+ {
210
+ name: "publisher_directory",
211
+ description: "Browse the public Opedd publisher catalog via GET /publisher-directory. " +
212
+ "Returns paginated publishers with article counts, pricing (per-article + annual + monthly-forward-feed), " +
213
+ "plan, and sample articles (RAG-extended metadata). " +
214
+ "**The primary discovery surface for AI labs to find Opedd-licensable publishers** — distinct from " +
215
+ "`browse_registry` (which lists issued LICENSES, not publishers). " +
216
+ "Filter by category (case-insensitive substring), min_articles, or verified status. " +
217
+ "Public no-auth — useful pre-purchase scoping before buyers commit to enterprise-license POST.",
218
+ inputSchema: {
219
+ type: "object",
220
+ properties: {
221
+ category: {
222
+ type: "string",
223
+ description: "Case-insensitive substring filter on publisher category (e.g. 'finance', 'AI').",
224
+ },
225
+ min_articles: {
226
+ type: "number",
227
+ description: "Filter to publishers with at least this many licensable articles.",
228
+ },
229
+ verified: {
230
+ type: "string",
231
+ description: "'true' to show only verified publishers (default), 'false' for unverified.",
232
+ },
233
+ limit: {
234
+ type: "number",
235
+ description: "Page size cap.",
236
+ },
237
+ offset: {
238
+ type: "number",
239
+ description: "Pagination offset.",
240
+ },
242
241
  },
243
242
  },
244
243
  },
245
- },
246
- // ─── Phase 12 Wave 3 W3.1 — onboarding helpers ────────────────────────────
247
- {
248
- name: "detect_platform",
249
- description: "Detect the content platform behind a URL via POST /detect-platform (Phase 12 Wave 3 W3.1). " +
250
- "Public no-auth lookup. Given a URL, identifies what platform powers it " +
251
- "(Substack / Beehiiv / Ghost / Medium / Brevo / custom) and returns the suggested onboarding workflow. " +
252
- "Hostname-detectable platforms (Substack subdomain, Beehiiv suffix, etc.) resolve in milliseconds; " +
253
- "custom domains may take ~few seconds while the detector probes well-known platform endpoints in parallel. " +
254
- "Returns: {platform, confidence, archive_method, forward_method, required_credentials, instructions}. " +
255
- "The archive_method + forward_method fields are the two onboarding-workflow inputs Opedd's setup wizard reads " +
256
- "(one for historical content backfill, one for new-content forward stream). " +
257
- "instructions is human-readable operator copy explaining the inferred path.",
258
- inputSchema: {
259
- type: "object",
260
- required: ["url"],
261
- properties: {
262
- url: {
263
- type: "string",
264
- description: "Publisher URL to inspect (any well-formed URL works; hostname-match short-circuits the probe path).",
244
+ // ─── Phase 12 Wave 3 W3.1 — onboarding helpers ────────────────────────────
245
+ {
246
+ name: "detect_platform",
247
+ description: "Detect the content platform behind a URL via POST /detect-platform (Phase 12 Wave 3 W3.1). " +
248
+ "Public no-auth lookup. Given a URL, identifies what platform powers it " +
249
+ "(Substack / Beehiiv / Ghost / Medium / Brevo / custom) and returns the suggested onboarding workflow. " +
250
+ "Hostname-detectable platforms (Substack subdomain, Beehiiv suffix, etc.) resolve in milliseconds; " +
251
+ "custom domains may take ~few seconds while the detector probes well-known platform endpoints in parallel. " +
252
+ "Returns: {platform, confidence, archive_method, forward_method, required_credentials, instructions}. " +
253
+ "The archive_method + forward_method fields are the two onboarding-workflow inputs Opedd's setup wizard reads " +
254
+ "(one for historical content backfill, one for new-content forward stream). " +
255
+ "instructions is human-readable operator copy explaining the inferred path.",
256
+ inputSchema: {
257
+ type: "object",
258
+ required: ["url"],
259
+ properties: {
260
+ url: {
261
+ type: "string",
262
+ description: "Publisher URL to inspect (any well-formed URL works; hostname-match short-circuits the probe path).",
263
+ },
265
264
  },
266
265
  },
267
266
  },
268
- },
269
- // ─── Phase 12 Wave 1 W1.1 — public RSL Standard manifest ─────────────────
270
- {
271
- name: "rsl_get",
272
- description: "Fetch a publisher's RSL Standard manifest via GET /rsl-manifest (Phase 12 Wave 1 W1.1). " +
273
- "Public no-auth endpoint — discovery surface for AI agents/crawlers wanting to know what's licensable " +
274
- "from a publisher BEFORE going through the buyer-account signup flow. " +
275
- "Returns the 4 canonical license types (ai_retrieval, ai_training, human_per_article, human_full_archive) " +
276
- "the publisher has opted into, plus the EU CDSM Article 4(3) opt-out posture (`tdm_reservation`). " +
277
- "Set `jsonld: true` to request the JSON-LD shape with embedded HMAC-SHA256 signed receipt over the " +
278
- "CDSM Article 4(3) reservation state + `tdm:reservationSignedAt` timestamp — regulators can post-hoc " +
279
- "verify the reservation was the claimed value at the claimed time. Default `jsonld: false` returns " +
280
- "the raw RSL Standard JSON manifest. " +
281
- "Per INVARIANTS.md W1.6: this is the PUBLISHER-side CDSM Article 4(3) declaration surface. It is NOT " +
282
- "an EU AI Act Article 53 attestation (which is buyer-side, JWT-auth, via article_53_attestation tool).",
283
- inputSchema: {
284
- type: "object",
285
- required: ["publisher_id"],
286
- properties: {
287
- publisher_id: {
288
- type: "string",
289
- description: "UUID of the publisher whose RSL manifest to fetch. Publisher must be verified.",
290
- },
291
- jsonld: {
292
- type: "boolean",
293
- description: "If true, request JSON-LD shape (Accept: application/ld+json) with embedded HMAC-SHA256 signed receipt. " +
294
- "Default false returns raw RSL Standard JSON shape.",
267
+ // ─── Phase 12 Wave 1 W1.1 — public RSL Standard manifest ─────────────────
268
+ {
269
+ name: "rsl_get",
270
+ description: "Fetch a publisher's RSL Standard manifest via GET /rsl-manifest (Phase 12 Wave 1 W1.1). " +
271
+ "Public no-auth endpoint — discovery surface for AI agents/crawlers wanting to know what's licensable " +
272
+ "from a publisher BEFORE going through the buyer-account signup flow. " +
273
+ "Returns the 4 canonical license types (ai_retrieval, ai_training, human_per_article, human_full_archive) " +
274
+ "the publisher has opted into, plus the EU CDSM Article 4(3) opt-out posture (`tdm_reservation`). " +
275
+ "Set `jsonld: true` to request the JSON-LD shape with embedded HMAC-SHA256 signed receipt over the " +
276
+ "CDSM Article 4(3) reservation state + `tdm:reservationSignedAt` timestamp — regulators can post-hoc " +
277
+ "verify the reservation was the claimed value at the claimed time. Default `jsonld: false` returns " +
278
+ "the raw RSL Standard JSON manifest. " +
279
+ "Per INVARIANTS.md W1.6: this is the PUBLISHER-side CDSM Article 4(3) declaration surface. It is NOT " +
280
+ "an EU AI Act Article 53 attestation (which is buyer-side, JWT-auth, via article_53_attestation tool).",
281
+ inputSchema: {
282
+ type: "object",
283
+ required: ["publisher_id"],
284
+ properties: {
285
+ publisher_id: {
286
+ type: "string",
287
+ description: "UUID of the publisher whose RSL manifest to fetch. Publisher must be verified.",
288
+ },
289
+ jsonld: {
290
+ type: "boolean",
291
+ description: "If true, request JSON-LD shape (Accept: application/ld+json) with embedded HMAC-SHA256 signed receipt. " +
292
+ "Default false returns raw RSL Standard JSON shape.",
293
+ },
295
294
  },
296
295
  },
297
296
  },
298
- },
299
- // ─── Phase 10 + 11 buyer-side surfaces (M6.4) ─────────────────────────────
300
- {
301
- name: "purchase_enterprise_license",
302
- description: "Purchase a bulk enterprise license covering multiple publishers (Phase 10). " +
303
- "Returns a Stripe client_secret for payment completion + the enterprise_license_id. " +
304
- "After payment, an ent_* access key is emailed to buyer_email. " +
305
- "Scopes: 'custom' (pass-through publisher_ids), 'platform_wide' (auto-resolve all opted-in publishers), 'filtered' (Phase 10 filter_rules). " +
306
- "License tiers: 'rag' (= ai_retrieval), 'training' (= ai_training, flat-fee not metered), 'inference' (= ai_retrieval), 'full_ai' (writes both retrieval + training records).",
307
- inputSchema: {
308
- type: "object",
309
- required: ["publisher_ids", "buyer_email", "buyer_org"],
310
- properties: {
311
- publisher_ids: {
312
- type: "array",
313
- items: { type: "string" },
314
- description: "Array of publisher UUIDs. Required for scope='custom'; ignored for platform_wide/filtered (resolved server-side).",
315
- },
316
- buyer_email: {
317
- type: "string",
318
- description: "Email to deliver the access key after payment",
319
- },
320
- buyer_org: {
321
- type: "string",
322
- description: "Buyer organization name (for billing + audit ledger)",
323
- },
324
- billing_type: {
325
- type: "string",
326
- enum: ["annual", "monthly", "annual_plus_monthly"],
327
- description: "Billing cadence (default: annual)",
328
- },
329
- license_tier: {
330
- type: "string",
331
- enum: ["rag", "training", "inference", "full_ai"],
332
- description: "License tier (default: rag)",
333
- },
334
- duration_months: {
335
- type: "number",
336
- description: "License duration in months (default: 12)",
337
- },
338
- scope: {
339
- type: "string",
340
- enum: ["custom", "platform_wide", "filtered"],
341
- description: "Coverage scope (default: custom)",
342
- },
343
- filter_rules: {
344
- type: "object",
345
- description: "Required when scope='filtered'. See Phase 10 docs for shape: excluded_publisher_ids / direct_license_carveouts / categories / max_price_per_event.",
346
- },
347
- buyer_webhook_url: {
348
- type: "string",
349
- description: "Optional HMAC-signed webhook for content.published events on covered publishers",
297
+ // ─── Phase 10 + 11 buyer-side surfaces (M6.4) ─────────────────────────────
298
+ {
299
+ name: "purchase_enterprise_license",
300
+ description: "Purchase a bulk enterprise license covering multiple publishers (Phase 10). " +
301
+ "Returns a Stripe client_secret for payment completion + the enterprise_license_id. " +
302
+ "After payment, an ent_* access key is emailed to buyer_email. " +
303
+ "Scopes: 'custom' (pass-through publisher_ids), 'platform_wide' (auto-resolve all opted-in publishers), 'filtered' (Phase 10 filter_rules). " +
304
+ "License tiers: 'rag' (= ai_retrieval), 'training' (= ai_training, flat-fee not metered), 'inference' (= ai_retrieval), 'full_ai' (writes both retrieval + training records).",
305
+ inputSchema: {
306
+ type: "object",
307
+ required: ["publisher_ids", "buyer_email", "buyer_org"],
308
+ properties: {
309
+ publisher_ids: {
310
+ type: "array",
311
+ items: { type: "string" },
312
+ description: "Array of publisher UUIDs. Required for scope='custom'; ignored for platform_wide/filtered (resolved server-side).",
313
+ },
314
+ buyer_email: {
315
+ type: "string",
316
+ description: "Email to deliver the access key after payment",
317
+ },
318
+ buyer_org: {
319
+ type: "string",
320
+ description: "Buyer organization name (for billing + audit ledger)",
321
+ },
322
+ billing_type: {
323
+ type: "string",
324
+ enum: ["annual", "monthly", "annual_plus_monthly"],
325
+ description: "Billing cadence (default: annual)",
326
+ },
327
+ license_tier: {
328
+ type: "string",
329
+ enum: ["rag", "training", "inference", "full_ai"],
330
+ description: "License tier (default: rag)",
331
+ },
332
+ duration_months: {
333
+ type: "number",
334
+ description: "License duration in months (default: 12)",
335
+ },
336
+ scope: {
337
+ type: "string",
338
+ enum: ["custom", "platform_wide", "filtered"],
339
+ description: "Coverage scope (default: custom)",
340
+ },
341
+ filter_rules: {
342
+ type: "object",
343
+ description: "Required when scope='filtered'. See Phase 10 docs for shape: excluded_publisher_ids / direct_license_carveouts / categories / max_price_per_event.",
344
+ },
345
+ buyer_webhook_url: {
346
+ type: "string",
347
+ description: "Optional HMAC-signed webhook for content.published events on covered publishers",
348
+ },
350
349
  },
351
350
  },
352
351
  },
353
- },
354
- ];
355
- // If a buyer token is configured, expose content delivery tooling
356
- if (BUYER_TOKEN) {
357
- TOOLS.push({
358
- name: "get_content",
359
- description: "Retrieve the full body of a licensed article using a buyer API token (opedd_buyer_live_* canonical; opedd_buyer_test_* for sandbox). " +
360
- "Requires OPEDD_BUYER_TOKEN env var (create one at opedd.com/licenses after purchasing). " +
361
- "Works for per-article licenses (token scoped to that article) and archive licenses (token covers all publisher content). " +
362
- "The publisher must have content delivery enabled and must have pushed content for the article. " +
363
- "Phase 11 M2 RAG-extended shape: response includes 7 RAG-essential metadata fields — author, language, word_count, content_hash, image_urls, canonical_url, tags. " +
364
- "On pre-2026-05-14 historical articles, optional fields (author/language/image_urls/canonical_url/tags) may be NULL. " +
365
- "NULL means 'data unavailable for this article', NOT 'explicitly empty' — treat as data-missing when filtering; do not interpret as anti-match.",
366
- inputSchema: {
367
- type: "object",
368
- required: ["article_id"],
369
- properties: {
370
- article_id: {
371
- type: "string",
372
- description: "The Opedd article UUID to retrieve content for",
373
- },
374
- buyer_token: {
375
- type: "string",
376
- description: "Buyer API token (opedd_buyer_live_* or opedd_buyer_test_*). Falls back to OPEDD_BUYER_TOKEN env var.",
352
+ ];
353
+ // If a buyer token is configured, expose content delivery tooling
354
+ if (has.buyerToken) {
355
+ TOOLS.push({
356
+ name: "get_content",
357
+ description: "Retrieve the full body of a licensed article using a buyer API token (opedd_buyer_live_* canonical; opedd_buyer_test_* for sandbox). " +
358
+ "Requires OPEDD_BUYER_TOKEN env var (create one at opedd.com/licenses after purchasing). " +
359
+ "Works for per-article licenses (token scoped to that article) and archive licenses (token covers all publisher content). " +
360
+ "The publisher must have content delivery enabled and must have pushed content for the article. " +
361
+ "Phase 11 M2 RAG-extended shape: response includes 7 RAG-essential metadata fields — author, language, word_count, content_hash, image_urls, canonical_url, tags. " +
362
+ "On pre-2026-05-14 historical articles, optional fields (author/language/image_urls/canonical_url/tags) may be NULL. " +
363
+ "NULL means 'data unavailable for this article', NOT 'explicitly empty' — treat as data-missing when filtering; do not interpret as anti-match.",
364
+ inputSchema: {
365
+ type: "object",
366
+ required: ["article_id"],
367
+ properties: {
368
+ article_id: {
369
+ type: "string",
370
+ description: "The Opedd article UUID to retrieve content for",
371
+ },
372
+ buyer_token: {
373
+ type: "string",
374
+ description: "Buyer API token (opedd_buyer_live_* or opedd_buyer_test_*). Falls back to OPEDD_BUYER_TOKEN env var.",
375
+ },
377
376
  },
378
377
  },
379
- },
380
- });
381
- }
382
- // If an enterprise access key is configured, expose feed tools
383
- if (ACCESS_KEY) {
384
- TOOLS.push({
385
- name: "list_feed",
386
- description: "List articles from a buyer's licensed catalog via GET /enterprise-license (Phase 10 + 11). " +
387
- "Returns JSON-format response with paginated articles. " +
388
- "Use `since` (ISO 8601) for delta-feed polling — only articles published after the timestamp. " +
389
- "Use `cursor` for pagination across pages. " +
390
- "Requires OPEDD_ACCESS_KEY (ent_* enterprise access key). " +
391
- "For larger bulk corpus pulls, use stream_feed_ndjson (up to 1000 articles per call vs 200 here).",
392
- inputSchema: {
393
- type: "object",
394
- properties: {
395
- since: {
396
- type: "string",
397
- description: "ISO 8601 timestamp — return only articles with published_at > since",
398
- },
399
- cursor: {
400
- type: "string",
401
- description: "Opaque cursor from prior response's _meta.next_cursor",
402
- },
403
- limit: {
404
- type: "number",
405
- description: "Max articles per response (default: 50, max: 200)",
378
+ });
379
+ }
380
+ // If an enterprise access key is configured, expose feed tools
381
+ if (has.accessKey) {
382
+ TOOLS.push({
383
+ name: "list_feed",
384
+ description: "List articles from a buyer's licensed catalog via GET /enterprise-license (Phase 10 + 11). " +
385
+ "Returns JSON-format response with paginated articles. " +
386
+ "Use `since` (ISO 8601) for delta-feed polling — only articles published after the timestamp. " +
387
+ "Use `cursor` for pagination across pages. " +
388
+ "Requires OPEDD_ACCESS_KEY (ent_* enterprise access key). " +
389
+ "For larger bulk corpus pulls, use stream_feed_ndjson (up to 1000 articles per call vs 200 here).",
390
+ inputSchema: {
391
+ type: "object",
392
+ properties: {
393
+ since: {
394
+ type: "string",
395
+ description: "ISO 8601 timestamp — return only articles with published_at > since",
396
+ },
397
+ cursor: {
398
+ type: "string",
399
+ description: "Opaque cursor from prior response's _meta.next_cursor",
400
+ },
401
+ limit: {
402
+ type: "number",
403
+ description: "Max articles per response (default: 50, max: 200)",
404
+ },
406
405
  },
407
406
  },
408
- },
409
- });
410
- TOOLS.push({
411
- name: "stream_feed_ndjson",
412
- description: "Bulk-export a buyer's licensed catalog via GET /enterprise-license?format=ndjson (Phase 11 M3). " +
413
- "Returns up to 1000 articles per call (collected from line-delimited JSON wire format). " +
414
- "Each article emits one usage_records row (analytics-only sentinel 'bulk-export:<request_id>:<article_id>' — not metered-billable per the revenue-model bifurcation invariant). " +
415
- "Use `since` (ISO 8601) for delta-feed. Use `cursor` to paginate beyond 1000. " +
416
- "Backend supports 5000 articles per call; the MCP cap is 1000 for transport reasonability. " +
417
- "Real bulk-ingest pipelines should use the Python SDK (pip install opedd) directly — not via MCP. " +
418
- "Requires OPEDD_ACCESS_KEY (ent_*).",
419
- inputSchema: {
420
- type: "object",
421
- properties: {
422
- since: {
423
- type: "string",
424
- description: "ISO 8601 timestamp — return only articles with published_at > since",
425
- },
426
- cursor: {
427
- type: "string",
428
- description: "Opaque cursor from prior response's _meta.next_cursor",
429
- },
430
- limit: {
431
- type: "number",
432
- description: "Max articles per response (default: 200, max: 1000)",
407
+ });
408
+ TOOLS.push({
409
+ name: "stream_feed_ndjson",
410
+ description: "Bulk-export a buyer's licensed catalog via GET /enterprise-license?format=ndjson (Phase 11 M3). " +
411
+ "Returns up to 1000 articles per call (collected from line-delimited JSON wire format). " +
412
+ "Each article emits one usage_records row (analytics-only sentinel 'bulk-export:<request_id>:<article_id>' — not metered-billable per the revenue-model bifurcation invariant). " +
413
+ "Use `since` (ISO 8601) for delta-feed. Use `cursor` to paginate beyond 1000. " +
414
+ "Backend supports 5000 articles per call; the MCP cap is 1000 for transport reasonability. " +
415
+ "Real bulk-ingest pipelines should use the Python SDK (pip install opedd) directly — not via MCP. " +
416
+ "Requires OPEDD_ACCESS_KEY (ent_*).",
417
+ inputSchema: {
418
+ type: "object",
419
+ properties: {
420
+ since: {
421
+ type: "string",
422
+ description: "ISO 8601 timestamp — return only articles with published_at > since",
423
+ },
424
+ cursor: {
425
+ type: "string",
426
+ description: "Opaque cursor from prior response's _meta.next_cursor",
427
+ },
428
+ limit: {
429
+ type: "number",
430
+ description: "Max articles per response (default: 200, max: 1000)",
431
+ },
433
432
  },
434
433
  },
435
- },
436
- });
437
- }
438
- // If a Supabase buyer JWT is configured, expose audit + compliance tools
439
- if (BUYER_JWT) {
440
- TOOLS.push({
441
- name: "get_audit_events",
442
- description: "Browse per-event audit rows for the authenticated buyer via GET /buyer-audit (Phase 9.x). " +
443
- "Each row carries license_terms + Tempo on-chain attestation (merkle_root + inclusion_proof when blockchain_status='confirmed'). " +
444
- "Optional filter by event_type ('content_access', 'bulk_content_access', 'compliance_report_generated'). " +
445
- "Window cap 30 days (vs 90-day cap on get_compliance_dossier). " +
446
- "Attestation inclusion proof is included on every row by default — no separate flag needed (M6.4 consolidation per founder ratification: tools 4 + 6 merged into one cleaner mental model). " +
447
- "Requires OPEDD_BUYER_JWT (Supabase session JWT from the buyer portal).",
448
- inputSchema: {
449
- type: "object",
450
- properties: {
451
- from: {
452
- type: "string",
453
- description: "ISO 8601 timestamp lower bound (inclusive)",
454
- },
455
- to: {
456
- type: "string",
457
- description: "ISO 8601 timestamp upper bound (inclusive)",
458
- },
459
- event_type: {
460
- type: "string",
461
- enum: ["content_access", "bulk_content_access", "compliance_report_generated"],
462
- description: "Optional event-class filter",
463
- },
464
- cursor: {
465
- type: "string",
466
- description: "Opaque cursor for pagination",
467
- },
468
- limit: {
469
- type: "number",
470
- description: "Max events per response (default: 50, max: 200)",
434
+ });
435
+ }
436
+ // If a Supabase buyer JWT is configured, expose audit + compliance tools
437
+ if (has.buyerJwt) {
438
+ TOOLS.push({
439
+ name: "get_audit_events",
440
+ description: "Browse per-event audit rows for the authenticated buyer via GET /buyer-audit (Phase 9.x). " +
441
+ "Each row carries license_terms + Tempo on-chain attestation (merkle_root + inclusion_proof when blockchain_status='confirmed'). " +
442
+ "Optional filter by event_type ('content_access', 'bulk_content_access', 'compliance_report_generated'). " +
443
+ "Window cap 30 days (vs 90-day cap on get_compliance_dossier). " +
444
+ "Attestation inclusion proof is included on every row by default — no separate flag needed (M6.4 consolidation per founder ratification: tools 4 + 6 merged into one cleaner mental model). " +
445
+ "Requires OPEDD_BUYER_JWT (Supabase session JWT from the buyer portal).",
446
+ inputSchema: {
447
+ type: "object",
448
+ properties: {
449
+ from: {
450
+ type: "string",
451
+ description: "ISO 8601 timestamp lower bound (inclusive)",
452
+ },
453
+ to: {
454
+ type: "string",
455
+ description: "ISO 8601 timestamp upper bound (inclusive)",
456
+ },
457
+ event_type: {
458
+ type: "string",
459
+ enum: ["content_access", "bulk_content_access", "compliance_report_generated"],
460
+ description: "Optional event-class filter",
461
+ },
462
+ cursor: {
463
+ type: "string",
464
+ description: "Opaque cursor for pagination",
465
+ },
466
+ limit: {
467
+ type: "number",
468
+ description: "Max events per response (default: 50, max: 200)",
469
+ },
471
470
  },
472
471
  },
473
- },
474
- });
475
- TOOLS.push({
476
- name: "get_buyer_account",
477
- description: "Fetch the authenticated buyer's account profile + masked API key list via GET /buyer-account. " +
478
- "Returns the enterprise_buyers row (contact_email, buyer_org, created_at, etc.) plus a list of all " +
479
- "buyer-side API keys with masked prefixes (NEVER plaintext post-issuance — only the 12-char " +
480
- "key_prefix is returned, e.g. 'opedd_buyer_'). " +
481
- "Use cases: post-signup verification ('what was just issued to me?'), buyer dashboard mental model " +
482
- "('what licenses do I currently hold?'), audit prep ('show me the key list before rotation'). " +
483
- "For full mid-lifecycle license details (filter_rules, billing, payouts), buyers consult the buyer portal at opedd.com/buyer. " +
484
- "Requires OPEDD_BUYER_JWT.",
485
- inputSchema: {
486
- type: "object",
487
- properties: {},
488
- },
489
- });
490
- TOOLS.push({
491
- name: "article_53_attestation",
492
- description: "Issue a signed JWT attesting to EU AI Act Article 53 compliance for a specific license via " +
493
- "GET /eu-ai-act/article-53-attestation (Phase 12 Wave 1 W1.4). " +
494
- "Returns a freshly-signed HS256 JWT regulators can verify offline against the canonical signing key. " +
495
- "Embeds: license context, usage-count over the attestation window, the most-recent Tempo Merkle root, " +
496
- "and canonical claims (iss/sub/iat/exp/jti/aud). " +
497
- "**The artifact AI labs hand to legal/procurement for EU AI Act Article 53(1)(d) transparency-obligation evidence.** " +
498
- "Per INVARIANTS.md W1.6: this attests to EU AI Act Article 53 ONLY (buyer-side GPAI-model-provider " +
499
- "transparency obligation). It does NOT discharge a publisher's CDSM Article 4(3) reservation obligation — " +
500
- "that lives on the rsl_get tool (jsonld=true variant). Never conflate. " +
501
- "Optional `content_id` scopes the attestation to one article; default is license-wide. " +
502
- "Window cap: 365 days. Requires OPEDD_BUYER_JWT.",
503
- inputSchema: {
504
- type: "object",
505
- required: ["license_id"],
506
- properties: {
507
- license_id: {
508
- type: "string",
509
- description: "UUID of the enterprise_license OR legacy individual license to attest. Buyer must own it.",
510
- },
511
- content_id: {
512
- type: "string",
513
- description: "Optional UUID of a specific article to scope the attestation. Default: license-wide.",
514
- },
515
- window_start: {
516
- type: "string",
517
- description: "ISO 8601 lower bound of the attestation window. Default: now - 90 days.",
518
- },
519
- window_end: {
520
- type: "string",
521
- description: "ISO 8601 upper bound. Default: now. Window may not exceed 365 days (hard cap).",
522
- },
472
+ });
473
+ TOOLS.push({
474
+ name: "get_buyer_account",
475
+ description: "Fetch the authenticated buyer's account profile + masked API key list via GET /buyer-account. " +
476
+ "Returns the enterprise_buyers row (contact_email, buyer_org, created_at, etc.) plus a list of all " +
477
+ "buyer-side API keys with masked prefixes (NEVER plaintext post-issuance — only the 12-char " +
478
+ "key_prefix is returned, e.g. 'opedd_buyer_'). " +
479
+ "Use cases: post-signup verification ('what was just issued to me?'), buyer dashboard mental model " +
480
+ "('what licenses do I currently hold?'), audit prep ('show me the key list before rotation'). " +
481
+ "For full mid-lifecycle license details (filter_rules, billing, payouts), buyers consult the buyer portal at opedd.com/buyer. " +
482
+ "Requires OPEDD_BUYER_JWT.",
483
+ inputSchema: {
484
+ type: "object",
485
+ properties: {},
523
486
  },
524
- },
525
- });
526
- TOOLS.push({
527
- name: "get_compliance_dossier",
528
- description: "Generate a procurement-defense compliance dossier via GET /buyer-compliance-report (Phase 11 M4). " +
529
- "Per-row dossier shape: 25+ fields including 17 RAG-essential article fields + full license_terms + on_chain_attestation block. " +
530
- "Bulk envelopes fan out into per-article rows by iterating metadata.article_ids[]. " +
531
- "Self-audit invariant: every successful call writes one license_events row with event_type='compliance_report_generated' BEFORE returning. " +
532
- "Window cap: 90 days per call (vs 30-day cap on get_audit_events). For annual audits, paginate via _meta.next_cursor across 4 quarterly windows. " +
533
- "Compliance framework anchors (boolean flags) map to EU AI Act Article 53, CDSM Article 4(3), on-chain attestation, TDM reservation. " +
534
- "Requires OPEDD_BUYER_JWT.",
535
- inputSchema: {
536
- type: "object",
537
- required: ["from", "to"],
538
- properties: {
539
- from: {
540
- type: "string",
541
- description: "ISO 8601 timestamp lower bound (inclusive)",
542
- },
543
- to: {
544
- type: "string",
545
- description: "ISO 8601 timestamp upper bound (inclusive). Window cap 90 days.",
546
- },
547
- cursor: {
548
- type: "string",
549
- description: "Opaque cursor for pagination",
487
+ });
488
+ TOOLS.push({
489
+ name: "article_53_attestation",
490
+ description: "Issue a signed JWT attesting to EU AI Act Article 53 compliance for a specific license via " +
491
+ "GET /eu-ai-act/article-53-attestation (Phase 12 Wave 1 W1.4). " +
492
+ "Returns a freshly-signed HS256 JWT regulators can verify offline against the canonical signing key. " +
493
+ "Embeds: license context, usage-count over the attestation window, the most-recent Tempo Merkle root, " +
494
+ "and canonical claims (iss/sub/iat/exp/jti/aud). " +
495
+ "**The artifact AI labs hand to legal/procurement for EU AI Act Article 53(1)(d) transparency-obligation evidence.** " +
496
+ "Per INVARIANTS.md W1.6: this attests to EU AI Act Article 53 ONLY (buyer-side GPAI-model-provider " +
497
+ "transparency obligation). It does NOT discharge a publisher's CDSM Article 4(3) reservation obligation — " +
498
+ "that lives on the rsl_get tool (jsonld=true variant). Never conflate. " +
499
+ "Optional `content_id` scopes the attestation to one article; default is license-wide. " +
500
+ "Window cap: 365 days. Requires OPEDD_BUYER_JWT.",
501
+ inputSchema: {
502
+ type: "object",
503
+ required: ["license_id"],
504
+ properties: {
505
+ license_id: {
506
+ type: "string",
507
+ description: "UUID of the enterprise_license OR legacy individual license to attest. Buyer must own it.",
508
+ },
509
+ content_id: {
510
+ type: "string",
511
+ description: "Optional UUID of a specific article to scope the attestation. Default: license-wide.",
512
+ },
513
+ window_start: {
514
+ type: "string",
515
+ description: "ISO 8601 lower bound of the attestation window. Default: now - 90 days.",
516
+ },
517
+ window_end: {
518
+ type: "string",
519
+ description: "ISO 8601 upper bound. Default: now. Window may not exceed 365 days (hard cap).",
520
+ },
550
521
  },
551
522
  },
552
- },
553
- });
554
- }
555
- // If a publisher API key is configured, expose publisher-specific tooling
556
- if (PUB_BEARER || API_KEY) {
557
- TOOLS.push({
558
- name: "list_publisher_content",
559
- description: "List all licensable articles for the authenticated publisher (requires OPEDD_PUB_BEARER, or legacy OPEDD_API_KEY). " +
560
- "Returns articles with titles, descriptions, pricing, and sales statistics. " +
561
- "Use article IDs from this list to purchase licenses via purchase_license.",
562
- inputSchema: {
563
- type: "object",
564
- properties: {
565
- limit: {
566
- type: "number",
567
- description: "Number of results (default: 20, max: 100)",
568
- },
569
- type: {
570
- type: "string",
571
- enum: ["human", "ai"],
572
- description: "Filter by license type availability",
523
+ });
524
+ TOOLS.push({
525
+ name: "get_compliance_dossier",
526
+ description: "Generate a procurement-defense compliance dossier via GET /buyer-compliance-report (Phase 11 M4). " +
527
+ "Per-row dossier shape: 25+ fields including 17 RAG-essential article fields + full license_terms + on_chain_attestation block. " +
528
+ "Bulk envelopes fan out into per-article rows by iterating metadata.article_ids[]. " +
529
+ "Self-audit invariant: every successful call writes one license_events row with event_type='compliance_report_generated' BEFORE returning. " +
530
+ "Window cap: 90 days per call (vs 30-day cap on get_audit_events). For annual audits, paginate via _meta.next_cursor across 4 quarterly windows. " +
531
+ "Compliance framework anchors (boolean flags) map to EU AI Act Article 53, CDSM Article 4(3), on-chain attestation, TDM reservation. " +
532
+ "Requires OPEDD_BUYER_JWT.",
533
+ inputSchema: {
534
+ type: "object",
535
+ required: ["from", "to"],
536
+ properties: {
537
+ from: {
538
+ type: "string",
539
+ description: "ISO 8601 timestamp lower bound (inclusive)",
540
+ },
541
+ to: {
542
+ type: "string",
543
+ description: "ISO 8601 timestamp upper bound (inclusive). Window cap 90 days.",
544
+ },
545
+ cursor: {
546
+ type: "string",
547
+ description: "Opaque cursor for pagination",
548
+ },
573
549
  },
574
- offset: {
575
- type: "number",
576
- description: "Pagination offset (default: 0)",
550
+ },
551
+ });
552
+ }
553
+ // If a publisher API key is configured, expose publisher-specific tooling
554
+ if (has.pubBearer) {
555
+ TOOLS.push({
556
+ name: "list_publisher_content",
557
+ description: "List all licensable articles for the authenticated publisher (requires OPEDD_PUB_BEARER, or legacy OPEDD_API_KEY). " +
558
+ "Returns articles with titles, descriptions, pricing, and sales statistics. " +
559
+ "Use article IDs from this list to purchase licenses via purchase_license.",
560
+ inputSchema: {
561
+ type: "object",
562
+ properties: {
563
+ limit: {
564
+ type: "number",
565
+ description: "Number of results (default: 20, max: 100)",
566
+ },
567
+ type: {
568
+ type: "string",
569
+ enum: ["human", "ai"],
570
+ description: "Filter by license type availability",
571
+ },
572
+ offset: {
573
+ type: "number",
574
+ description: "Pagination offset (default: 0)",
575
+ },
577
576
  },
578
577
  },
579
- },
580
- });
581
- // Supply-side push: onboard a back-catalogue or send new posts directly from
582
- // the AI assistant — the native companion to the /publishers-content API.
583
- TOOLS.push({
584
- name: "push_content",
585
- description: "Push your published articles to Opedd so they can be licensed to AI buyers (requires OPEDD_PUB_BEARER — your opedd_pub_ publisher key). " +
586
- "Send 1–100 articles per call; batch larger back-catalogues into multiple calls. Each article needs title, url, and html_body — everything else is optional (published_at defaults to now). " +
587
- "This is the supply-side companion to list_publisher_content: use it to onboard your archive or push new content with no code, straight from your AI assistant.",
588
- inputSchema: {
589
- type: "object",
590
- required: ["articles"],
591
- properties: {
592
- articles: {
593
- type: "array",
594
- minItems: 1,
595
- maxItems: 100,
596
- description: "1–100 articles to push in this call.",
597
- items: {
598
- type: "object",
599
- required: ["title", "url", "html_body"],
600
- properties: {
601
- title: { type: "string", description: "Article title (required, ≤500 chars)." },
602
- url: { type: "string", description: "The article's canonical web address (required)." },
603
- html_body: { type: "string", description: "Full article content, HTML or plain text (required, ≤200,000 chars)." },
604
- published_at: { type: "string", description: "ISO-8601 datetime (e.g. 2026-01-15T09:30:00Z). Defaults to now if omitted." },
605
- description: { type: "string", description: "Short summary (≤500 chars)." },
606
- author: { type: "string", description: "Author name (≤200 chars)." },
607
- language: { type: "string", description: "Language code, e.g. \"en\"." },
608
- tags: { type: "array", items: { type: "string" }, description: "Up to 20 tags." },
609
- image_urls: { type: "array", items: { type: "string" }, description: "Up to 10 body-image URLs." },
610
- thumbnail_url: { type: "string", description: "https cover-image URL for the catalog." },
611
- canonical_url: { type: "string", description: "Canonical URL if different from url." },
612
- category: { type: "string", description: "Content category." },
613
- is_paid: { type: "boolean", description: "Whether the article is behind a paywall." },
614
- audience: { type: "string", enum: ["everyone", "only_free", "only_paid"], description: "Intended audience." },
578
+ });
579
+ // Supply-side push: onboard a back-catalogue or send new posts directly from
580
+ // the AI assistant — the native companion to the /publishers-content API.
581
+ TOOLS.push({
582
+ name: "push_content",
583
+ description: "Push your published articles to Opedd so they can be licensed to AI buyers (requires OPEDD_PUB_BEARER — your opedd_pub_ publisher key). " +
584
+ "Send 1–100 articles per call; batch larger back-catalogues into multiple calls. Each article needs title, url, and html_body — everything else is optional (published_at defaults to now). " +
585
+ "This is the supply-side companion to list_publisher_content: use it to onboard your archive or push new content with no code, straight from your AI assistant.",
586
+ inputSchema: {
587
+ type: "object",
588
+ required: ["articles"],
589
+ properties: {
590
+ articles: {
591
+ type: "array",
592
+ minItems: 1,
593
+ maxItems: 100,
594
+ description: "1–100 articles to push in this call.",
595
+ items: {
596
+ type: "object",
597
+ required: ["title", "url", "html_body"],
598
+ properties: {
599
+ title: { type: "string", description: "Article title (required, ≤500 chars)." },
600
+ url: { type: "string", description: "The article's canonical web address (required)." },
601
+ html_body: { type: "string", description: "Full article content, HTML or plain text (required, ≤200,000 chars)." },
602
+ published_at: { type: "string", description: "ISO-8601 datetime (e.g. 2026-01-15T09:30:00Z). Defaults to now if omitted." },
603
+ description: { type: "string", description: "Short summary (≤500 chars)." },
604
+ author: { type: "string", description: "Author name (≤200 chars)." },
605
+ language: { type: "string", description: "Language code, e.g. \"en\"." },
606
+ tags: { type: "array", items: { type: "string" }, description: "Up to 20 tags." },
607
+ image_urls: { type: "array", items: { type: "string" }, description: "Up to 10 body-image URLs." },
608
+ thumbnail_url: { type: "string", description: "https cover-image URL for the catalog." },
609
+ canonical_url: { type: "string", description: "Canonical URL if different from url." },
610
+ category: { type: "string", description: "Content category." },
611
+ is_paid: { type: "boolean", description: "Whether the article is behind a paywall." },
612
+ audience: { type: "string", enum: ["everyone", "only_free", "only_paid"], description: "Intended audience." },
613
+ },
615
614
  },
616
615
  },
617
616
  },
618
617
  },
619
- },
620
- });
618
+ });
619
+ }
620
+ return TOOLS;
621
621
  }
622
+ // stdio: credential-gated list (only tools the local env can use).
623
+ export const TOOLS = buildTools({
624
+ buyerToken: !!ENV_CREDS.buyerToken,
625
+ accessKey: !!ENV_CREDS.accessKey,
626
+ buyerJwt: !!ENV_CREDS.buyerJwt,
627
+ pubBearer: !!(ENV_CREDS.pubBearer || ENV_CREDS.apiKey),
628
+ });
629
+ // hosted gateway: advertise ALL tools; per-request creds decide what
630
+ // actually succeeds (dispatchTool returns a clear error on missing auth).
631
+ export const ALL_TOOLS = buildTools({
632
+ buyerToken: true, accessKey: true, buyerJwt: true, pubBearer: true,
633
+ });
622
634
  // ─── MCP Server ───────────────────────────────────────────────────────────────
623
635
  const server = new Server({ name: "opedd-mcp", version: SERVER_VERSION }, { capabilities: { tools: {} } });
624
636
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
@@ -638,7 +650,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
638
650
  // is a thin delegation to dispatchTool. Exporting allows unit tests to mock
639
651
  // global fetch + invoke each tool's handler directly without spawning a
640
652
  // stdio subprocess.
641
- export async function dispatchTool(name, args) {
653
+ export async function dispatchTool(name, args, creds = ENV_CREDS) {
642
654
  try {
643
655
  switch (name) {
644
656
  // ── lookup_content ─────────────────────────────────────────────────────
@@ -646,7 +658,7 @@ export async function dispatchTool(name, args) {
646
658
  const { url } = args;
647
659
  if (!url)
648
660
  return err("url is required");
649
- const data = await opeddFetch(`/lookup-article?url=${encodeURIComponent(url)}`);
661
+ const data = await opeddFetch(creds, `/lookup-article?url=${encodeURIComponent(url)}`);
650
662
  return ok(data);
651
663
  }
652
664
  // ── purchase_license ───────────────────────────────────────────────────
@@ -655,11 +667,11 @@ export async function dispatchTool(name, args) {
655
667
  if (!article_url && !article_id) {
656
668
  return err("Either article_url or article_id is required");
657
669
  }
658
- const buyerEmail = argEmail || BUYER_EMAIL;
670
+ const buyerEmail = argEmail || creds.buyerEmail;
659
671
  if (!buyerEmail) {
660
672
  return err("buyer_email is required (or set the OPEDD_BUYER_EMAIL env var)");
661
673
  }
662
- const paymentMethodId = argPm || PAYMENT_METHOD_ID;
674
+ const paymentMethodId = argPm || creds.paymentMethodId;
663
675
  if (!paymentMethodId) {
664
676
  return err("payment_method_id is required (or set the OPEDD_PAYMENT_METHOD_ID env var). " +
665
677
  "Get a Stripe payment method ID by saving a card at stripe.com/docs/api/payment_methods.");
@@ -673,7 +685,7 @@ export async function dispatchTool(name, args) {
673
685
  ...(buyer_organization ? { buyer_organization } : {}),
674
686
  ...(intended_use ? { intended_use } : {}),
675
687
  };
676
- const data = await opeddFetch("/agent-purchase", {
688
+ const data = await opeddFetch(creds, "/agent-purchase", {
677
689
  method: "POST",
678
690
  body: JSON.stringify(body),
679
691
  });
@@ -684,7 +696,7 @@ export async function dispatchTool(name, args) {
684
696
  const { license_key } = args;
685
697
  if (!license_key)
686
698
  return err("license_key is required");
687
- const data = await opeddFetch(`/verify-license?key=${encodeURIComponent(license_key)}`);
699
+ const data = await opeddFetch(creds, `/verify-license?key=${encodeURIComponent(license_key)}`);
688
700
  return ok(data);
689
701
  }
690
702
  // ── browse_registry ────────────────────────────────────────────────────
@@ -696,7 +708,7 @@ export async function dispatchTool(name, args) {
696
708
  if (article_id)
697
709
  params.set("article_id", article_id);
698
710
  params.set("limit", String(Math.min(Number(limit), 50)));
699
- const data = await opeddFetch(`/registry?${params.toString()}`);
711
+ const data = await opeddFetch(creds, `/registry?${params.toString()}`);
700
712
  return ok(data);
701
713
  }
702
714
  // ── get_content ────────────────────────────────────────────────────────
@@ -704,12 +716,12 @@ export async function dispatchTool(name, args) {
704
716
  const { article_id, buyer_token: argToken } = args;
705
717
  if (!article_id)
706
718
  return err("article_id is required");
707
- const token = argToken || BUYER_TOKEN;
719
+ const token = argToken || creds.buyerToken;
708
720
  if (!token) {
709
721
  return err("buyer_token is required (or set the OPEDD_BUYER_TOKEN env var). " +
710
722
  "Create a token at opedd.com/licenses after purchasing a license.");
711
723
  }
712
- const data = await opeddFetch(`/content-delivery?article_id=${encodeURIComponent(article_id)}`, { headers: { Authorization: `Bearer ${token}` } });
724
+ const data = await opeddFetch(creds, `/content-delivery?article_id=${encodeURIComponent(article_id)}`, { headers: { Authorization: `Bearer ${token}` } });
713
725
  return ok(data);
714
726
  }
715
727
  // ── publisher_directory (buyer-discovery catalog browse) ───────────────
@@ -727,7 +739,7 @@ export async function dispatchTool(name, args) {
727
739
  if (offset !== undefined)
728
740
  params.set("offset", String(offset));
729
741
  const query = params.toString();
730
- const data = await opeddFetch(`/publisher-directory${query ? `?${query}` : ""}`);
742
+ const data = await opeddFetch(creds, `/publisher-directory${query ? `?${query}` : ""}`);
731
743
  return ok(data);
732
744
  }
733
745
  // ── detect_platform (Phase 12 Wave 3 W3.1) ─────────────────────────────
@@ -735,7 +747,7 @@ export async function dispatchTool(name, args) {
735
747
  const { url } = args;
736
748
  if (!url)
737
749
  return err("url is required");
738
- const data = await opeddFetch("/detect-platform", {
750
+ const data = await opeddFetch(creds, "/detect-platform", {
739
751
  method: "POST",
740
752
  body: JSON.stringify({ url }),
741
753
  });
@@ -747,7 +759,7 @@ export async function dispatchTool(name, args) {
747
759
  if (!publisher_id)
748
760
  return err("publisher_id is required");
749
761
  const accept = jsonld ? "application/ld+json" : "application/json";
750
- const data = await opeddFetch(`/rsl-manifest?publisher_id=${encodeURIComponent(publisher_id)}`, { headers: { Accept: accept } });
762
+ const data = await opeddFetch(creds, `/rsl-manifest?publisher_id=${encodeURIComponent(publisher_id)}`, { headers: { Accept: accept } });
751
763
  return ok(data);
752
764
  }
753
765
  // ── purchase_enterprise_license (Phase 10) ─────────────────────────────
@@ -773,7 +785,7 @@ export async function dispatchTool(name, args) {
773
785
  ...(filter_rules ? { filter_rules } : {}),
774
786
  ...(buyer_webhook_url ? { buyer_webhook_url } : {}),
775
787
  };
776
- const data = await opeddFetch("/enterprise-license", {
788
+ const data = await opeddFetch(creds, "/enterprise-license", {
777
789
  method: "POST",
778
790
  body: JSON.stringify(body),
779
791
  });
@@ -781,12 +793,12 @@ export async function dispatchTool(name, args) {
781
793
  }
782
794
  // ── list_feed (Phase 10 + 11) ──────────────────────────────────────────
783
795
  case "list_feed": {
784
- if (!ACCESS_KEY) {
796
+ if (!creds.accessKey) {
785
797
  return err("OPEDD_ACCESS_KEY env var is required for this tool (ent_* enterprise access key)");
786
798
  }
787
799
  const { since, cursor, limit = 50 } = args;
788
800
  const params = new URLSearchParams({
789
- access_key: ACCESS_KEY,
801
+ access_key: creds.accessKey,
790
802
  format: "json",
791
803
  limit: String(Math.min(Number(limit) || 50, 200)),
792
804
  });
@@ -794,17 +806,17 @@ export async function dispatchTool(name, args) {
794
806
  params.set("since", since);
795
807
  if (cursor)
796
808
  params.set("cursor", cursor);
797
- const data = await opeddFetch(`/enterprise-license?${params.toString()}`);
809
+ const data = await opeddFetch(creds, `/enterprise-license?${params.toString()}`);
798
810
  return ok(data);
799
811
  }
800
812
  // ── stream_feed_ndjson (Phase 11 M3) ───────────────────────────────────
801
813
  case "stream_feed_ndjson": {
802
- if (!ACCESS_KEY) {
814
+ if (!creds.accessKey) {
803
815
  return err("OPEDD_ACCESS_KEY env var is required for this tool (ent_* enterprise access key)");
804
816
  }
805
817
  const { since, cursor, limit = 200 } = args;
806
818
  const params = new URLSearchParams({
807
- access_key: ACCESS_KEY,
819
+ access_key: creds.accessKey,
808
820
  format: "ndjson",
809
821
  limit: String(Math.min(Number(limit) || 200, 1000)),
810
822
  });
@@ -812,12 +824,12 @@ export async function dispatchTool(name, args) {
812
824
  params.set("since", since);
813
825
  if (cursor)
814
826
  params.set("cursor", cursor);
815
- const data = await opeddFetchNdjson(`/enterprise-license?${params.toString()}`);
827
+ const data = await opeddFetchNdjson(creds, `/enterprise-license?${params.toString()}`);
816
828
  return ok(data);
817
829
  }
818
830
  // ── get_audit_events (Phase 9.x + 10 M5 attestation) ───────────────────
819
831
  case "get_audit_events": {
820
- if (!BUYER_JWT) {
832
+ if (!creds.buyerJwt) {
821
833
  return err("OPEDD_BUYER_JWT env var is required for this tool (Supabase session JWT)");
822
834
  }
823
835
  const { from, to, event_type, cursor, limit = 50 } = args;
@@ -832,24 +844,24 @@ export async function dispatchTool(name, args) {
832
844
  params.set("event_type", event_type);
833
845
  if (cursor)
834
846
  params.set("cursor", cursor);
835
- const data = await opeddFetch(`/buyer-audit?${params.toString()}`, {
836
- headers: { Authorization: `Bearer ${BUYER_JWT}` },
847
+ const data = await opeddFetch(creds, `/buyer-audit?${params.toString()}`, {
848
+ headers: { Authorization: `Bearer ${creds.buyerJwt}` },
837
849
  });
838
850
  return ok(data);
839
851
  }
840
852
  // ── get_buyer_account (buyer profile + masked key list) ────────────────
841
853
  case "get_buyer_account": {
842
- if (!BUYER_JWT) {
854
+ if (!creds.buyerJwt) {
843
855
  return err("OPEDD_BUYER_JWT env var is required for this tool (Supabase session JWT)");
844
856
  }
845
- const data = await opeddFetch("/buyer-account", {
846
- headers: { Authorization: `Bearer ${BUYER_JWT}` },
857
+ const data = await opeddFetch(creds, "/buyer-account", {
858
+ headers: { Authorization: `Bearer ${creds.buyerJwt}` },
847
859
  });
848
860
  return ok(data);
849
861
  }
850
862
  // ── article_53_attestation (Phase 12 Wave 1 W1.4) ──────────────────────
851
863
  case "article_53_attestation": {
852
- if (!BUYER_JWT) {
864
+ if (!creds.buyerJwt) {
853
865
  return err("OPEDD_BUYER_JWT env var is required for this tool (Supabase session JWT)");
854
866
  }
855
867
  const { license_id, content_id, window_start, window_end } = args;
@@ -867,12 +879,12 @@ export async function dispatchTool(name, args) {
867
879
  // slashed "/eu-ai-act/article-53-attestation" resolved to a
868
880
  // nonexistent function named "eu-ai-act" and 404'd — this tool had
869
881
  // NEVER worked in production until the 2026-07-10 fix (live-probed).
870
- const data = await opeddFetch(`/eu-ai-act-article-53-attestation?${params.toString()}`, { headers: { Authorization: `Bearer ${BUYER_JWT}` } });
882
+ const data = await opeddFetch(creds, `/eu-ai-act-article-53-attestation?${params.toString()}`, { headers: { Authorization: `Bearer ${creds.buyerJwt}` } });
871
883
  return ok(data);
872
884
  }
873
885
  // ── get_compliance_dossier (Phase 11 M4) ───────────────────────────────
874
886
  case "get_compliance_dossier": {
875
- if (!BUYER_JWT) {
887
+ if (!creds.buyerJwt) {
876
888
  return err("OPEDD_BUYER_JWT env var is required for this tool (Supabase session JWT)");
877
889
  }
878
890
  const { from, to, cursor } = args;
@@ -887,14 +899,14 @@ export async function dispatchTool(name, args) {
887
899
  });
888
900
  if (cursor)
889
901
  params.set("cursor", cursor);
890
- const data = await opeddFetch(`/buyer-compliance-report?${params.toString()}`, {
891
- headers: { Authorization: `Bearer ${BUYER_JWT}` },
902
+ const data = await opeddFetch(creds, `/buyer-compliance-report?${params.toString()}`, {
903
+ headers: { Authorization: `Bearer ${creds.buyerJwt}` },
892
904
  });
893
905
  return ok(data);
894
906
  }
895
907
  // ── list_publisher_content ─────────────────────────────────────────────
896
908
  case "list_publisher_content": {
897
- if (!PUB_BEARER && !API_KEY) {
909
+ if (!creds.pubBearer && !creds.apiKey) {
898
910
  return err("OPEDD_PUB_BEARER env var is required for this tool (canonical Bearer; legacy OPEDD_API_KEY also accepted during transition)");
899
911
  }
900
912
  const { limit = 20, type, offset = 0 } = args;
@@ -903,12 +915,12 @@ export async function dispatchTool(name, args) {
903
915
  params.set("offset", String(Number(offset)));
904
916
  if (type)
905
917
  params.set("type", type);
906
- const data = await opeddFetch(`/api?${params.toString()}`);
918
+ const data = await opeddFetch(creds, `/api?${params.toString()}`);
907
919
  return ok(data);
908
920
  }
909
921
  // ── push_content ───────────────────────────────────────────────────────
910
922
  case "push_content": {
911
- if (!PUB_BEARER && !API_KEY) {
923
+ if (!creds.pubBearer && !creds.apiKey) {
912
924
  return err("OPEDD_PUB_BEARER env var is required for this tool (your opedd_pub_ publisher key).");
913
925
  }
914
926
  const { articles } = args;
@@ -920,7 +932,7 @@ export async function dispatchTool(name, args) {
920
932
  }
921
933
  // Backend /publishers-content enforces the full strict schema + returns
922
934
  // clear per-article errors; we pass through so the assistant can relay them.
923
- const data = await opeddFetch("/publishers-content", {
935
+ const data = await opeddFetch(creds, "/publishers-content", {
924
936
  method: "POST",
925
937
  body: JSON.stringify({ articles }),
926
938
  });