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