@webhooks-cc/mcp 0.3.0 → 1.0.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.
package/dist/index.js CHANGED
@@ -21,102 +21,589 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  createServer: () => createServer,
24
+ registerPrompts: () => registerPrompts,
25
+ registerResources: () => registerResources,
24
26
  registerTools: () => registerTools
25
27
  });
26
28
  module.exports = __toCommonJS(index_exports);
29
+ var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
30
+ var import_sdk2 = require("@webhooks-cc/sdk");
31
+
32
+ // src/prompts.ts
33
+ var import_zod = require("zod");
34
+ function registerPrompts(server) {
35
+ server.registerPrompt(
36
+ "debug_webhook_delivery",
37
+ {
38
+ title: "Debug Webhook Delivery",
39
+ description: "Guide an agent through diagnosing why webhook delivery is failing or missing.",
40
+ argsSchema: {
41
+ provider: import_zod.z.string().optional().describe("Webhook provider, if known"),
42
+ endpointSlug: import_zod.z.string().optional().describe("Hosted endpoint slug, if known"),
43
+ targetUrl: import_zod.z.string().optional().describe("Your app's receiving URL, if known")
44
+ }
45
+ },
46
+ async ({ provider, endpointSlug, targetUrl }) => {
47
+ const scope = [
48
+ provider ? `Provider: ${provider}.` : null,
49
+ endpointSlug ? `Endpoint slug: ${endpointSlug}.` : null,
50
+ targetUrl ? `Target URL: ${targetUrl}.` : null
51
+ ].filter(Boolean).join(" ");
52
+ return {
53
+ description: "Diagnose a missing or broken webhook delivery.",
54
+ messages: [
55
+ {
56
+ role: "user",
57
+ content: {
58
+ type: "text",
59
+ text: [
60
+ scope,
61
+ "Diagnose webhook delivery step by step.",
62
+ "Use list_endpoints or get_endpoint to confirm the endpoint and URL.",
63
+ "Use list_requests, wait_for_request, or wait_for_requests to check whether anything arrived.",
64
+ "If the provider is known, use preview_webhook or send_webhook to reproduce the webhook with realistic signing.",
65
+ "Use verify_signature when a secret is available.",
66
+ "Use compare_requests to compare retries or changed payloads.",
67
+ "Conclude with the most likely cause and the next concrete fix."
68
+ ].filter(Boolean).join(" ")
69
+ }
70
+ }
71
+ ]
72
+ };
73
+ }
74
+ );
75
+ server.registerPrompt(
76
+ "setup_provider_testing",
77
+ {
78
+ title: "Setup Provider Testing",
79
+ description: "Guide an agent through setting up webhook testing for a provider.",
80
+ argsSchema: {
81
+ provider: import_zod.z.string().describe("Webhook provider to test"),
82
+ targetUrl: import_zod.z.string().optional().describe("Optional local or remote target URL")
83
+ }
84
+ },
85
+ async ({ provider, targetUrl }) => {
86
+ return {
87
+ description: `Set up webhook testing for ${provider}.`,
88
+ messages: [
89
+ {
90
+ role: "user",
91
+ content: {
92
+ type: "text",
93
+ text: [
94
+ `Set up webhook testing for ${provider}.`,
95
+ "Use list_provider_templates to inspect supported templates and signing details first.",
96
+ "Create an endpoint with create_endpoint, preferably ephemeral.",
97
+ "If a target URL is provided, use preview_webhook before send_to so the request shape is visible.",
98
+ targetUrl ? `Target URL: ${targetUrl}.` : null,
99
+ "Send a realistic provider webhook, wait for capture, and verify the signature if a secret is available.",
100
+ "Return the endpoint URL, the exact tools used, and the next step for the developer."
101
+ ].filter(Boolean).join(" ")
102
+ }
103
+ }
104
+ ]
105
+ };
106
+ }
107
+ );
108
+ server.registerPrompt(
109
+ "compare_webhook_attempts",
110
+ {
111
+ title: "Compare Webhook Attempts",
112
+ description: "Guide an agent through comparing two webhook deliveries or retries.",
113
+ argsSchema: {
114
+ endpointSlug: import_zod.z.string().optional().describe("Endpoint slug to inspect for recent attempts"),
115
+ leftRequestId: import_zod.z.string().optional().describe("First request ID, if already known"),
116
+ rightRequestId: import_zod.z.string().optional().describe("Second request ID, if already known")
117
+ }
118
+ },
119
+ async ({ endpointSlug, leftRequestId, rightRequestId }) => {
120
+ return {
121
+ description: "Compare two webhook deliveries and explain the difference.",
122
+ messages: [
123
+ {
124
+ role: "user",
125
+ content: {
126
+ type: "text",
127
+ text: [
128
+ endpointSlug ? `Endpoint slug: ${endpointSlug}.` : null,
129
+ leftRequestId && rightRequestId ? `Compare request ${leftRequestId} against ${rightRequestId}.` : "Find the most relevant two webhook attempts first.",
130
+ "Use compare_requests for the structured diff.",
131
+ "If request IDs are not provided, use list_requests or the endpoint recent resource to find the last two attempts.",
132
+ "Explain what changed in the body, headers, or timing, and whether the difference looks expected, retried, or broken."
133
+ ].filter(Boolean).join(" ")
134
+ }
135
+ }
136
+ ]
137
+ };
138
+ }
139
+ );
140
+ }
141
+
142
+ // src/resources.ts
27
143
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
28
- var import_sdk = require("@webhooks-cc/sdk");
144
+ var ENDPOINTS_RESOURCE_URI = "webhooks://endpoints";
145
+ var ENDPOINT_RECENT_TEMPLATE_URI = "webhooks://endpoint/{slug}/recent";
146
+ var REQUEST_TEMPLATE_URI = "webhooks://request/{id}";
147
+ var MAX_ENDPOINT_RESOURCE_ITEMS = 25;
148
+ var RECENT_REQUEST_LIMIT = 10;
149
+ function jsonResource(uri, value) {
150
+ return {
151
+ contents: [
152
+ {
153
+ uri,
154
+ mimeType: "application/json",
155
+ text: JSON.stringify(value, null, 2)
156
+ }
157
+ ]
158
+ };
159
+ }
160
+ function summarizeRequest(request) {
161
+ return {
162
+ id: request.id,
163
+ method: request.method,
164
+ path: request.path,
165
+ receivedAt: request.receivedAt,
166
+ contentType: request.contentType ?? null
167
+ };
168
+ }
169
+ function variableToString(value, name) {
170
+ if (typeof value === "string" && value.length > 0) {
171
+ return value;
172
+ }
173
+ throw new Error(`Missing resource variable "${name}"`);
174
+ }
175
+ async function listEndpointSummaries(client) {
176
+ const endpoints = (await client.endpoints.list()).slice().sort((left, right) => right.createdAt - left.createdAt);
177
+ const truncated = endpoints.length > MAX_ENDPOINT_RESOURCE_ITEMS;
178
+ const visible = endpoints.slice(0, MAX_ENDPOINT_RESOURCE_ITEMS);
179
+ const summaries = await Promise.all(
180
+ visible.map(async (endpoint) => {
181
+ const recent = await client.requests.list(endpoint.slug, { limit: 1 });
182
+ return {
183
+ ...endpoint,
184
+ lastRequest: recent[0] ? summarizeRequest(recent[0]) : null
185
+ };
186
+ })
187
+ );
188
+ return {
189
+ endpoints: summaries,
190
+ total: endpoints.length,
191
+ truncated
192
+ };
193
+ }
194
+ function registerResources(server, client) {
195
+ server.registerResource(
196
+ "endpoints-overview",
197
+ ENDPOINTS_RESOURCE_URI,
198
+ {
199
+ title: "Endpoints Overview",
200
+ description: "All endpoints with a summary of recent activity.",
201
+ mimeType: "application/json"
202
+ },
203
+ async () => {
204
+ return jsonResource(ENDPOINTS_RESOURCE_URI, await listEndpointSummaries(client));
205
+ }
206
+ );
207
+ server.registerResource(
208
+ "endpoint-recent-requests",
209
+ new import_mcp.ResourceTemplate(ENDPOINT_RECENT_TEMPLATE_URI, {
210
+ list: async () => {
211
+ const endpoints = await client.endpoints.list();
212
+ return {
213
+ resources: endpoints.map((endpoint) => ({
214
+ uri: `webhooks://endpoint/${endpoint.slug}/recent`,
215
+ name: `${endpoint.slug} recent requests`,
216
+ description: `Recent requests for endpoint ${endpoint.slug}`,
217
+ mimeType: "application/json"
218
+ }))
219
+ };
220
+ },
221
+ complete: {
222
+ slug: async (value) => {
223
+ const endpoints = await client.endpoints.list();
224
+ return endpoints.map((endpoint) => endpoint.slug).filter((slug) => slug.startsWith(value)).slice(0, 20);
225
+ }
226
+ }
227
+ }),
228
+ {
229
+ title: "Endpoint Recent Requests",
230
+ description: "Last 10 captured requests for an endpoint.",
231
+ mimeType: "application/json"
232
+ },
233
+ async (uri, variables) => {
234
+ const slug = variableToString(variables.slug, "slug");
235
+ const [endpoint, requests] = await Promise.all([
236
+ client.endpoints.get(slug),
237
+ client.requests.list(slug, { limit: RECENT_REQUEST_LIMIT })
238
+ ]);
239
+ return jsonResource(uri.toString(), {
240
+ endpoint,
241
+ requests
242
+ });
243
+ }
244
+ );
245
+ server.registerResource(
246
+ "request-details",
247
+ new import_mcp.ResourceTemplate(REQUEST_TEMPLATE_URI, {
248
+ list: void 0,
249
+ complete: {}
250
+ }),
251
+ {
252
+ title: "Request Details",
253
+ description: "Full details for a captured request by ID.",
254
+ mimeType: "application/json"
255
+ },
256
+ async (uri, variables) => {
257
+ const id = variableToString(variables.id, "id");
258
+ const request = await client.requests.get(id);
259
+ return jsonResource(uri.toString(), request);
260
+ }
261
+ );
262
+ }
29
263
 
30
264
  // src/tools.ts
31
- var import_zod = require("zod");
265
+ var import_zod2 = require("zod");
266
+ var import_sdk = require("@webhooks-cc/sdk");
32
267
  var MAX_BODY_SIZE = 32768;
268
+ var HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
269
+ var TEMPLATE_PROVIDER_VALUES = [
270
+ "stripe",
271
+ "github",
272
+ "shopify",
273
+ "twilio",
274
+ "slack",
275
+ "paddle",
276
+ "linear",
277
+ "standard-webhooks"
278
+ ];
279
+ var VERIFY_PROVIDER_VALUES = [
280
+ ...TEMPLATE_PROVIDER_VALUES,
281
+ "discord"
282
+ ];
283
+ var TIME_SEPARATOR = " \u2014 ";
284
+ var httpUrlSchema = import_zod2.z.string().url().refine(
285
+ (value) => {
286
+ try {
287
+ const protocol = new URL(value).protocol;
288
+ return protocol === "http:" || protocol === "https:";
289
+ } catch {
290
+ return false;
291
+ }
292
+ },
293
+ { message: "Only http and https URLs are supported" }
294
+ );
295
+ var methodSchema = import_zod2.z.enum(HTTP_METHODS).default("POST").describe("HTTP method (default: POST)");
296
+ var durationOrTimestampSchema = import_zod2.z.union([import_zod2.z.string(), import_zod2.z.number()]);
297
+ var mockResponseSchema = import_zod2.z.object({
298
+ status: import_zod2.z.number().int().min(100).max(599).describe("HTTP status code (100-599)"),
299
+ body: import_zod2.z.string().default("").describe("Response body string (default: empty)"),
300
+ headers: import_zod2.z.record(import_zod2.z.string()).default({}).describe("Response headers (default: none)")
301
+ });
33
302
  function textContent(text) {
34
303
  return { content: [{ type: "text", text }] };
35
304
  }
305
+ function serializeJson(value, limit = MAX_BODY_SIZE) {
306
+ const full = JSON.stringify(value, null, 2);
307
+ if (full.length <= limit) {
308
+ return full;
309
+ }
310
+ if (Array.isArray(value)) {
311
+ let low = 0;
312
+ let high = value.length;
313
+ let best = JSON.stringify(
314
+ { items: [], truncated: true, total: value.length, returned: 0 },
315
+ null,
316
+ 2
317
+ );
318
+ while (low <= high) {
319
+ const mid = Math.floor((low + high) / 2);
320
+ const candidate = JSON.stringify(
321
+ {
322
+ items: value.slice(0, mid),
323
+ truncated: true,
324
+ total: value.length,
325
+ returned: mid
326
+ },
327
+ null,
328
+ 2
329
+ );
330
+ if (candidate.length <= limit) {
331
+ best = candidate;
332
+ low = mid + 1;
333
+ } else {
334
+ high = mid - 1;
335
+ }
336
+ }
337
+ return best;
338
+ }
339
+ return full.slice(0, limit) + `
340
+ ... [truncated, ${full.length} chars total]`;
341
+ }
342
+ function jsonContent(value) {
343
+ return textContent(serializeJson(value));
344
+ }
36
345
  async function readBodyTruncated(response, limit = MAX_BODY_SIZE) {
37
346
  const text = await response.text();
38
347
  if (text.length <= limit) return text;
39
348
  return text.slice(0, limit) + `
40
349
  ... [truncated, ${text.length} chars total]`;
41
350
  }
351
+ function sleep(ms) {
352
+ return new Promise((resolve) => setTimeout(resolve, ms));
353
+ }
354
+ function splitHint(message) {
355
+ const separatorIndex = message.indexOf(TIME_SEPARATOR);
356
+ if (separatorIndex === -1) {
357
+ return { message, hint: null };
358
+ }
359
+ return {
360
+ message: message.slice(0, separatorIndex),
361
+ hint: message.slice(separatorIndex + TIME_SEPARATOR.length) || null
362
+ };
363
+ }
364
+ function serializeError(error) {
365
+ const rawMessage = error instanceof Error ? error.message : String(error);
366
+ const { message, hint } = splitHint(rawMessage);
367
+ const payload = {
368
+ error: true,
369
+ code: "validation_error",
370
+ message,
371
+ hint,
372
+ retryAfter: null
373
+ };
374
+ if (error instanceof import_sdk.UnauthorizedError) {
375
+ payload.code = "unauthorized";
376
+ } else if (error instanceof import_sdk.NotFoundError) {
377
+ payload.code = "not_found";
378
+ } else if (error instanceof import_sdk.RateLimitError) {
379
+ payload.code = "rate_limited";
380
+ payload.retryAfter = error.retryAfter ?? null;
381
+ } else if (error instanceof import_sdk.TimeoutError) {
382
+ payload.code = "timeout";
383
+ } else if (error instanceof import_sdk.WebhooksCCError) {
384
+ payload.code = error.statusCode >= 500 ? "server_error" : "validation_error";
385
+ }
386
+ return JSON.stringify(payload, null, 2);
387
+ }
42
388
  function withErrorHandling(handler) {
43
389
  return async (args) => {
44
390
  try {
45
391
  return await handler(args);
46
392
  } catch (error) {
47
- const message = error instanceof Error ? error.message : String(error);
48
- return { ...textContent(`Error: ${message}`), isError: true };
393
+ return { ...textContent(serializeError(error)), isError: true };
49
394
  }
50
395
  };
51
396
  }
397
+ function filterRequestsByMethod(requests, method) {
398
+ if (!method) {
399
+ return requests;
400
+ }
401
+ const target = method.toUpperCase();
402
+ return requests.filter((request) => request.method.toUpperCase() === target);
403
+ }
404
+ async function waitForMultipleRequests(client, endpointSlug, options) {
405
+ const timeoutMs = typeof options.timeout === "number" ? options.timeout : options.timeout ? Number.isNaN(Number(options.timeout)) ? parseDurationLike(options.timeout) : Number(options.timeout) : 3e4;
406
+ const pollIntervalMs = typeof options.pollInterval === "number" ? options.pollInterval : options.pollInterval ? Number.isNaN(Number(options.pollInterval)) ? parseDurationLike(options.pollInterval) : Number(options.pollInterval) : 500;
407
+ const startedAt = Date.now();
408
+ let since = startedAt;
409
+ const seenIds = /* @__PURE__ */ new Set();
410
+ const requests = [];
411
+ while (Date.now() - startedAt < timeoutMs) {
412
+ const checkTime = Date.now();
413
+ const page = await client.requests.list(endpointSlug, {
414
+ since,
415
+ limit: Math.max(100, options.count * 5)
416
+ });
417
+ since = checkTime;
418
+ const filtered = filterRequestsByMethod(page, options.method).slice().sort((left, right) => left.receivedAt - right.receivedAt);
419
+ for (const request of filtered) {
420
+ if (seenIds.has(request.id)) {
421
+ continue;
422
+ }
423
+ seenIds.add(request.id);
424
+ requests.push(request);
425
+ if (requests.length >= options.count) {
426
+ return {
427
+ requests,
428
+ complete: true,
429
+ timedOut: false,
430
+ expectedCount: options.count
431
+ };
432
+ }
433
+ }
434
+ await sleep(Math.max(10, pollIntervalMs));
435
+ }
436
+ return {
437
+ requests,
438
+ complete: requests.length >= options.count,
439
+ timedOut: true,
440
+ expectedCount: options.count
441
+ };
442
+ }
443
+ function parseDurationLike(value) {
444
+ const trimmed = value.trim();
445
+ if (trimmed.length === 0) {
446
+ throw new Error("Duration value cannot be empty");
447
+ }
448
+ const numeric = Number(trimmed);
449
+ if (!Number.isNaN(numeric)) {
450
+ return numeric;
451
+ }
452
+ const match = trimmed.match(/^(\d+)\s*(ms|s|m|h|d)$/i);
453
+ if (!match) {
454
+ throw new Error(`Invalid duration: "${value}"`);
455
+ }
456
+ const amount = Number(match[1]);
457
+ const unit = match[2].toLowerCase();
458
+ const multiplier = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
459
+ return amount * multiplier;
460
+ }
461
+ function ensureVerifyArgs(args) {
462
+ if (args.provider === "discord") {
463
+ const publicKey = args.publicKey?.trim();
464
+ if (!publicKey) {
465
+ throw new Error('verify_signature for provider "discord" requires publicKey');
466
+ }
467
+ return {
468
+ provider: "discord",
469
+ publicKey
470
+ };
471
+ }
472
+ const secret = args.secret?.trim();
473
+ if (!secret) {
474
+ throw new Error(`verify_signature for provider "${args.provider}" requires secret`);
475
+ }
476
+ return {
477
+ provider: args.provider,
478
+ secret,
479
+ ...args.url ? { url: args.url } : {}
480
+ };
481
+ }
482
+ async function summarizeResponse(response) {
483
+ return {
484
+ status: response.status,
485
+ statusText: response.statusText,
486
+ body: await readBodyTruncated(response)
487
+ };
488
+ }
52
489
  function registerTools(server, client) {
53
490
  server.tool(
54
491
  "create_endpoint",
55
- "Create a new webhook endpoint. Returns the endpoint URL and slug.",
56
- { name: import_zod.z.string().optional().describe("Display name for the endpoint") },
57
- withErrorHandling(async ({ name }) => {
58
- const endpoint = await client.endpoints.create({ name });
59
- return textContent(JSON.stringify(endpoint, null, 2));
492
+ "Create a webhook endpoint. Returns the endpoint slug, URL, and metadata.",
493
+ {
494
+ name: import_zod2.z.string().optional().describe("Display name for the endpoint"),
495
+ ephemeral: import_zod2.z.boolean().optional().describe("Create a temporary endpoint that auto-expires"),
496
+ expiresIn: durationOrTimestampSchema.optional().describe('Auto-expire after this duration, for example "12h"'),
497
+ mockResponse: mockResponseSchema.optional().describe("Optional mock response to return when the endpoint receives a request")
498
+ },
499
+ withErrorHandling(async ({ name, ephemeral, expiresIn, mockResponse }) => {
500
+ const endpoint = await client.endpoints.create({ name, ephemeral, expiresIn, mockResponse });
501
+ return jsonContent(endpoint);
60
502
  })
61
503
  );
62
504
  server.tool(
63
505
  "list_endpoints",
64
- "List all webhook endpoints for the authenticated user. Returns an array of endpoints with their slugs, names, and URLs.",
506
+ "List all webhook endpoints for the authenticated user.",
65
507
  {},
66
508
  withErrorHandling(async () => {
67
509
  const endpoints = await client.endpoints.list();
68
- return textContent(JSON.stringify(endpoints, null, 2));
510
+ return jsonContent(endpoints);
69
511
  })
70
512
  );
71
513
  server.tool(
72
514
  "get_endpoint",
73
- "Get details for a specific webhook endpoint by its slug.",
74
- { slug: import_zod.z.string().describe("The endpoint slug (from the URL)") },
515
+ "Get details for a specific webhook endpoint by slug.",
516
+ { slug: import_zod2.z.string().describe("The endpoint slug") },
75
517
  withErrorHandling(async ({ slug }) => {
76
518
  const endpoint = await client.endpoints.get(slug);
77
- return textContent(JSON.stringify(endpoint, null, 2));
519
+ return jsonContent(endpoint);
78
520
  })
79
521
  );
80
522
  server.tool(
81
523
  "update_endpoint",
82
- "Update an endpoint's name or mock response configuration.",
524
+ "Update an endpoint name or mock response configuration.",
83
525
  {
84
- slug: import_zod.z.string().describe("The endpoint slug to update"),
85
- name: import_zod.z.string().optional().describe("New display name"),
86
- mockResponse: import_zod.z.object({
87
- status: import_zod.z.number().min(100).max(599).describe("HTTP status code (100-599)"),
88
- body: import_zod.z.string().default("").describe("Response body string (default: empty)"),
89
- headers: import_zod.z.record(import_zod.z.string()).default({}).describe("Response headers (default: none)")
90
- }).nullable().optional().describe("Mock response config, or null to clear it")
526
+ slug: import_zod2.z.string().describe("The endpoint slug to update"),
527
+ name: import_zod2.z.string().optional().describe("New display name"),
528
+ mockResponse: mockResponseSchema.nullable().optional().describe("Mock response config, or null to clear it")
91
529
  },
92
530
  withErrorHandling(async ({ slug, name, mockResponse }) => {
93
531
  const endpoint = await client.endpoints.update(slug, { name, mockResponse });
94
- return textContent(JSON.stringify(endpoint, null, 2));
532
+ return jsonContent(endpoint);
95
533
  })
96
534
  );
97
535
  server.tool(
98
536
  "delete_endpoint",
99
537
  "Delete a webhook endpoint and all its captured requests.",
100
- { slug: import_zod.z.string().describe("The endpoint slug to delete") },
538
+ { slug: import_zod2.z.string().describe("The endpoint slug to delete") },
101
539
  withErrorHandling(async ({ slug }) => {
102
540
  await client.endpoints.delete(slug);
103
541
  return textContent(`Endpoint "${slug}" deleted.`);
104
542
  })
105
543
  );
544
+ server.tool(
545
+ "create_endpoints",
546
+ "Create multiple webhook endpoints in one call.",
547
+ {
548
+ count: import_zod2.z.number().int().min(1).max(20).describe("Number of endpoints to create"),
549
+ namePrefix: import_zod2.z.string().optional().describe("Optional prefix for endpoint names"),
550
+ ephemeral: import_zod2.z.boolean().optional().describe("Create temporary endpoints that auto-expire"),
551
+ expiresIn: durationOrTimestampSchema.optional().describe('Auto-expire after this duration, for example "12h"')
552
+ },
553
+ withErrorHandling(async ({ count, namePrefix, ephemeral, expiresIn }) => {
554
+ const endpoints = await Promise.all(
555
+ Array.from(
556
+ { length: count },
557
+ (_, index) => client.endpoints.create({
558
+ name: namePrefix ? `${namePrefix}-${index + 1}` : void 0,
559
+ ephemeral,
560
+ expiresIn
561
+ })
562
+ )
563
+ );
564
+ return jsonContent({ endpoints });
565
+ })
566
+ );
567
+ server.tool(
568
+ "delete_endpoints",
569
+ "Delete multiple webhook endpoints in one call.",
570
+ {
571
+ slugs: import_zod2.z.array(import_zod2.z.string()).min(1).max(100).describe("Endpoint slugs to delete")
572
+ },
573
+ withErrorHandling(async ({ slugs }) => {
574
+ const settled = await Promise.allSettled(
575
+ slugs.map(async (slug) => {
576
+ await client.endpoints.delete(slug);
577
+ return slug;
578
+ })
579
+ );
580
+ return jsonContent({
581
+ deleted: settled.filter(
582
+ (result) => result.status === "fulfilled"
583
+ ).map((result) => result.value),
584
+ failed: settled.flatMap(
585
+ (result, index) => result.status === "rejected" ? [
586
+ {
587
+ slug: slugs[index],
588
+ message: result.reason instanceof Error ? result.reason.message : String(result.reason)
589
+ }
590
+ ] : []
591
+ )
592
+ });
593
+ })
594
+ );
106
595
  server.tool(
107
596
  "send_webhook",
108
- "Send a test webhook to an endpoint. Useful for testing webhook handling code.",
597
+ "Send a test webhook to a hosted endpoint. Supports provider templates and signing.",
109
598
  {
110
- slug: import_zod.z.string().describe("The endpoint slug to send to"),
111
- method: import_zod.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).default("POST").describe("HTTP method (default: POST)"),
112
- headers: import_zod.z.record(import_zod.z.string()).optional().describe("HTTP headers to include"),
113
- body: import_zod.z.unknown().optional().describe("Request body (will be JSON-serialized)"),
114
- provider: import_zod.z.enum(["stripe", "github", "shopify", "twilio", "standard-webhooks"]).optional().describe("Optional provider template to send with signed headers"),
115
- template: import_zod.z.string().optional().describe("Optional provider-specific template preset (for example: pull_request.opened)"),
116
- event: import_zod.z.string().optional().describe("Optional provider event/topic name when provider template is used"),
117
- secret: import_zod.z.string().optional().describe(
118
- "Shared secret for provider signature generation (required when provider is set)"
119
- )
599
+ slug: import_zod2.z.string().describe("The endpoint slug to send to"),
600
+ method: methodSchema,
601
+ headers: import_zod2.z.record(import_zod2.z.string()).optional().describe("HTTP headers to include"),
602
+ body: import_zod2.z.unknown().optional().describe("Request body"),
603
+ provider: import_zod2.z.enum(TEMPLATE_PROVIDER_VALUES).optional().describe("Optional provider template to send with signed headers"),
604
+ template: import_zod2.z.string().optional().describe("Provider-specific template preset"),
605
+ event: import_zod2.z.string().optional().describe("Provider event or topic name"),
606
+ secret: import_zod2.z.string().optional().describe("Signing secret. Required when provider is set.")
120
607
  },
121
608
  withErrorHandling(
122
609
  async ({ slug, method, headers, body, provider, template, event, secret }) => {
@@ -139,104 +626,204 @@ function registerTools(server, client) {
139
626
  response = await client.endpoints.send(slug, { method, headers, body });
140
627
  }
141
628
  const responseBody = await readBodyTruncated(response);
142
- return textContent(
143
- JSON.stringify(
144
- { status: response.status, statusText: response.statusText, body: responseBody },
145
- null,
146
- 2
147
- )
148
- );
629
+ return jsonContent({
630
+ status: response.status,
631
+ statusText: response.statusText,
632
+ body: responseBody
633
+ });
149
634
  }
150
635
  )
151
636
  );
152
637
  server.tool(
153
638
  "list_requests",
154
- "List captured webhook requests for an endpoint. Returns the most recent requests (default: 25).",
639
+ "List recent captured requests for an endpoint.",
155
640
  {
156
- endpointSlug: import_zod.z.string().describe("The endpoint slug"),
157
- limit: import_zod.z.number().default(25).describe("Max number of requests to return (default: 25)"),
158
- since: import_zod.z.number().optional().describe("Only return requests after this timestamp (ms)")
641
+ endpointSlug: import_zod2.z.string().describe("The endpoint slug"),
642
+ limit: import_zod2.z.number().int().min(1).max(100).default(25).describe("Max requests to return"),
643
+ since: import_zod2.z.number().optional().describe("Only return requests after this timestamp in ms")
159
644
  },
160
645
  withErrorHandling(async ({ endpointSlug, limit, since }) => {
161
646
  const requests = await client.requests.list(endpointSlug, { limit, since });
162
- return textContent(JSON.stringify(requests, null, 2));
647
+ return jsonContent(requests);
648
+ })
649
+ );
650
+ server.tool(
651
+ "search_requests",
652
+ "Search captured webhook requests across endpoints using retained full-text search.",
653
+ {
654
+ slug: import_zod2.z.string().optional().describe("Filter to a specific endpoint slug"),
655
+ method: import_zod2.z.string().optional().describe("Filter by HTTP method"),
656
+ q: import_zod2.z.string().optional().describe("Free-text search across path, body, and headers"),
657
+ from: durationOrTimestampSchema.optional().describe('Start time as a timestamp or duration like "1h" or "7d"'),
658
+ to: durationOrTimestampSchema.optional().describe('End time as a timestamp or duration like "1h" or "7d"'),
659
+ limit: import_zod2.z.number().int().min(1).max(200).default(50).describe("Max results to return"),
660
+ offset: import_zod2.z.number().int().min(0).max(1e4).default(0).describe("Result offset"),
661
+ order: import_zod2.z.enum(["asc", "desc"]).default("desc").describe("Sort order by received time")
662
+ },
663
+ withErrorHandling(async ({ slug, method, q, from, to, limit, offset, order }) => {
664
+ const results = await client.requests.search({
665
+ slug,
666
+ method,
667
+ q,
668
+ from,
669
+ to,
670
+ limit,
671
+ offset,
672
+ order
673
+ });
674
+ return jsonContent(results);
675
+ })
676
+ );
677
+ server.tool(
678
+ "count_requests",
679
+ "Count captured webhook requests that match the given filters.",
680
+ {
681
+ slug: import_zod2.z.string().optional().describe("Filter to a specific endpoint slug"),
682
+ method: import_zod2.z.string().optional().describe("Filter by HTTP method"),
683
+ q: import_zod2.z.string().optional().describe("Free-text search across path, body, and headers"),
684
+ from: durationOrTimestampSchema.optional().describe('Start time as a timestamp or duration like "1h" or "7d"'),
685
+ to: durationOrTimestampSchema.optional().describe('End time as a timestamp or duration like "1h" or "7d"')
686
+ },
687
+ withErrorHandling(async ({ slug, method, q, from, to }) => {
688
+ const count = await client.requests.count({ slug, method, q, from, to });
689
+ return jsonContent({ count });
163
690
  })
164
691
  );
165
692
  server.tool(
166
693
  "get_request",
167
- "Get full details of a specific captured webhook request by its ID. Includes method, headers, body, path, and timestamp.",
168
- { requestId: import_zod.z.string().describe("The request ID") },
694
+ "Get full details for a specific captured request by ID.",
695
+ { requestId: import_zod2.z.string().describe("The request ID") },
169
696
  withErrorHandling(async ({ requestId }) => {
170
697
  const request = await client.requests.get(requestId);
171
- return textContent(JSON.stringify(request, null, 2));
698
+ return jsonContent(request);
172
699
  })
173
700
  );
174
701
  server.tool(
175
702
  "wait_for_request",
176
- "Wait for a webhook request to arrive at an endpoint. Polls until a request is captured or timeout expires. Use this after sending a webhook to verify it was received.",
703
+ "Wait for a request to arrive at an endpoint.",
177
704
  {
178
- endpointSlug: import_zod.z.string().describe("The endpoint slug to monitor"),
179
- timeout: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).default("30s").describe('How long to wait (e.g. "30s", "5m", or milliseconds as number)'),
180
- pollInterval: import_zod.z.union([import_zod.z.string(), import_zod.z.number()]).optional().describe('Interval between polls (e.g. "1s", "500", or milliseconds). Default: 500ms')
705
+ endpointSlug: import_zod2.z.string().describe("The endpoint slug to monitor"),
706
+ timeout: durationOrTimestampSchema.default("30s").describe('How long to wait, for example "30s"'),
707
+ pollInterval: durationOrTimestampSchema.optional().describe('Interval between polls, for example "500ms" or "1s"')
181
708
  },
182
709
  withErrorHandling(async ({ endpointSlug, timeout, pollInterval }) => {
183
710
  const request = await client.requests.waitFor(endpointSlug, { timeout, pollInterval });
184
- return textContent(JSON.stringify(request, null, 2));
711
+ return jsonContent(request);
712
+ })
713
+ );
714
+ server.tool(
715
+ "wait_for_requests",
716
+ "Wait for multiple requests to arrive at an endpoint.",
717
+ {
718
+ endpointSlug: import_zod2.z.string().describe("The endpoint slug to monitor"),
719
+ count: import_zod2.z.number().int().min(1).max(20).describe("Number of requests to collect"),
720
+ timeout: durationOrTimestampSchema.default("30s").describe('How long to wait, for example "30s"'),
721
+ pollInterval: durationOrTimestampSchema.optional().describe('Interval between polls, for example "500ms" or "1s"'),
722
+ method: import_zod2.z.string().optional().describe("Only collect requests with this HTTP method")
723
+ },
724
+ withErrorHandling(async ({ endpointSlug, count, timeout, pollInterval, method }) => {
725
+ const result = await waitForMultipleRequests(client, endpointSlug, {
726
+ count,
727
+ timeout,
728
+ pollInterval,
729
+ method
730
+ });
731
+ return jsonContent(result);
185
732
  })
186
733
  );
187
734
  server.tool(
188
735
  "replay_request",
189
- "Replay a previously captured webhook request to a target URL. Sends the original method, headers, and body to the specified URL. Only use with URLs you trust \u2014 the original request data is forwarded.",
736
+ "Replay a previously captured request to a target URL.",
190
737
  {
191
- requestId: import_zod.z.string().describe("The ID of the captured request to replay"),
192
- targetUrl: import_zod.z.string().url().refine(
193
- (u) => {
194
- try {
195
- const p = new URL(u).protocol;
196
- return p === "http:" || p === "https:";
197
- } catch {
198
- return false;
199
- }
200
- },
201
- { message: "Only http and https URLs are supported" }
202
- ).describe("The URL to send the replayed request to (http or https only)")
738
+ requestId: import_zod2.z.string().describe("The captured request ID"),
739
+ targetUrl: httpUrlSchema.describe("The URL to replay the request to")
203
740
  },
204
741
  withErrorHandling(async ({ requestId, targetUrl }) => {
205
742
  const response = await client.requests.replay(requestId, targetUrl);
206
743
  const responseBody = await readBodyTruncated(response);
207
- return textContent(
208
- JSON.stringify(
209
- { status: response.status, statusText: response.statusText, body: responseBody },
210
- null,
211
- 2
212
- )
744
+ return jsonContent({
745
+ status: response.status,
746
+ statusText: response.statusText,
747
+ body: responseBody
748
+ });
749
+ })
750
+ );
751
+ server.tool(
752
+ "compare_requests",
753
+ "Compare two captured requests and show the structured differences.",
754
+ {
755
+ leftRequestId: import_zod2.z.string().describe("The first request ID"),
756
+ rightRequestId: import_zod2.z.string().describe("The second request ID"),
757
+ ignoreHeaders: import_zod2.z.array(import_zod2.z.string()).optional().describe("Headers to ignore during comparison")
758
+ },
759
+ withErrorHandling(async ({ leftRequestId, rightRequestId, ignoreHeaders }) => {
760
+ const [leftRequest, rightRequest] = await Promise.all([
761
+ client.requests.get(leftRequestId),
762
+ client.requests.get(rightRequestId)
763
+ ]);
764
+ const diff = (0, import_sdk.diffRequests)(leftRequest, rightRequest, { ignoreHeaders });
765
+ return jsonContent(diff);
766
+ })
767
+ );
768
+ server.tool(
769
+ "extract_from_request",
770
+ "Extract specific JSON fields from a captured request body.",
771
+ {
772
+ requestId: import_zod2.z.string().describe("The request ID"),
773
+ jsonPaths: import_zod2.z.array(import_zod2.z.string()).min(1).max(50).describe("Dot-notation JSON paths to extract")
774
+ },
775
+ withErrorHandling(async ({ requestId, jsonPaths }) => {
776
+ const request = await client.requests.get(requestId);
777
+ const extracted = Object.fromEntries(
778
+ jsonPaths.map((path) => [path, (0, import_sdk.extractJsonField)(request, path) ?? null])
213
779
  );
780
+ return jsonContent(extracted);
781
+ })
782
+ );
783
+ server.tool(
784
+ "verify_signature",
785
+ "Verify the webhook signature on a captured request.",
786
+ {
787
+ requestId: import_zod2.z.string().describe("The captured request ID"),
788
+ provider: import_zod2.z.enum(VERIFY_PROVIDER_VALUES).describe("Provider whose signature scheme should be verified"),
789
+ secret: import_zod2.z.string().optional().describe("Shared signing secret. Required for non-Discord providers."),
790
+ publicKey: import_zod2.z.string().optional().describe("Discord application public key. Required for provider=discord."),
791
+ url: httpUrlSchema.optional().describe("Original signed URL. Required for Twilio verification.")
792
+ },
793
+ withErrorHandling(async ({ requestId, provider, secret, publicKey, url }) => {
794
+ const request = await client.requests.get(requestId);
795
+ const verificationOptions = ensureVerifyArgs({ provider, secret, publicKey, url });
796
+ const result = await (0, import_sdk.verifySignature)(request, verificationOptions);
797
+ return jsonContent({
798
+ valid: result.valid,
799
+ details: result.valid ? "Signature is valid." : "Signature did not match."
800
+ });
801
+ })
802
+ );
803
+ server.tool(
804
+ "clear_requests",
805
+ "Delete captured requests for an endpoint without deleting the endpoint itself.",
806
+ {
807
+ slug: import_zod2.z.string().describe("The endpoint slug to clear"),
808
+ before: durationOrTimestampSchema.optional().describe('Only clear requests older than this timestamp or duration like "1h"')
809
+ },
810
+ withErrorHandling(async ({ slug, before }) => {
811
+ await client.requests.clear(slug, { before });
812
+ return jsonContent({ slug, cleared: true, before: before ?? null });
214
813
  })
215
814
  );
216
815
  server.tool(
217
816
  "send_to",
218
- "Send a webhook directly to any URL with optional provider signing. Use this for local integration testing \u2014 send properly signed webhooks to localhost handlers without routing through webhooks.cc infrastructure.",
817
+ "Send a webhook directly to any URL with optional provider signing.",
219
818
  {
220
- url: import_zod.z.string().url().refine(
221
- (u) => {
222
- try {
223
- const p = new URL(u).protocol;
224
- return p === "http:" || p === "https:";
225
- } catch {
226
- return false;
227
- }
228
- },
229
- { message: "Only http and https URLs are supported" }
230
- ).describe("Target URL to send the webhook to"),
231
- method: import_zod.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]).default("POST").describe("HTTP method (default: POST)"),
232
- headers: import_zod.z.record(import_zod.z.string()).optional().describe("HTTP headers to include"),
233
- body: import_zod.z.unknown().optional().describe("Request body (will be JSON-serialized)"),
234
- provider: import_zod.z.enum(["stripe", "github", "shopify", "twilio", "standard-webhooks"]).optional().describe("Optional provider template for signing"),
235
- template: import_zod.z.string().optional().describe("Provider-specific template preset (not used for standard-webhooks)"),
236
- event: import_zod.z.string().optional().describe("Provider event/topic name"),
237
- secret: import_zod.z.string().optional().describe(
238
- "Shared secret for provider signature generation (required when provider is set)"
239
- )
819
+ url: httpUrlSchema.describe("Target URL"),
820
+ method: methodSchema,
821
+ headers: import_zod2.z.record(import_zod2.z.string()).optional().describe("HTTP headers to include"),
822
+ body: import_zod2.z.unknown().optional().describe("Request body"),
823
+ provider: import_zod2.z.enum(TEMPLATE_PROVIDER_VALUES).optional().describe("Optional provider template for signing"),
824
+ template: import_zod2.z.string().optional().describe("Provider-specific template preset"),
825
+ event: import_zod2.z.string().optional().describe("Provider event or topic name"),
826
+ secret: import_zod2.z.string().optional().describe("Signing secret. Required when provider is set.")
240
827
  },
241
828
  withErrorHandling(async ({ url, method, headers, body, provider, template, event, secret }) => {
242
829
  const response = await client.sendTo(url, {
@@ -249,47 +836,175 @@ function registerTools(server, client) {
249
836
  secret
250
837
  });
251
838
  const responseBody = await readBodyTruncated(response);
252
- return textContent(
253
- JSON.stringify(
254
- { status: response.status, statusText: response.statusText, body: responseBody },
255
- null,
256
- 2
257
- )
839
+ return jsonContent({
840
+ status: response.status,
841
+ statusText: response.statusText,
842
+ body: responseBody
843
+ });
844
+ })
845
+ );
846
+ server.tool(
847
+ "preview_webhook",
848
+ "Preview a webhook request without sending it. Returns the exact URL, method, headers, and body.",
849
+ {
850
+ url: httpUrlSchema.describe("Target URL"),
851
+ method: methodSchema,
852
+ headers: import_zod2.z.record(import_zod2.z.string()).optional().describe("HTTP headers to include"),
853
+ body: import_zod2.z.unknown().optional().describe("Request body"),
854
+ provider: import_zod2.z.enum(TEMPLATE_PROVIDER_VALUES).optional().describe("Optional provider template for signing"),
855
+ template: import_zod2.z.string().optional().describe("Provider-specific template preset"),
856
+ event: import_zod2.z.string().optional().describe("Provider event or topic name"),
857
+ secret: import_zod2.z.string().optional().describe("Signing secret. Required when provider is set.")
858
+ },
859
+ withErrorHandling(async ({ url, method, headers, body, provider, template, event, secret }) => {
860
+ const preview = await client.buildRequest(url, {
861
+ method,
862
+ headers,
863
+ body,
864
+ provider,
865
+ template,
866
+ event,
867
+ secret
868
+ });
869
+ return jsonContent(preview);
870
+ })
871
+ );
872
+ server.tool(
873
+ "list_provider_templates",
874
+ "List supported webhook providers, templates, and signing metadata.",
875
+ {
876
+ provider: import_zod2.z.enum(TEMPLATE_PROVIDER_VALUES).optional().describe("Filter to a single provider")
877
+ },
878
+ withErrorHandling(async ({ provider }) => {
879
+ if (provider) {
880
+ return jsonContent([client.templates.get(provider)]);
881
+ }
882
+ return jsonContent(
883
+ client.templates.listProviders().map((name) => client.templates.get(name))
258
884
  );
259
885
  })
260
886
  );
887
+ server.tool(
888
+ "get_usage",
889
+ "Check current request usage, remaining quota, plan, and period end.",
890
+ {},
891
+ withErrorHandling(async () => {
892
+ const usage = await client.usage();
893
+ return jsonContent({
894
+ ...usage,
895
+ periodEnd: usage.periodEnd ? new Date(usage.periodEnd).toISOString() : null
896
+ });
897
+ })
898
+ );
899
+ server.tool(
900
+ "test_webhook_flow",
901
+ "Run a full webhook test flow: create endpoint, optionally mock, send, wait, verify, replay, and clean up.",
902
+ {
903
+ provider: import_zod2.z.enum(TEMPLATE_PROVIDER_VALUES).optional().describe("Optional provider template to use when sending the webhook"),
904
+ event: import_zod2.z.string().optional().describe("Optional provider event or topic name"),
905
+ secret: import_zod2.z.string().optional().describe(
906
+ "Signing secret. Required when provider is set or signature verification is enabled."
907
+ ),
908
+ mockStatus: import_zod2.z.number().int().min(100).max(599).optional().describe("Optional mock response status to configure before sending"),
909
+ targetUrl: httpUrlSchema.optional().describe("Optional URL to replay the captured request to after capture"),
910
+ verifySignature: import_zod2.z.boolean().default(false).describe("Verify the captured request signature after capture"),
911
+ cleanup: import_zod2.z.boolean().default(true).describe("Delete the created endpoint after the flow completes")
912
+ },
913
+ withErrorHandling(
914
+ async ({
915
+ provider,
916
+ event,
917
+ secret,
918
+ mockStatus,
919
+ targetUrl,
920
+ verifySignature: shouldVerify,
921
+ cleanup
922
+ }) => {
923
+ const flow = client.flow().createEndpoint({ expiresIn: "1h" }).waitForCapture({ timeout: "30s" });
924
+ if (mockStatus !== void 0) {
925
+ flow.setMock({
926
+ status: mockStatus,
927
+ body: "",
928
+ headers: {}
929
+ });
930
+ }
931
+ if (provider) {
932
+ const templateSecret = secret?.trim();
933
+ if (!templateSecret) {
934
+ throw new Error(
935
+ "test_webhook_flow with provider templates requires a non-empty secret"
936
+ );
937
+ }
938
+ flow.sendTemplate({
939
+ provider,
940
+ event,
941
+ secret: templateSecret
942
+ });
943
+ if (shouldVerify) {
944
+ flow.verifySignature({
945
+ provider,
946
+ secret: templateSecret
947
+ });
948
+ }
949
+ } else {
950
+ if (shouldVerify) {
951
+ throw new Error("test_webhook_flow cannot verify signatures without a provider");
952
+ }
953
+ flow.send();
954
+ }
955
+ if (targetUrl) {
956
+ flow.replayTo(targetUrl);
957
+ }
958
+ if (cleanup) {
959
+ flow.cleanup();
960
+ }
961
+ const result = await flow.run();
962
+ return jsonContent({
963
+ endpoint: result.endpoint,
964
+ request: result.request ?? null,
965
+ verification: result.verification ?? null,
966
+ replayResponse: result.replayResponse ? await summarizeResponse(result.replayResponse) : null,
967
+ cleanedUp: result.cleanedUp
968
+ });
969
+ }
970
+ )
971
+ );
261
972
  server.tool(
262
973
  "describe",
263
- "Describe all available SDK operations, their parameters, and types. Useful for discovering what actions are possible.",
974
+ "Describe all available SDK operations, parameters, and types.",
264
975
  {},
265
976
  withErrorHandling(async () => {
266
977
  const description = client.describe();
267
- return textContent(JSON.stringify(description, null, 2));
978
+ return jsonContent(description);
268
979
  })
269
980
  );
270
981
  }
271
982
 
272
983
  // src/index.ts
273
- var VERSION = true ? "0.3.0" : "0.0.0-dev";
984
+ var VERSION = true ? "1.0.0" : "0.0.0-dev";
274
985
  function createServer(options = {}) {
275
986
  const apiKey = options.apiKey ?? process.env.WHK_API_KEY;
276
987
  if (!apiKey) {
277
988
  throw new Error("Missing API key. Set WHK_API_KEY environment variable or pass apiKey option.");
278
989
  }
279
- const client = new import_sdk.WebhooksCC({
990
+ const client = new import_sdk2.WebhooksCC({
280
991
  apiKey,
281
992
  webhookUrl: options.webhookUrl ?? process.env.WHK_WEBHOOK_URL,
282
993
  baseUrl: options.baseUrl ?? process.env.WHK_BASE_URL
283
994
  });
284
- const server = new import_mcp.McpServer({
995
+ const server = new import_mcp2.McpServer({
285
996
  name: "webhooks-cc",
286
997
  version: VERSION
287
998
  });
288
999
  registerTools(server, client);
1000
+ registerPrompts(server);
1001
+ registerResources(server, client);
289
1002
  return server;
290
1003
  }
291
1004
  // Annotate the CommonJS export names for ESM import in node:
292
1005
  0 && (module.exports = {
293
1006
  createServer,
1007
+ registerPrompts,
1008
+ registerResources,
294
1009
  registerTools
295
1010
  });