@webhooks-cc/mcp 1.10.1 → 1.11.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/bin/mcp.js CHANGED
@@ -6,7 +6,7 @@ var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
6
6
 
7
7
  // src/index.ts
8
8
  var import_mcp2 = require("@modelcontextprotocol/sdk/server/mcp.js");
9
- var import_sdk2 = require("@webhooks-cc/sdk");
9
+ var import_sdk3 = require("@webhooks-cc/sdk");
10
10
 
11
11
  // src/prompts.ts
12
12
  var import_zod = require("zod");
@@ -383,6 +383,10 @@ function registerResources(server, client) {
383
383
  );
384
384
  }
385
385
 
386
+ // src/sandbox-tools.ts
387
+ var import_zod3 = require("zod");
388
+ var import_sdk2 = require("@webhooks-cc/sdk");
389
+
386
390
  // src/tools.ts
387
391
  var import_zod2 = require("zod");
388
392
  var import_sdk = require("@webhooks-cc/sdk");
@@ -442,6 +446,44 @@ var mockResponseSchema = import_zod2.z.object({
442
446
  `Response delay in milliseconds (${import_sdk.MOCK_RESPONSE_DELAY_MIN}-${import_sdk.MOCK_RESPONSE_DELAY_MAX}, default: none)`
443
447
  )
444
448
  });
449
+ var createEndpointShape = {
450
+ name: import_zod2.z.string().optional().describe("Display name for the endpoint"),
451
+ ephemeral: import_zod2.z.boolean().optional().describe("Create a temporary endpoint that auto-expires"),
452
+ expiresIn: durationOrTimestampSchema.optional().describe('Auto-expire after this duration, for example "12h"'),
453
+ mockResponse: mockResponseSchema.optional().describe("Optional mock response to return when the endpoint receives a request"),
454
+ responseRules: responseRulesSchema.optional().describe(
455
+ "Conditional response rules. Each rule has conditions and a response. First matching rule wins."
456
+ ),
457
+ notificationUrl: import_zod2.z.string().url().optional().describe(
458
+ "URL to POST a JSON summary to after each captured request (e.g. Slack/Discord webhook)"
459
+ ),
460
+ signingProvider: import_zod2.z.string().optional().describe(
461
+ "Signing provider for automatic signature verification (e.g. stripe, github, shopify)"
462
+ ),
463
+ signingSecret: import_zod2.z.string().optional().describe(
464
+ "Signing secret (encrypted server-side, never returned). Required when signingProvider is set."
465
+ ),
466
+ signingHeader: import_zod2.z.string().optional().describe("Custom signature header name. Only used with generic-hmac provider.")
467
+ };
468
+ var listEndpointsShape = {
469
+ team: import_zod2.z.string().min(1).optional().describe(
470
+ "Team id or name (case-insensitive). Keeps endpoints shared with you from that team and endpoints you own that are shared with it."
471
+ )
472
+ };
473
+ var getEndpointShape = { slug: import_zod2.z.string().describe("The endpoint slug") };
474
+ var deleteEndpointShape = { slug: import_zod2.z.string().describe("The endpoint slug to delete") };
475
+ var listRequestsShape = {
476
+ endpointSlug: import_zod2.z.string().describe("The endpoint slug"),
477
+ limit: import_zod2.z.number().int().min(1).max(100).default(25).describe("Max requests to return"),
478
+ since: import_zod2.z.number().optional().describe("Only return requests after this timestamp in ms"),
479
+ kind: kindSchema
480
+ };
481
+ var getRequestShape = { requestId: import_zod2.z.string().describe("The request ID") };
482
+ var waitForRequestShape = {
483
+ endpointSlug: import_zod2.z.string().describe("The endpoint slug to monitor"),
484
+ timeout: durationOrTimestampSchema.default("30s").describe('How long to wait, for example "30s"'),
485
+ pollInterval: durationOrTimestampSchema.optional().describe('Interval between polls, for example "500ms" or "1s"')
486
+ };
445
487
  function textContent(text) {
446
488
  return { content: [{ type: "text", text }] };
447
489
  }
@@ -745,25 +787,7 @@ function registerTools(server, client) {
745
787
  server.tool(
746
788
  "create_endpoint",
747
789
  "Create a webhook endpoint. Returns the endpoint slug, URL, and metadata.",
748
- {
749
- name: import_zod2.z.string().optional().describe("Display name for the endpoint"),
750
- ephemeral: import_zod2.z.boolean().optional().describe("Create a temporary endpoint that auto-expires"),
751
- expiresIn: durationOrTimestampSchema.optional().describe('Auto-expire after this duration, for example "12h"'),
752
- mockResponse: mockResponseSchema.optional().describe("Optional mock response to return when the endpoint receives a request"),
753
- responseRules: responseRulesSchema.optional().describe(
754
- "Conditional response rules. Each rule has conditions and a response. First matching rule wins."
755
- ),
756
- notificationUrl: import_zod2.z.string().url().optional().describe(
757
- "URL to POST a JSON summary to after each captured request (e.g. Slack/Discord webhook)"
758
- ),
759
- signingProvider: import_zod2.z.string().optional().describe(
760
- "Signing provider for automatic signature verification (e.g. stripe, github, shopify)"
761
- ),
762
- signingSecret: import_zod2.z.string().optional().describe(
763
- "Signing secret (encrypted server-side, never returned). Required when signingProvider is set."
764
- ),
765
- signingHeader: import_zod2.z.string().optional().describe("Custom signature header name. Only used with generic-hmac provider.")
766
- },
790
+ createEndpointShape,
767
791
  withErrorHandling(
768
792
  async ({
769
793
  name,
@@ -816,11 +840,7 @@ function registerTools(server, client) {
816
840
  server.tool(
817
841
  "list_endpoints",
818
842
  "List webhook endpoints: those you own (with sharedWith) and those shared with you through teams (with fromTeam). Optionally keep only one team's endpoints.",
819
- {
820
- team: import_zod2.z.string().min(1).optional().describe(
821
- "Team id or name (case-insensitive). Keeps endpoints shared with you from that team and endpoints you own that are shared with it."
822
- )
823
- },
843
+ listEndpointsShape,
824
844
  withErrorHandling(async ({ team }) => {
825
845
  const endpoints = await client.endpoints.list({ team });
826
846
  return jsonContent(endpoints);
@@ -876,7 +896,7 @@ function registerTools(server, client) {
876
896
  server.tool(
877
897
  "get_endpoint",
878
898
  "Get details for a specific webhook endpoint by slug.",
879
- { slug: import_zod2.z.string().describe("The endpoint slug") },
899
+ getEndpointShape,
880
900
  withErrorHandling(async ({ slug }) => {
881
901
  const endpoint = await client.endpoints.get(slug);
882
902
  return jsonContent(endpoint);
@@ -929,7 +949,7 @@ function registerTools(server, client) {
929
949
  server.tool(
930
950
  "delete_endpoint",
931
951
  "Delete a webhook endpoint and all its captured requests.",
932
- { slug: import_zod2.z.string().describe("The endpoint slug to delete") },
952
+ deleteEndpointShape,
933
953
  withErrorHandling(async ({ slug }) => {
934
954
  await client.endpoints.delete(slug);
935
955
  return textContent(`Endpoint "${slug}" deleted.`);
@@ -1033,12 +1053,7 @@ function registerTools(server, client) {
1033
1053
  server.tool(
1034
1054
  "list_requests",
1035
1055
  "List recent captured requests for an endpoint, HTTP requests and emails together (filter with kind). For emails, list_emails is shorter.",
1036
- {
1037
- endpointSlug: import_zod2.z.string().describe("The endpoint slug"),
1038
- limit: import_zod2.z.number().int().min(1).max(100).default(25).describe("Max requests to return"),
1039
- since: import_zod2.z.number().optional().describe("Only return requests after this timestamp in ms"),
1040
- kind: kindSchema
1041
- },
1056
+ listRequestsShape,
1042
1057
  withErrorHandling(async ({ endpointSlug, limit, since, kind }) => {
1043
1058
  const requests = await client.requests.list(endpointSlug, { limit, since, kind });
1044
1059
  return jsonContent(requests.map(compactRequest));
@@ -1092,7 +1107,7 @@ function registerTools(server, client) {
1092
1107
  server.tool(
1093
1108
  "get_request",
1094
1109
  "Get full details for a specific captured request by ID.",
1095
- { requestId: import_zod2.z.string().describe("The request ID") },
1110
+ getRequestShape,
1096
1111
  withErrorHandling(async ({ requestId }) => {
1097
1112
  const request = await client.requests.get(requestId);
1098
1113
  return jsonContent(compactRequest(request));
@@ -1101,11 +1116,7 @@ function registerTools(server, client) {
1101
1116
  server.tool(
1102
1117
  "wait_for_request",
1103
1118
  "Wait for a request to arrive at an endpoint.",
1104
- {
1105
- endpointSlug: import_zod2.z.string().describe("The endpoint slug to monitor"),
1106
- timeout: durationOrTimestampSchema.default("30s").describe('How long to wait, for example "30s"'),
1107
- pollInterval: durationOrTimestampSchema.optional().describe('Interval between polls, for example "500ms" or "1s"')
1108
- },
1119
+ waitForRequestShape,
1109
1120
  withErrorHandling(async ({ endpointSlug, timeout, pollInterval }) => {
1110
1121
  const request = await client.requests.waitFor(endpointSlug, { timeout, pollInterval });
1111
1122
  return jsonContent(compactRequest(request));
@@ -1596,127 +1607,389 @@ function registerTools(server, client) {
1596
1607
  return jsonContent(description);
1597
1608
  })
1598
1609
  );
1599
- registerAgentRegistrationTools(server);
1600
- }
1601
- function resolveBaseUrl() {
1602
- return process.env.WHK_BASE_URL ?? "https://webhooks.cc";
1603
1610
  }
1604
- function registerAgentRegistrationTools(server) {
1605
- const baseUrl = resolveBaseUrl();
1606
- server.tool(
1607
- "how_to_register",
1608
- "Explain how an agent self-registers for a webhooks.cc API credential (auth.md). Call this FIRST when you have no API key. Returns the three registration flows and the auth.md documentation URL. No authentication required.",
1609
- {},
1610
- withErrorHandling(async () => {
1611
- return jsonContent({
1612
- ...import_sdk.WebhooksCC.describeRegistration(baseUrl),
1613
- next_steps: [
1614
- "Easiest: call register_agent (anonymous) to get a key immediately, then ask a human to open the returned claimUrl while signed in to webhooks.cc and enter the userCode. Poll check_claim until it says claimed.",
1615
- "Or set WHK_API_KEY to an existing whcc_ key and use the authenticated tools."
1616
- ]
1611
+
1612
+ // src/sandbox-tools.ts
1613
+ var SANDBOX = {
1614
+ maxEndpoints: 3,
1615
+ requestsPerEndpoint: 25,
1616
+ requests: 100,
1617
+ lifetimeHours: 24
1618
+ };
1619
+ var DEFAULT_WAIT_SECONDS = 45;
1620
+ var MAX_WAIT_SECONDS = 600;
1621
+ var TOKEN_REFRESH_MARGIN_MS = 6e4;
1622
+ var DOCS_URL = "https://webhooks.cc/docs/agents";
1623
+ var ACCOUNT_ONLY_OPTIONS = [
1624
+ "mockResponse",
1625
+ "responseRules",
1626
+ "notificationUrl",
1627
+ "signingProvider",
1628
+ "signingSecret",
1629
+ "signingHeader"
1630
+ ];
1631
+ var AgentSession = class {
1632
+ constructor(baseUrl, webhookUrl, clientName) {
1633
+ this.baseUrl = baseUrl;
1634
+ this.webhookUrl = webhookUrl;
1635
+ this.clientName = clientName;
1636
+ this.sandbox = null;
1637
+ this.claim = null;
1638
+ this.connected = false;
1639
+ }
1640
+ /**
1641
+ * The sandbox, registered on first use and again after it expired. Tool
1642
+ * calls can run in parallel: this.sandbox is read again after every await,
1643
+ * and a new sandbox is assigned with no await in between, so parallel
1644
+ * calls share one registration. Calls waiting on a registration that fails
1645
+ * get its error (a 429 asks them to wait); the next call starts again.
1646
+ */
1647
+ async sandboxClient() {
1648
+ while (this.sandbox) {
1649
+ const pending = this.sandbox;
1650
+ const sandbox = await pending;
1651
+ if (!this.expired(pending, sandbox)) return sandbox;
1652
+ }
1653
+ const created = import_sdk2.WebhooksCC.sandbox({
1654
+ baseUrl: this.baseUrl,
1655
+ webhookUrl: this.webhookUrl,
1656
+ clientName: this.clientName
1657
+ });
1658
+ this.sandbox = created;
1659
+ created.catch(() => {
1660
+ if (this.sandbox === created) this.sandbox = null;
1661
+ });
1662
+ return created;
1663
+ }
1664
+ /** The live sandbox, if one was registered; never registers one. */
1665
+ async existingSandbox() {
1666
+ const pending = this.sandbox;
1667
+ if (!pending) return null;
1668
+ let sandbox;
1669
+ try {
1670
+ sandbox = await pending;
1671
+ } catch {
1672
+ return null;
1673
+ }
1674
+ return this.expired(pending, sandbox) ? null : sandbox;
1675
+ }
1676
+ /** True when the sandbox is past its 24 hours; then it is dropped. */
1677
+ expired(pending, sandbox) {
1678
+ if (sandbox.expiresAt.getTime() > Date.now()) return false;
1679
+ if (this.sandbox === pending) this.sandbox = null;
1680
+ if (this.claim?.kind === "sandbox" && this.claim.claimToken === sandbox.registration.claimToken) {
1681
+ this.claim = null;
1682
+ }
1683
+ return true;
1684
+ }
1685
+ async requireSandbox() {
1686
+ const sandbox = await this.existingSandbox();
1687
+ if (!sandbox) {
1688
+ throw new Error("No sandbox yet: create_endpoint starts one.");
1689
+ }
1690
+ return sandbox;
1691
+ }
1692
+ forgetSandbox() {
1693
+ this.sandbox = null;
1694
+ }
1695
+ };
1696
+ function claimedTokens(baseUrl, assertion, first) {
1697
+ let current = first;
1698
+ let pending = null;
1699
+ return async (options) => {
1700
+ if (!options?.forceRefresh && current.expiresAt.getTime() - Date.now() > TOKEN_REFRESH_MARGIN_MS) {
1701
+ return current.accessToken;
1702
+ }
1703
+ if (!pending) {
1704
+ pending = import_sdk2.WebhooksCC.agent.exchange({ baseUrl, assertion }).finally(() => {
1705
+ pending = null;
1617
1706
  });
1618
- })
1707
+ }
1708
+ current = await pending;
1709
+ return current.accessToken;
1710
+ };
1711
+ }
1712
+ function minutesLeft(until) {
1713
+ return Math.max(1, Math.round((until.getTime() - Date.now()) / 6e4));
1714
+ }
1715
+ function onlyKind(requests, kind) {
1716
+ if (!kind) return requests;
1717
+ return requests.filter((request) => (request.kind ?? "http") === kind);
1718
+ }
1719
+ function registerSandboxTools(server, options = {}) {
1720
+ const baseUrl = options.baseUrl ?? process.env.WHK_BASE_URL ?? "https://webhooks.cc";
1721
+ const session = new AgentSession(
1722
+ baseUrl,
1723
+ options.webhookUrl ?? process.env.WHK_WEBHOOK_URL,
1724
+ options.clientName ?? "webhooks-cc-mcp"
1619
1725
  );
1620
- server.tool(
1621
- "register_agent",
1622
- "Self-register for a webhooks.cc API credential via the anonymous auth.md flow. Returns a whcc_ API key, plus a short userCode and claimUrl a human uses to bind the key to their account. Until a human claims it, the key only works with the sandbox API (/api/agent/sandbox/endpoints), not with these tools, and it is deleted about 15 minutes after registration. No authentication required.",
1623
- {
1624
- clientName: import_zod2.z.string().optional().describe("A human-readable name for this agent, recorded on the issued key")
1625
- },
1626
- withErrorHandling(async ({ clientName }) => {
1627
- const reg = await import_sdk.WebhooksCC.register.anonymous({ baseUrl, clientName });
1628
- return jsonContent({
1629
- credential: reg.credential,
1630
- scopes: reg.scopes,
1631
- claim: {
1632
- userCode: reg.userCode,
1633
- claimUrl: reg.claimUrl,
1634
- claimToken: reg.claimToken,
1635
- expiresAt: reg.claimTokenExpires,
1636
- instructions: `Ask a human to open ${reg.claimUrl} while logged in to webhooks.cc and either enter the code ${reg.userCode} or open ${reg.claimUrl}?token=${reg.claimToken}. Then call check_claim with the claimToken.`
1637
- },
1638
- usage: "Until a human claims it, the key only works with the sandbox API at /api/agent/sandbox/endpoints (create temporary endpoints, read their requests), and it is deleted about 15 minutes after registration. Once check_claim says claimed, set WHK_API_KEY to `credential` and restart the MCP server to use the authenticated tools."
1639
- });
1640
- })
1726
+ const registered = [];
1727
+ const limits = `up to ${SANDBOX.maxEndpoints} endpoints at a time, ${SANDBOX.requestsPerEndpoint} captured requests each and ${SANDBOX.requests} in all, deleted ${SANDBOX.lifetimeHours} hours after the sandbox was created`;
1728
+ registered.push(
1729
+ server.tool(
1730
+ "create_endpoint",
1731
+ `Create a temporary webhook capture endpoint in the agent sandbox (no account needed): ${limits}. The first call registers the sandbox, which takes a few seconds of proof of work. Mock responses, notifications and signature verification need an account: see connect_account.`,
1732
+ createEndpointShape,
1733
+ withErrorHandling(async (args2) => {
1734
+ const accountOnly = ACCOUNT_ONLY_OPTIONS.filter((key) => args2[key] !== void 0);
1735
+ if (accountOnly.length > 0) {
1736
+ throw new Error(
1737
+ `${accountOnly.join(", ")} need an account; sandbox endpoints only capture and answer 200. Call connect_account to connect one.`
1738
+ );
1739
+ }
1740
+ const sandbox = await session.sandboxClient();
1741
+ const endpoint = await sandbox.endpoints.create();
1742
+ const ignored = args2.name !== void 0 || args2.expiresIn !== void 0;
1743
+ return jsonContent(
1744
+ ignored ? {
1745
+ ...endpoint,
1746
+ note: "Sandbox endpoints have no name and expire with the sandbox."
1747
+ } : endpoint
1748
+ );
1749
+ })
1750
+ )
1641
1751
  );
1642
- server.tool(
1643
- "check_claim",
1644
- "Check whether an anonymous registration's API key has been claimed by a human yet. Poll this after register_agent until status is 'claimed'. No authentication required.",
1645
- {
1646
- claimToken: import_zod2.z.string().describe("The claimToken returned by register_agent")
1647
- },
1648
- withErrorHandling(async ({ claimToken }) => {
1649
- const poll = await import_sdk.WebhooksCC.register.pollClaim(claimToken, { baseUrl });
1650
- return jsonContent(poll);
1651
- })
1752
+ registered.push(
1753
+ server.tool(
1754
+ "list_endpoints",
1755
+ "List this agent's sandbox endpoints. Empty until create_endpoint starts the sandbox.",
1756
+ listEndpointsShape,
1757
+ withErrorHandling(async ({ team }) => {
1758
+ if (team !== void 0) {
1759
+ throw new Error("Teams need an account. Call connect_account to connect one.");
1760
+ }
1761
+ const sandbox = await session.existingSandbox();
1762
+ return jsonContent(sandbox ? await sandbox.endpoints.list() : []);
1763
+ })
1764
+ )
1652
1765
  );
1653
- server.tool(
1654
- "register_agent_with_email",
1655
- "Self-register via the verified_email auth.md flow: webhooks.cc emails a one-time code to the address. The credential is WITHHELD until the code is confirmed with verify_agent_otp. Returns a claimToken to pass to verify_agent_otp. No authentication required.",
1656
- {
1657
- email: import_zod2.z.string().email({ message: "Invalid email address" }).describe("The email address to verify and bind the credential to"),
1658
- clientName: import_zod2.z.string().optional().describe("A human-readable name for this agent, recorded on the issued key")
1659
- },
1660
- withErrorHandling(async ({ email, clientName }) => {
1661
- const challenge = await import_sdk.WebhooksCC.register.withEmail(email, { baseUrl, clientName });
1662
- return jsonContent({
1663
- claimToken: challenge.claimToken,
1664
- expiresAt: challenge.claimTokenExpires,
1665
- postClaimScopes: challenge.postClaimScopes,
1666
- next_step: `A one-time code was emailed to ${email}. Ask the human for it, then call verify_agent_otp with this claimToken and the code.`
1667
- });
1668
- })
1766
+ registered.push(
1767
+ server.tool(
1768
+ "get_endpoint",
1769
+ "Get one of this agent's sandbox endpoints by slug, with its sandbox limits and usage.",
1770
+ getEndpointShape,
1771
+ withErrorHandling(async ({ slug }) => {
1772
+ return jsonContent(await (await session.requireSandbox()).endpoints.get(slug));
1773
+ })
1774
+ )
1669
1775
  );
1670
- server.tool(
1671
- "verify_agent_otp",
1672
- "Complete the verified_email flow: submit the emailed OTP with the claimToken from register_agent_with_email. On success returns the whcc_ API key (bound to the verified email). Set WHK_API_KEY to it. No authentication required.",
1673
- {
1674
- claimToken: import_zod2.z.string().describe("The claimToken returned by register_agent_with_email"),
1675
- otp: import_zod2.z.string().describe("The one-time code the human received by email")
1676
- },
1677
- withErrorHandling(async ({ claimToken, otp }) => {
1678
- const issued = await import_sdk.WebhooksCC.register.confirmEmailOtp({ claimToken, otp }, { baseUrl });
1679
- return jsonContent({
1680
- credential: issued.credential,
1681
- scopes: issued.scopes,
1682
- usage: "Set WHK_API_KEY to `credential` to use the authenticated tools."
1683
- });
1684
- })
1776
+ registered.push(
1777
+ server.tool(
1778
+ "delete_endpoint",
1779
+ "Delete one of this agent's sandbox endpoints and its captured requests. Frees a slot; the sandbox's request budget is not refunded.",
1780
+ deleteEndpointShape,
1781
+ withErrorHandling(async ({ slug }) => {
1782
+ await (await session.requireSandbox()).endpoints.delete(slug);
1783
+ return jsonContent({ deleted: slug });
1784
+ })
1785
+ )
1685
1786
  );
1686
- server.tool(
1687
- "register_agent_with_idjag",
1688
- "Self-register via the identity_assertion (ID-JAG) auth.md flow: present a verified identity-assertion JWT (urn:ietf:params:oauth:token-type:id-jag) from a trusted provider. The credential is returned synchronously \u2014 no human claim step. No webhooks.cc authentication required, but only works if webhooks.cc trusts your provider.",
1689
- {
1690
- assertion: import_zod2.z.string().describe("The ID-JAG assertion JWT (typ oauth-id-jag+jwt) from a trusted provider")
1691
- },
1692
- withErrorHandling(async ({ assertion }) => {
1693
- const issued = await import_sdk.WebhooksCC.register.withIdJag(assertion, { baseUrl });
1694
- return jsonContent({
1695
- credential: issued.credential,
1696
- scopes: issued.scopes,
1697
- usage: "Set WHK_API_KEY to `credential` to use the authenticated tools."
1698
- });
1699
- })
1787
+ registered.push(
1788
+ server.tool(
1789
+ "list_requests",
1790
+ "List recent requests captured by a sandbox endpoint, newest first.",
1791
+ listRequestsShape,
1792
+ withErrorHandling(async ({ endpointSlug, limit, since, kind }) => {
1793
+ const sandbox = await session.requireSandbox();
1794
+ const requests = await sandbox.requests.list(endpointSlug, { limit, since });
1795
+ return jsonContent(onlyKind(requests, kind).map(compactRequest));
1796
+ })
1797
+ )
1798
+ );
1799
+ registered.push(
1800
+ server.tool(
1801
+ "get_request",
1802
+ "Get full details for a request captured by a sandbox endpoint.",
1803
+ getRequestShape,
1804
+ withErrorHandling(async ({ requestId }) => {
1805
+ const sandbox = await session.requireSandbox();
1806
+ return jsonContent(compactRequest(await sandbox.requests.get(requestId)));
1807
+ })
1808
+ )
1809
+ );
1810
+ registered.push(
1811
+ server.tool(
1812
+ "wait_for_request",
1813
+ "Wait for a request to arrive at a sandbox endpoint.",
1814
+ waitForRequestShape,
1815
+ withErrorHandling(async ({ endpointSlug, timeout, pollInterval }) => {
1816
+ const sandbox = await session.requireSandbox();
1817
+ const request = await sandbox.requests.waitFor(endpointSlug, { timeout, pollInterval });
1818
+ return jsonContent(compactRequest(request));
1819
+ })
1820
+ )
1821
+ );
1822
+ registered.push(
1823
+ server.tool(
1824
+ "connect_account",
1825
+ "Connect this agent to a human's webhooks.cc account, for the full tool set (mock responses, signatures, email, teams) and to keep the sandbox endpoints. Returns a link and a 6-digit code: show both to the human, who signs in or signs up with that email and enters the code. Then call wait_for_connection. Calling again gives a new code.",
1826
+ {
1827
+ email: import_zod3.z.string().email({ message: "Invalid email address" }).describe("The human's email address; only someone signed in as it can connect")
1828
+ },
1829
+ withErrorHandling(async ({ email }) => {
1830
+ if (session.connected) {
1831
+ return jsonContent({ connected: true, message: "Already connected to an account." });
1832
+ }
1833
+ const normalized = email.trim().toLowerCase();
1834
+ const sandbox = await session.existingSandbox();
1835
+ let claim;
1836
+ if (sandbox) {
1837
+ claim = {
1838
+ kind: "sandbox",
1839
+ claimToken: sandbox.registration.claimToken,
1840
+ email: normalized,
1841
+ attempt: await sandbox.claim({ email: normalized }),
1842
+ claimExpires: sandbox.expiresAt
1843
+ };
1844
+ } else if (session.claim?.kind === "service_auth" && session.claim.email === normalized && session.claim.claimExpires.getTime() > Date.now()) {
1845
+ const attempt = await import_sdk2.WebhooksCC.agent.startClaim({
1846
+ baseUrl,
1847
+ claimToken: session.claim.claimToken
1848
+ });
1849
+ claim = { ...session.claim, attempt };
1850
+ } else {
1851
+ const registration = await import_sdk2.WebhooksCC.agent.registerServiceAuth({
1852
+ baseUrl,
1853
+ email: normalized,
1854
+ clientName: session.clientName
1855
+ });
1856
+ claim = {
1857
+ kind: "service_auth",
1858
+ claimToken: registration.claimToken,
1859
+ email: normalized,
1860
+ attempt: registration.claim,
1861
+ claimExpires: registration.claimTokenExpires
1862
+ };
1863
+ }
1864
+ session.claim = claim;
1865
+ const { verificationUri, userCode, expiresAt } = claim.attempt;
1866
+ return jsonContent({
1867
+ verificationUri,
1868
+ userCode,
1869
+ expiresAt: expiresAt.toISOString(),
1870
+ tellTheHuman: `Open ${verificationUri}, sign in or sign up as ${normalized}, and enter the code ${userCode}.`,
1871
+ next: `Show the human that line, then call wait_for_connection. The code works for about ${minutesLeft(expiresAt)} minutes; connect_account gives a new one.`,
1872
+ ...claim.kind === "sandbox" ? { endpoints: "The sandbox endpoints move into that account with what they captured." } : {}
1873
+ });
1874
+ })
1875
+ )
1876
+ );
1877
+ registered.push(
1878
+ server.tool(
1879
+ "wait_for_connection",
1880
+ `Wait for the human to enter the code from connect_account. On success the full webhooks.cc tools for their account replace these sandbox tools. Returns after timeoutSeconds (default ${DEFAULT_WAIT_SECONDS}) if they have not finished yet; call it again to keep waiting.`,
1881
+ {
1882
+ timeoutSeconds: import_zod3.z.number().int().min(1).max(MAX_WAIT_SECONDS).optional().describe(`How long to wait, in seconds (default ${DEFAULT_WAIT_SECONDS})`)
1883
+ },
1884
+ withErrorHandling(async ({ timeoutSeconds }) => {
1885
+ if (session.connected) {
1886
+ return jsonContent({ connected: true, message: "Already connected to an account." });
1887
+ }
1888
+ const claim = session.claim;
1889
+ if (!claim) {
1890
+ throw new Error("Nothing to wait for: call connect_account first.");
1891
+ }
1892
+ let claimed;
1893
+ try {
1894
+ claimed = await import_sdk2.WebhooksCC.agent.waitForClaim({
1895
+ baseUrl,
1896
+ claimToken: claim.claimToken,
1897
+ interval: claim.attempt.interval,
1898
+ timeout: (timeoutSeconds ?? DEFAULT_WAIT_SECONDS) * 1e3
1899
+ });
1900
+ } catch (error) {
1901
+ if (!(error instanceof import_sdk2.AgentAuthError)) throw error;
1902
+ if (error.code === "timeout") {
1903
+ return jsonContent({
1904
+ connected: false,
1905
+ status: "waiting",
1906
+ message: `Not connected yet. The code works until ${claim.attempt.expiresAt.toISOString()}; call wait_for_connection again.`
1907
+ });
1908
+ }
1909
+ if (error.code === "expired_token") {
1910
+ return jsonContent({
1911
+ connected: false,
1912
+ status: "expired",
1913
+ message: "The code expired. Call connect_account for a new one."
1914
+ });
1915
+ }
1916
+ if (error.code === "access_denied") {
1917
+ return jsonContent({
1918
+ connected: false,
1919
+ status: "declined",
1920
+ message: "The human declined. Call connect_account again only if they ask you to."
1921
+ });
1922
+ }
1923
+ throw error;
1924
+ }
1925
+ const client = new import_sdk2.WebhooksCC({
1926
+ baseUrl,
1927
+ webhookUrl: session.webhookUrl,
1928
+ getAccessToken: claimedTokens(baseUrl, claimed.identityAssertion, claimed.token)
1929
+ });
1930
+ session.connected = true;
1931
+ session.claim = null;
1932
+ session.forgetSandbox();
1933
+ for (const tool of registered) tool.remove();
1934
+ registerTools(server, client);
1935
+ options.onConnected?.(client);
1936
+ return jsonContent({
1937
+ connected: true,
1938
+ email: claim.email,
1939
+ scope: claimed.token.scope,
1940
+ message: `Connected to the webhooks.cc account of ${claim.email}. The full tool set has replaced the sandbox tools (the tool list changed; if your client does not pick that up, ask the user to restart it).${claim.kind === "sandbox" ? " The sandbox endpoints are now that account's endpoints, with what they captured." : ""} This connection lasts while this MCP server runs; for a lasting setup, the human can create an API key under Account and set WHK_API_KEY.`
1941
+ });
1942
+ })
1943
+ )
1944
+ );
1945
+ registered.push(
1946
+ server.tool(
1947
+ "about_sandbox",
1948
+ "Explain what this agent can do without a webhooks.cc account, the sandbox limits, and how to connect an account. No network call.",
1949
+ {},
1950
+ withErrorHandling(async () => {
1951
+ return jsonContent({
1952
+ mode: "sandbox (no WHK_API_KEY)",
1953
+ sandbox: {
1954
+ maxEndpoints: SANDBOX.maxEndpoints,
1955
+ requestsPerEndpoint: SANDBOX.requestsPerEndpoint,
1956
+ requestsInAll: SANDBOX.requests,
1957
+ lifetimeHours: SANDBOX.lifetimeHours,
1958
+ startsWith: "create_endpoint (registers the sandbox; a few seconds of proof of work)",
1959
+ captures: "Endpoints answer every request with 200; only this agent can read what they capture.",
1960
+ notAvailable: "Mock responses, response rules, notifications, signature verification, email capture, forwarding, teams and sending webhooks."
1961
+ },
1962
+ connectAnAccount: [
1963
+ "Call connect_account with the human's email and show them the link and code it returns.",
1964
+ "Call wait_for_connection until it reports connected; the full tools for their account then replace the sandbox tools.",
1965
+ "Sandbox endpoints move into the account with their captured requests."
1966
+ ],
1967
+ withAnApiKey: "Set WHK_API_KEY to a whcc_ key from the dashboard and restart for the full tools from the start.",
1968
+ docs: DOCS_URL,
1969
+ protocol: `${baseUrl}/auth.md`
1970
+ });
1971
+ })
1972
+ )
1700
1973
  );
1701
1974
  }
1702
1975
 
1703
1976
  // src/index.ts
1704
- var VERSION = true ? "1.10.1" : "0.0.0-dev";
1977
+ var VERSION = true ? "1.11.0" : "0.0.0-dev";
1705
1978
  function createServer(options = {}) {
1706
1979
  const apiKey = options.apiKey ?? process.env.WHK_API_KEY;
1707
- const server = new import_mcp2.McpServer({
1708
- name: "webhooks-cc",
1709
- version: VERSION
1710
- });
1980
+ const webhookUrl = options.webhookUrl ?? process.env.WHK_WEBHOOK_URL;
1981
+ const baseUrl = options.baseUrl ?? process.env.WHK_BASE_URL;
1982
+ const server = new import_mcp2.McpServer(
1983
+ { name: "webhooks-cc", version: VERSION },
1984
+ // Connecting an account swaps every tool at once: one list_changed, not dozens.
1985
+ { debouncedNotificationMethods: ["notifications/tools/list_changed"] }
1986
+ );
1711
1987
  if (!apiKey) {
1712
- registerAgentRegistrationTools(server);
1988
+ registerSandboxTools(server, { baseUrl, webhookUrl });
1989
+ registerPrompts(server);
1713
1990
  return server;
1714
1991
  }
1715
- const client = new import_sdk2.WebhooksCC({
1716
- apiKey,
1717
- webhookUrl: options.webhookUrl ?? process.env.WHK_WEBHOOK_URL,
1718
- baseUrl: options.baseUrl ?? process.env.WHK_BASE_URL
1719
- });
1992
+ const client = new import_sdk3.WebhooksCC({ apiKey, webhookUrl, baseUrl });
1720
1993
  registerTools(server, client);
1721
1994
  registerPrompts(server);
1722
1995
  registerResources(server, client);