pcific 0.0.0-stage → 0.2.0

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,689 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { BaseUrlError, DEFAULT_BASE_URL, normalizeBaseUrl, readMergedEnv, redactSecrets, } from "../api/run.js";
3
+ const SAFEGUARD_TERMINAL = new Set(["done", "questions", "failed"]);
4
+ const ORBIT_TERMINAL = new Set(["listing", "questions", "failed", "cancelled"]);
5
+ export function isMcpString(value) {
6
+ return typeof value === "string";
7
+ }
8
+ export function isMcpNumber(value) {
9
+ return typeof value === "number";
10
+ }
11
+ export function isMcpJsonObject(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
13
+ }
14
+ export function parseMcpJsonValue(text) {
15
+ // SAFETY: JSON.parse returns only JSON primitives, arrays, or plain objects matching McpJsonValue.
16
+ return JSON.parse(text);
17
+ }
18
+ export function resolveMcpTestKey(cwd, envOverride) {
19
+ const env = readMergedEnv(cwd, envOverride);
20
+ const baseUrl = env.get("PCIFIC_BASE_URL")?.trim() || undefined;
21
+ // STRICT TEST-KEY-ONLY GUARD: Never load or send PCIFIC_LIVE_KEY.
22
+ const candidate = env.get("PCIFIC_TEST_KEY")?.trim();
23
+ if (candidate && candidate.startsWith("pcific_live_")) {
24
+ return {
25
+ baseUrl,
26
+ error: "Refused: PCIFIC MCP only runs with test API keys (pcific_test_*). A live key (pcific_live_*) was found in PCIFIC_TEST_KEY. Replace it with a test key before using MCP tools.",
27
+ };
28
+ }
29
+ if (!candidate) {
30
+ return {
31
+ baseUrl,
32
+ error: "Missing PCIFIC_TEST_KEY. PCIFIC MCP only runs with test keys and never reads PCIFIC_LIVE_KEY. Set PCIFIC_TEST_KEY in your environment or .env file.",
33
+ };
34
+ }
35
+ return {
36
+ apiKey: candidate,
37
+ marketplaceId: env.get("PCIFIC_MARKETPLACE_ID")?.trim() || undefined,
38
+ baseUrl,
39
+ };
40
+ }
41
+ export function redactSecret(text, secret) {
42
+ let out = text;
43
+ if (secret && secret.length >= 6) {
44
+ out = out.split(secret).join("[REDACTED_KEY]");
45
+ }
46
+ return redactSecrets(out);
47
+ }
48
+ function defaultSleep(ms) {
49
+ return new Promise((resolve) => {
50
+ setTimeout(resolve, ms);
51
+ });
52
+ }
53
+ function toResult(payload, isError = false, secretToRedact) {
54
+ const raw = JSON.stringify(payload ?? null, null, 2);
55
+ const result = {
56
+ content: [{ type: "text", text: redactSecret(raw, secretToRedact) }],
57
+ };
58
+ if (isError) {
59
+ result.isError = true;
60
+ }
61
+ return result;
62
+ }
63
+ function buildUrl(baseUrl, path, query = {}, marketplaceId) {
64
+ const cleanBase = normalizeBaseUrl(baseUrl || DEFAULT_BASE_URL);
65
+ const url = new URL(`${cleanBase}${path}`);
66
+ if (marketplaceId && query.marketplaceId === undefined) {
67
+ url.searchParams.set("marketplaceId", marketplaceId);
68
+ }
69
+ for (const [key, value] of Object.entries(query)) {
70
+ if (value !== undefined && String(value).length > 0) {
71
+ url.searchParams.set(key, String(value));
72
+ }
73
+ }
74
+ return url.toString();
75
+ }
76
+ function apiOutcomeValue(outcome) {
77
+ if (outcome.ok) {
78
+ return outcome.data ?? null;
79
+ }
80
+ const err = outcome.error;
81
+ if (!err)
82
+ return null;
83
+ const obj = {};
84
+ obj.status = err.status;
85
+ obj.code = err.code;
86
+ obj.error = err.error;
87
+ if (err.tryThis !== undefined)
88
+ obj.tryThis = err.tryThis;
89
+ if (err.problems !== undefined)
90
+ obj.problems = err.problems;
91
+ if (err.requestId !== undefined)
92
+ obj.requestId = err.requestId;
93
+ return obj;
94
+ }
95
+ async function callApiJson(ctx, params) {
96
+ const url = buildUrl(ctx.baseUrl, params.path, params.query, params.marketplaceId);
97
+ const headers = new Headers({
98
+ Accept: "application/json",
99
+ });
100
+ if (params.apiKey) {
101
+ headers.set("Authorization", `Bearer ${params.apiKey}`);
102
+ }
103
+ if (params.idempotent) {
104
+ headers.set("Idempotency-Key", randomUUID());
105
+ }
106
+ let bodyText;
107
+ if (params.body !== undefined) {
108
+ headers.set("Content-Type", "application/json");
109
+ bodyText = JSON.stringify(params.body);
110
+ }
111
+ let response;
112
+ try {
113
+ response = await ctx.fetch(url, {
114
+ method: params.method,
115
+ headers,
116
+ body: bodyText,
117
+ });
118
+ }
119
+ catch (networkError) {
120
+ return {
121
+ ok: false,
122
+ status: 0,
123
+ error: {
124
+ status: 0,
125
+ code: "NETWORK_ERROR",
126
+ error: redactSecret(networkError instanceof Error ? networkError.message : String(networkError), params.apiKey),
127
+ tryThis: "Check network connectivity and the configured PCIFIC base URL, then try again.",
128
+ },
129
+ };
130
+ }
131
+ const rawText = await response.text();
132
+ let parsed;
133
+ if (rawText.length > 0) {
134
+ try {
135
+ parsed = parseMcpJsonValue(rawText);
136
+ }
137
+ catch {
138
+ parsed = rawText;
139
+ }
140
+ }
141
+ if (response.ok) {
142
+ return { ok: true, status: response.status, data: parsed };
143
+ }
144
+ const obj = isMcpJsonObject(parsed) ? parsed : null;
145
+ const errCode = obj && isMcpString(obj.code) ? obj.code : `HTTP_${response.status}`;
146
+ const errMsg = obj && isMcpString(obj.error)
147
+ ? obj.error
148
+ : `PCIFIC API request failed with HTTP ${response.status}.`;
149
+ const tryThis = obj && isMcpString(obj.tryThis)
150
+ ? obj.tryThis
151
+ : "Check the error code and parameters, then retry.";
152
+ const problems = obj && Array.isArray(obj.problems) ? obj.problems : undefined;
153
+ const requestId = obj && isMcpString(obj.requestId)
154
+ ? obj.requestId
155
+ : (response.headers.get("x-request-id") ?? undefined);
156
+ return {
157
+ ok: false,
158
+ status: response.status,
159
+ error: {
160
+ status: response.status,
161
+ code: errCode,
162
+ error: errMsg,
163
+ tryThis,
164
+ problems,
165
+ requestId,
166
+ },
167
+ };
168
+ }
169
+ function asRecord(value) {
170
+ return isMcpJsonObject(value) ? value : {};
171
+ }
172
+ function asNonEmptyString(value) {
173
+ return isMcpString(value) && value.trim().length > 0 ? value.trim() : undefined;
174
+ }
175
+ function asPositiveNumber(value, fallback) {
176
+ return isMcpNumber(value) && Number.isFinite(value) && value > 0 ? value : fallback;
177
+ }
178
+ export const MCP_TOOLS = [
179
+ {
180
+ name: "pcific_doctor",
181
+ description: "Check test API key identity, permissions, daily cap, usage, and catalogue readiness on PCIFIC.",
182
+ inputSchema: {
183
+ type: "object",
184
+ properties: {
185
+ marketplaceId: {
186
+ type: "string",
187
+ description: "Optional shop ID to scope the catalogue status check.",
188
+ },
189
+ },
190
+ },
191
+ },
192
+ {
193
+ name: "pcific_check_changelog",
194
+ description: "Read PCIFIC API changelog entries from /changelog.txt (no API key required).",
195
+ inputSchema: {
196
+ type: "object",
197
+ properties: {
198
+ since: {
199
+ type: "string",
200
+ description: "Optional YYYY-MM-DD date to filter entries since that date.",
201
+ },
202
+ },
203
+ },
204
+ },
205
+ {
206
+ name: "pcific_get_docs",
207
+ description: "Fetch plain-text PCIFIC documentation (/llms.txt, /docs/<slug>.txt, or /docs/<slug>/quick.txt). No API key required.",
208
+ inputSchema: {
209
+ type: "object",
210
+ properties: {
211
+ slug: {
212
+ type: "string",
213
+ description: "Optional documentation slug such as safeguard, listing-generation, ask-pcific, message-check, dispute-pack, webhooks, or listing-fields-by-hand. Omit for /llms.txt.",
214
+ },
215
+ quick: {
216
+ type: "boolean",
217
+ description: "When true with a slug, fetches /docs/<slug>/quick.txt.",
218
+ },
219
+ },
220
+ },
221
+ },
222
+ {
223
+ name: "pcific_schema_status",
224
+ description: "Inspect the working schema draft categories, diff comparison against published version, and catalogue status.",
225
+ inputSchema: {
226
+ type: "object",
227
+ properties: {
228
+ marketplaceId: { type: "string", description: "Optional shop ID." },
229
+ },
230
+ },
231
+ },
232
+ {
233
+ name: "pcific_test_safeguard",
234
+ description: "Submit a test Safeguard review (POST /api/v1/safeguard/reviews) and poll until done, questions, or failed.",
235
+ inputSchema: {
236
+ type: "object",
237
+ properties: {
238
+ category: { type: "string", description: "Listing category name." },
239
+ listing: { type: "object", description: "Listing fields matching your schema." },
240
+ images: {
241
+ type: "array",
242
+ items: { type: "string" },
243
+ description: "Optional uploaded image IDs.",
244
+ },
245
+ sellerNotes: { type: "string", description: "Optional seller notes." },
246
+ review: { type: "boolean", description: "Whether to include seller review guidance." },
247
+ marketplaceId: { type: "string", description: "Optional shop ID." },
248
+ timeoutMs: { type: "number", description: "Maximum polling wait in milliseconds (default 60000)." },
249
+ pollIntervalMs: { type: "number", description: "Polling interval in milliseconds (default 1000)." },
250
+ },
251
+ required: ["listing"],
252
+ },
253
+ },
254
+ {
255
+ name: "pcific_test_orbit",
256
+ description: "Submit a test Orbit listing run (POST /api/v1/listings) and poll until terminal state or seller questions.",
257
+ inputSchema: {
258
+ type: "object",
259
+ properties: {
260
+ notes: { type: "string", description: "Seller notes describing the item." },
261
+ details: { type: "object", description: "Optional structured item details." },
262
+ images: {
263
+ type: "array",
264
+ items: { type: "string" },
265
+ description: "Optional uploaded image IDs.",
266
+ },
267
+ category: { type: "string", description: "Optional category name." },
268
+ price: { type: "boolean", description: "Whether to estimate price." },
269
+ safeguard: { type: "boolean", description: "Whether to run Safeguard on the draft." },
270
+ marketplaceId: { type: "string", description: "Optional shop ID." },
271
+ timeoutMs: { type: "number", description: "Maximum polling wait in milliseconds (default 60000)." },
272
+ pollIntervalMs: { type: "number", description: "Polling interval in milliseconds (default 1000)." },
273
+ },
274
+ },
275
+ },
276
+ {
277
+ name: "pcific_test_ask",
278
+ description: "Run a test Ask PCIFIC question (POST /api/v1/ask-pcific).",
279
+ inputSchema: {
280
+ type: "object",
281
+ properties: {
282
+ question: { type: "string", description: "Customer question to ask." },
283
+ quotes: { type: "boolean", description: "Include supporting quotes." },
284
+ conversationId: { type: "string", description: "Optional conversation ID." },
285
+ item: { type: "object", description: "Optional item context object." },
286
+ marketplaceId: { type: "string", description: "Optional shop ID." },
287
+ },
288
+ required: ["question"],
289
+ },
290
+ },
291
+ {
292
+ name: "pcific_test_message_check",
293
+ description: "Run a test Message Check call (POST /api/v1/message-check).",
294
+ inputSchema: {
295
+ type: "object",
296
+ properties: {
297
+ text: { type: "string", description: "Message text to check." },
298
+ conversationId: { type: "string", description: "Optional conversation ID." },
299
+ sender: { type: "object", description: "Optional sender metadata." },
300
+ context: { type: "object", description: "Optional conversation context." },
301
+ marketplaceId: { type: "string", description: "Optional shop ID." },
302
+ },
303
+ required: ["text"],
304
+ },
305
+ },
306
+ {
307
+ name: "pcific_list_logs",
308
+ description: "List recent API request logs (GET /api/v1/logs) with optional filters so agents can inspect failures.",
309
+ inputSchema: {
310
+ type: "object",
311
+ properties: {
312
+ limit: { type: "number", description: "Number of logs to return (1 to 100)." },
313
+ tool: {
314
+ type: "string",
315
+ description: "Filter by tool: orbit, safeguard, ask-pcific, pixel-trace, checkup, message-check, dispute-pack, or other.",
316
+ },
317
+ status: { type: "string", description: "Filter by status: failed or succeeded." },
318
+ keyKind: { type: "string", description: "Filter by keyKind: test or live." },
319
+ from: { type: "string", description: "Optional start date (YYYY-MM-DD or ISO 8601)." },
320
+ to: { type: "string", description: "Optional end date (YYYY-MM-DD or ISO 8601)." },
321
+ requestId: { type: "string", description: "Optional exact requestId UUID." },
322
+ marketplaceId: { type: "string", description: "Optional shop ID." },
323
+ },
324
+ },
325
+ },
326
+ {
327
+ name: "pcific_get_log",
328
+ description: "Read one API request log's redacted sent and returned contents (GET /api/v1/logs/{requestId}).",
329
+ inputSchema: {
330
+ type: "object",
331
+ properties: {
332
+ requestId: {
333
+ type: "string",
334
+ description: "The requestId UUID or numeric log row ID from pcific_list_logs or X-Request-Id.",
335
+ },
336
+ },
337
+ required: ["requestId"],
338
+ },
339
+ },
340
+ ];
341
+ export async function executeMcpTool(name, rawArgs, ctx) {
342
+ const args = asRecord(rawArgs);
343
+ const sleep = ctx.sleep ?? defaultSleep;
344
+ const now = ctx.now ?? (() => Date.now());
345
+ const mergedEnv = readMergedEnv(ctx.cwd, ctx.env);
346
+ let resolvedBaseUrl;
347
+ try {
348
+ resolvedBaseUrl = normalizeBaseUrl(ctx.baseUrl || mergedEnv.get("PCIFIC_BASE_URL")?.trim() || DEFAULT_BASE_URL);
349
+ }
350
+ catch (error) {
351
+ if (error instanceof BaseUrlError) {
352
+ return toResult({
353
+ code: error.code,
354
+ error: error.message,
355
+ tryThis: error.tryThis,
356
+ }, true);
357
+ }
358
+ throw error;
359
+ }
360
+ const effectiveCtx = {
361
+ ...ctx,
362
+ baseUrl: resolvedBaseUrl,
363
+ };
364
+ if (name === "pcific_check_changelog") {
365
+ const since = asNonEmptyString(args.since);
366
+ const url = buildUrl(effectiveCtx.baseUrl, "/changelog.txt", { since });
367
+ try {
368
+ const response = await ctx.fetch(url, {
369
+ method: "GET",
370
+ headers: { Accept: "text/plain" },
371
+ });
372
+ const text = await response.text();
373
+ if (!response.ok) {
374
+ return toResult({
375
+ status: response.status,
376
+ code: `HTTP_${response.status}`,
377
+ error: `Could not read changelog from ${url}.`,
378
+ tryThis: "Check the date format (YYYY-MM-DD) or try without the since filter.",
379
+ body: text,
380
+ }, true);
381
+ }
382
+ return toResult({ url, since: since ?? null, changelog: text });
383
+ }
384
+ catch (error) {
385
+ return toResult({
386
+ code: "NETWORK_ERROR",
387
+ error: error instanceof Error ? error.message : String(error),
388
+ tryThis: "Check network connectivity and try again.",
389
+ }, true);
390
+ }
391
+ }
392
+ if (name === "pcific_get_docs") {
393
+ const slug = asNonEmptyString(args.slug);
394
+ const quick = args.quick === true;
395
+ let docPath = "/llms.txt";
396
+ if (slug && slug !== "llms") {
397
+ if (!/^[a-z0-9][a-z0-9_-]*$/iu.test(slug)) {
398
+ return toResult({
399
+ code: "INVALID_DOC_SLUG",
400
+ error: `Invalid documentation slug "${slug}".`,
401
+ tryThis: 'Use a plain doc slug containing only letters, numbers, hyphens, or underscores (for example "safeguard" or "webhooks"), or omit slug to read /llms.txt.',
402
+ }, true);
403
+ }
404
+ docPath = quick ? `/docs/${slug}/quick.txt` : `/docs/${slug}.txt`;
405
+ }
406
+ const url = buildUrl(effectiveCtx.baseUrl, docPath);
407
+ try {
408
+ const response = await ctx.fetch(url, {
409
+ method: "GET",
410
+ headers: { Accept: "text/plain" },
411
+ });
412
+ const text = await response.text();
413
+ if (!response.ok) {
414
+ return toResult({
415
+ status: response.status,
416
+ code: `HTTP_${response.status}`,
417
+ error: `Could not load documentation at ${docPath}.`,
418
+ tryThis: "Call pcific_get_docs without a slug to inspect /llms.txt for valid doc slugs.",
419
+ body: text,
420
+ }, true);
421
+ }
422
+ return toResult({ path: docPath, content: text });
423
+ }
424
+ catch (error) {
425
+ return toResult({
426
+ code: "NETWORK_ERROR",
427
+ error: error instanceof Error ? error.message : String(error),
428
+ tryThis: "Check network connectivity and try again.",
429
+ }, true);
430
+ }
431
+ }
432
+ const auth = resolveMcpTestKey(ctx.cwd, ctx.env);
433
+ if (auth.error || !auth.apiKey) {
434
+ return toResult({
435
+ code: "TEST_KEY_REQUIRED",
436
+ error: auth.error ?? "Missing PCIFIC_TEST_KEY.",
437
+ tryThis: "Set PCIFIC_TEST_KEY to a pcific_test_* key in your environment or .env file.",
438
+ }, true);
439
+ }
440
+ const apiKey = auth.apiKey;
441
+ const marketplaceId = asNonEmptyString(args.marketplaceId) ?? auth.marketplaceId;
442
+ if (name === "pcific_doctor") {
443
+ const [keyRes, usageRes, catalogueRes] = await Promise.all([
444
+ callApiJson(effectiveCtx, { method: "GET", path: "/api/v1/key", apiKey }),
445
+ callApiJson(effectiveCtx, { method: "GET", path: "/api/v1/usage", apiKey, marketplaceId }),
446
+ callApiJson(effectiveCtx, { method: "GET", path: "/api/v1/catalogue/status", apiKey, marketplaceId }),
447
+ ]);
448
+ const hasError = !keyRes.ok || !usageRes.ok || !catalogueRes.ok;
449
+ return toResult({
450
+ ok: !hasError,
451
+ key: apiOutcomeValue(keyRes),
452
+ usage: apiOutcomeValue(usageRes),
453
+ catalogue: apiOutcomeValue(catalogueRes),
454
+ }, hasError, apiKey);
455
+ }
456
+ if (name === "pcific_schema_status") {
457
+ const [draftRes, catalogueRes] = await Promise.all([
458
+ callApiJson(effectiveCtx, { method: "GET", path: "/api/v1/schema-draft", apiKey, marketplaceId }),
459
+ callApiJson(effectiveCtx, { method: "GET", path: "/api/v1/catalogue/status", apiKey, marketplaceId }),
460
+ ]);
461
+ const hasError = !draftRes.ok || !catalogueRes.ok;
462
+ return toResult({
463
+ ok: !hasError,
464
+ draft: apiOutcomeValue(draftRes),
465
+ catalogue: apiOutcomeValue(catalogueRes),
466
+ }, hasError, apiKey);
467
+ }
468
+ if (name === "pcific_test_safeguard") {
469
+ const body = {};
470
+ for (const field of [
471
+ "category",
472
+ "listing",
473
+ "images",
474
+ "requirePhotos",
475
+ "sellerNotes",
476
+ "orbitRunId",
477
+ "review",
478
+ "faq",
479
+ "rewrite",
480
+ "modelTier",
481
+ "listingRef",
482
+ ]) {
483
+ const value = args[field];
484
+ if (value !== undefined)
485
+ body[field] = value;
486
+ }
487
+ const createRes = await callApiJson(effectiveCtx, {
488
+ method: "POST",
489
+ path: "/api/v1/safeguard/reviews",
490
+ apiKey,
491
+ marketplaceId,
492
+ body,
493
+ idempotent: true,
494
+ });
495
+ if (!createRes.ok) {
496
+ return toResult(createRes.error, true, apiKey);
497
+ }
498
+ const created = asRecord(createRes.data);
499
+ const reviewId = asNonEmptyString(created.reviewId) ?? asNonEmptyString(created.id);
500
+ const initialStatus = asNonEmptyString(created.status);
501
+ if (!reviewId || (initialStatus && SAFEGUARD_TERMINAL.has(initialStatus))) {
502
+ return toResult(created, initialStatus === "failed", apiKey);
503
+ }
504
+ const timeoutMs = asPositiveNumber(args.timeoutMs, 60_000);
505
+ const pollIntervalMs = asPositiveNumber(args.pollIntervalMs, 1_000);
506
+ const deadline = now() + timeoutMs;
507
+ while (true) {
508
+ const pollRes = await callApiJson(effectiveCtx, {
509
+ method: "GET",
510
+ path: `/api/v1/safeguard/reviews/${encodeURIComponent(reviewId)}`,
511
+ apiKey,
512
+ marketplaceId,
513
+ });
514
+ if (!pollRes.ok) {
515
+ return toResult(pollRes.error, true, apiKey);
516
+ }
517
+ const snapshot = asRecord(pollRes.data);
518
+ const status = asNonEmptyString(snapshot.status) ?? "";
519
+ if (SAFEGUARD_TERMINAL.has(status)) {
520
+ return toResult(snapshot, status === "failed", apiKey);
521
+ }
522
+ if (now() >= deadline) {
523
+ return toResult({
524
+ timedOut: true,
525
+ reviewId,
526
+ lastSnapshot: snapshot,
527
+ tryThis: `Poll GET /api/v1/safeguard/reviews/${reviewId} again or pass a higher timeoutMs.`,
528
+ }, true, apiKey);
529
+ }
530
+ await sleep(pollIntervalMs);
531
+ }
532
+ }
533
+ if (name === "pcific_test_orbit") {
534
+ const body = {};
535
+ for (const field of [
536
+ "notes",
537
+ "details",
538
+ "images",
539
+ "category",
540
+ "price",
541
+ "safeguard",
542
+ "faq",
543
+ "modelTier",
544
+ "listingRef",
545
+ "editChat",
546
+ ]) {
547
+ const value = args[field];
548
+ if (value !== undefined)
549
+ body[field] = value;
550
+ }
551
+ const createRes = await callApiJson(effectiveCtx, {
552
+ method: "POST",
553
+ path: "/api/v1/listings",
554
+ apiKey,
555
+ marketplaceId,
556
+ body,
557
+ idempotent: true,
558
+ });
559
+ if (!createRes.ok) {
560
+ return toResult(createRes.error, true, apiKey);
561
+ }
562
+ const created = asRecord(createRes.data);
563
+ const runId = asNonEmptyString(created.runId) ?? asNonEmptyString(created.id);
564
+ const initialStatus = asNonEmptyString(created.status);
565
+ if (!runId || (initialStatus && ORBIT_TERMINAL.has(initialStatus) && created.processing !== true)) {
566
+ return toResult(created, initialStatus === "failed", apiKey);
567
+ }
568
+ const timeoutMs = asPositiveNumber(args.timeoutMs, 60_000);
569
+ const pollIntervalMs = asPositiveNumber(args.pollIntervalMs, 1_000);
570
+ const deadline = now() + timeoutMs;
571
+ while (true) {
572
+ const pollRes = await callApiJson(effectiveCtx, {
573
+ method: "GET",
574
+ path: `/api/v1/listings/${encodeURIComponent(runId)}`,
575
+ apiKey,
576
+ marketplaceId,
577
+ });
578
+ if (!pollRes.ok) {
579
+ return toResult(pollRes.error, true, apiKey);
580
+ }
581
+ const snapshot = asRecord(pollRes.data);
582
+ const status = asNonEmptyString(snapshot.status) ?? "";
583
+ if (ORBIT_TERMINAL.has(status) && snapshot.processing !== true) {
584
+ return toResult(snapshot, status === "failed", apiKey);
585
+ }
586
+ if (now() >= deadline) {
587
+ return toResult({
588
+ timedOut: true,
589
+ runId,
590
+ lastSnapshot: snapshot,
591
+ tryThis: `Poll GET /api/v1/listings/${runId} again or pass a higher timeoutMs.`,
592
+ }, true, apiKey);
593
+ }
594
+ await sleep(pollIntervalMs);
595
+ }
596
+ }
597
+ if (name === "pcific_test_ask") {
598
+ const question = asNonEmptyString(args.question);
599
+ if (!question) {
600
+ return toResult({
601
+ code: "INVALID_FIELD",
602
+ error: "question is required.",
603
+ tryThis: 'Provide a non-empty "question" string.',
604
+ }, true, apiKey);
605
+ }
606
+ const body = {};
607
+ body.question = question;
608
+ for (const field of ["quotes", "modelTier", "conversationId", "buyer", "item"]) {
609
+ const value = args[field];
610
+ if (value !== undefined)
611
+ body[field] = value;
612
+ }
613
+ const res = await callApiJson(effectiveCtx, {
614
+ method: "POST",
615
+ path: "/api/v1/ask-pcific",
616
+ apiKey,
617
+ marketplaceId,
618
+ body,
619
+ idempotent: true,
620
+ });
621
+ return toResult(res.ok ? res.data : res.error, !res.ok, apiKey);
622
+ }
623
+ if (name === "pcific_test_message_check") {
624
+ const text = asNonEmptyString(args.text);
625
+ if (!text) {
626
+ return toResult({
627
+ code: "INVALID_FIELD",
628
+ error: "text is required.",
629
+ tryThis: 'Provide a non-empty "text" string to check.',
630
+ }, true, apiKey);
631
+ }
632
+ const body = {};
633
+ body.text = text;
634
+ for (const field of ["conversationId", "sender", "context", "confirmToken", "metadata"]) {
635
+ const value = args[field];
636
+ if (value !== undefined)
637
+ body[field] = value;
638
+ }
639
+ const res = await callApiJson(effectiveCtx, {
640
+ method: "POST",
641
+ path: "/api/v1/message-check",
642
+ apiKey,
643
+ marketplaceId,
644
+ body,
645
+ idempotent: true,
646
+ });
647
+ return toResult(res.ok ? res.data : res.error, !res.ok, apiKey);
648
+ }
649
+ if (name === "pcific_list_logs") {
650
+ const query = {
651
+ limit: isMcpNumber(args.limit) ? args.limit : undefined,
652
+ tool: asNonEmptyString(args.tool),
653
+ status: asNonEmptyString(args.status),
654
+ keyKind: asNonEmptyString(args.keyKind),
655
+ from: asNonEmptyString(args.from),
656
+ to: asNonEmptyString(args.to),
657
+ requestId: asNonEmptyString(args.requestId),
658
+ };
659
+ const res = await callApiJson(effectiveCtx, {
660
+ method: "GET",
661
+ path: "/api/v1/logs",
662
+ apiKey,
663
+ marketplaceId,
664
+ query,
665
+ });
666
+ return toResult(res.ok ? res.data : res.error, !res.ok, apiKey);
667
+ }
668
+ if (name === "pcific_get_log") {
669
+ const requestId = asNonEmptyString(args.requestId);
670
+ if (!requestId) {
671
+ return toResult({
672
+ code: "INVALID_FIELD",
673
+ error: "requestId is required.",
674
+ tryThis: "Pass a requestId UUID or log row number returned by pcific_list_logs.",
675
+ }, true, apiKey);
676
+ }
677
+ const res = await callApiJson(effectiveCtx, {
678
+ method: "GET",
679
+ path: `/api/v1/logs/${encodeURIComponent(requestId)}`,
680
+ apiKey,
681
+ });
682
+ return toResult(res.ok ? res.data : res.error, !res.ok, apiKey);
683
+ }
684
+ return toResult({
685
+ code: "UNKNOWN_TOOL",
686
+ error: `Unknown MCP tool "${name}".`,
687
+ tryThis: "Call tools/list to see the supported PCIFIC MCP tools.",
688
+ }, true, apiKey);
689
+ }