@webhooks-cc/mcp 0.3.1 → 1.0.1

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