@pithy-sh/auth 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (246) hide show
  1. package/README.md +30 -2
  2. package/dist/audit/actions.d.ts +39 -0
  3. package/dist/audit/actions.d.ts.map +1 -1
  4. package/dist/audit/actions.js +40 -1
  5. package/dist/audit/emit.d.ts +34 -0
  6. package/dist/audit/emit.d.ts.map +1 -1
  7. package/dist/audit/emit.js +47 -1
  8. package/dist/audit/evidence.d.ts +8 -2
  9. package/dist/audit/evidence.d.ts.map +1 -1
  10. package/dist/capability.d.ts +31 -11
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +38 -5
  13. package/dist/client/api.d.ts +55 -12
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +57 -18
  16. package/dist/client/bearer.d.ts +110 -0
  17. package/dist/client/bearer.d.ts.map +1 -0
  18. package/dist/client/bearer.js +265 -0
  19. package/dist/client/handoff.d.ts +77 -0
  20. package/dist/client/handoff.d.ts.map +1 -0
  21. package/dist/client/handoff.js +119 -0
  22. package/dist/client/mcp.d.ts +70 -0
  23. package/dist/client/mcp.d.ts.map +1 -0
  24. package/dist/client/mcp.js +65 -0
  25. package/dist/data/betterAuth.d.ts +3 -2
  26. package/dist/data/betterAuth.d.ts.map +1 -1
  27. package/dist/data/betterAuth.js +5 -3
  28. package/dist/data/kitFields.d.ts +5 -0
  29. package/dist/data/kitFields.d.ts.map +1 -1
  30. package/dist/data/kitFields.js +5 -0
  31. package/dist/data/tables.d.ts +25 -4
  32. package/dist/data/tables.d.ts.map +1 -1
  33. package/dist/data/tables.js +5 -3
  34. package/dist/data/userLifecycle.d.ts +9 -0
  35. package/dist/data/userLifecycle.d.ts.map +1 -1
  36. package/dist/data/userLifecycle.js +6 -2
  37. package/dist/data/verificationOutcome.d.ts +53 -0
  38. package/dist/data/verificationOutcome.d.ts.map +1 -0
  39. package/dist/data/verificationOutcome.js +50 -0
  40. package/dist/email/send.js +6 -2
  41. package/dist/http/adminRoutes.d.ts.map +1 -1
  42. package/dist/http/adminRoutes.js +56 -10
  43. package/dist/http/csrf.d.ts.map +1 -1
  44. package/dist/http/csrf.js +2 -1
  45. package/dist/http/guards.d.ts +15 -11
  46. package/dist/http/guards.d.ts.map +1 -1
  47. package/dist/http/guards.js +46 -11
  48. package/dist/http/handoff.d.ts +76 -0
  49. package/dist/http/handoff.d.ts.map +1 -0
  50. package/dist/http/handoff.js +316 -0
  51. package/dist/http/middleware.d.ts +12 -0
  52. package/dist/http/middleware.d.ts.map +1 -1
  53. package/dist/http/middleware.js +25 -4
  54. package/dist/http/resolve.d.ts.map +1 -1
  55. package/dist/http/resolve.js +9 -3
  56. package/dist/http/responses.d.ts +142 -0
  57. package/dist/http/responses.d.ts.map +1 -1
  58. package/dist/http/responses.js +66 -10
  59. package/dist/http/routes.d.ts +2 -0
  60. package/dist/http/routes.d.ts.map +1 -1
  61. package/dist/http/routes.js +35 -4
  62. package/dist/http/schemas.d.ts +57 -0
  63. package/dist/http/schemas.d.ts.map +1 -1
  64. package/dist/http/schemas.js +44 -1
  65. package/dist/http/views.d.ts +22 -2
  66. package/dist/http/views.d.ts.map +1 -1
  67. package/dist/http/views.js +40 -4
  68. package/dist/index.d.ts +2 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.js +4 -2
  71. package/dist/instance/auth.d.ts +148 -10
  72. package/dist/instance/auth.d.ts.map +1 -1
  73. package/dist/instance/auth.js +86 -41
  74. package/dist/instance/plugins.d.ts +6 -0
  75. package/dist/instance/plugins.d.ts.map +1 -1
  76. package/dist/instance/plugins.js +14 -1
  77. package/dist/ledger/read.d.ts +53 -0
  78. package/dist/ledger/read.d.ts.map +1 -0
  79. package/dist/ledger/read.js +85 -0
  80. package/dist/ledger/record.d.ts +35 -0
  81. package/dist/ledger/record.d.ts.map +1 -0
  82. package/dist/ledger/record.js +98 -0
  83. package/dist/lifecycle/erasure.d.ts +9 -0
  84. package/dist/lifecycle/erasure.d.ts.map +1 -0
  85. package/dist/lifecycle/erasure.js +96 -0
  86. package/dist/lifecycle/inactivity.d.ts +19 -0
  87. package/dist/lifecycle/inactivity.d.ts.map +1 -0
  88. package/dist/lifecycle/inactivity.js +28 -0
  89. package/dist/lifecycle/transitions.d.ts +22 -1
  90. package/dist/lifecycle/transitions.d.ts.map +1 -1
  91. package/dist/lifecycle/transitions.js +51 -4
  92. package/dist/mcp/argumentClass.d.ts +51 -0
  93. package/dist/mcp/argumentClass.d.ts.map +1 -0
  94. package/dist/mcp/argumentClass.js +69 -0
  95. package/dist/mcp/capability.d.ts +50 -0
  96. package/dist/mcp/capability.d.ts.map +1 -0
  97. package/dist/mcp/capability.js +140 -0
  98. package/dist/mcp/clientMetadata.d.ts +40 -0
  99. package/dist/mcp/clientMetadata.d.ts.map +1 -0
  100. package/dist/mcp/clientMetadata.js +68 -0
  101. package/dist/mcp/consent.d.ts +49 -0
  102. package/dist/mcp/consent.d.ts.map +1 -0
  103. package/dist/mcp/consent.js +69 -0
  104. package/dist/mcp/dispatch.d.ts +35 -0
  105. package/dist/mcp/dispatch.d.ts.map +1 -0
  106. package/dist/mcp/dispatch.js +135 -0
  107. package/dist/mcp/floor.d.ts +37 -0
  108. package/dist/mcp/floor.d.ts.map +1 -0
  109. package/dist/mcp/floor.js +41 -0
  110. package/dist/mcp/host.d.ts +34 -0
  111. package/dist/mcp/host.d.ts.map +1 -0
  112. package/dist/mcp/host.js +2 -0
  113. package/dist/mcp/http/redirectList.d.ts +9 -0
  114. package/dist/mcp/http/redirectList.d.ts.map +1 -0
  115. package/dist/mcp/http/redirectList.js +24 -0
  116. package/dist/mcp/http/responses.d.ts +143 -0
  117. package/dist/mcp/http/responses.d.ts.map +1 -0
  118. package/dist/mcp/http/responses.js +83 -0
  119. package/dist/mcp/http/routes.d.ts +28 -0
  120. package/dist/mcp/http/routes.d.ts.map +1 -0
  121. package/dist/mcp/http/routes.js +517 -0
  122. package/dist/mcp/http/schemas.d.ts +24 -0
  123. package/dist/mcp/http/schemas.d.ts.map +1 -0
  124. package/dist/mcp/http/schemas.js +18 -0
  125. package/dist/mcp/marker.d.ts +15 -0
  126. package/dist/mcp/marker.d.ts.map +1 -0
  127. package/dist/mcp/marker.js +15 -0
  128. package/dist/mcp/provider.d.ts +78 -0
  129. package/dist/mcp/provider.d.ts.map +1 -0
  130. package/dist/mcp/provider.js +108 -0
  131. package/dist/mcp/purge.d.ts +15 -0
  132. package/dist/mcp/purge.d.ts.map +1 -0
  133. package/dist/mcp/purge.js +31 -0
  134. package/dist/mcp/rpc.d.ts +79 -0
  135. package/dist/mcp/rpc.d.ts.map +1 -0
  136. package/dist/mcp/rpc.js +103 -0
  137. package/dist/mcp/toolAudit.d.ts +76 -0
  138. package/dist/mcp/toolAudit.d.ts.map +1 -0
  139. package/dist/mcp/toolAudit.js +86 -0
  140. package/dist/migrations/0006_verification_outcomes.d.ts +15 -0
  141. package/dist/migrations/0006_verification_outcomes.d.ts.map +1 -0
  142. package/dist/migrations/0006_verification_outcomes.js +35 -0
  143. package/dist/migrations/0007_erasure_record.d.ts +17 -0
  144. package/dist/migrations/0007_erasure_record.d.ts.map +1 -0
  145. package/dist/migrations/0007_erasure_record.js +36 -0
  146. package/dist/migrations/0008_last_active.d.ts +15 -0
  147. package/dist/migrations/0008_last_active.d.ts.map +1 -0
  148. package/dist/migrations/0008_last_active.js +29 -0
  149. package/dist/migrations/set.d.ts +4 -1
  150. package/dist/migrations/set.d.ts.map +1 -1
  151. package/dist/migrations/set.js +8 -2
  152. package/dist/peer.d.ts +3 -2
  153. package/dist/peer.d.ts.map +1 -1
  154. package/dist/processing/activities.d.ts +6 -0
  155. package/dist/processing/activities.d.ts.map +1 -0
  156. package/dist/processing/activities.js +12 -0
  157. package/dist/purge/contribution.d.ts +20 -5
  158. package/dist/purge/contribution.d.ts.map +1 -1
  159. package/dist/purge/contribution.js +20 -6
  160. package/dist/purge/run.d.ts +75 -5
  161. package/dist/purge/run.d.ts.map +1 -1
  162. package/dist/purge/run.js +117 -14
  163. package/dist/purge/workflow.d.ts +15 -2
  164. package/dist/purge/workflow.d.ts.map +1 -1
  165. package/dist/purge/workflow.js +51 -7
  166. package/dist/test-utils/accountFootprint.d.ts +5 -2
  167. package/dist/test-utils/accountFootprint.d.ts.map +1 -1
  168. package/dist/test-utils/accountFootprint.js +7 -2
  169. package/dist/test-utils/liveApp.d.ts +6 -0
  170. package/dist/test-utils/liveApp.d.ts.map +1 -1
  171. package/dist/test-utils/liveApp.js +7 -2
  172. package/dist/token/handoff.d.ts +80 -0
  173. package/dist/token/handoff.d.ts.map +1 -0
  174. package/dist/token/handoff.js +136 -0
  175. package/dist/version.generated.d.ts +1 -1
  176. package/dist/version.generated.js +1 -1
  177. package/docs/account-lifecycle.md +59 -7
  178. package/docs/apple-signin.md +32 -4
  179. package/docs/facebook-oauth.md +2 -2
  180. package/docs/github-oauth.md +2 -2
  181. package/docs/google-oauth.md +9 -7
  182. package/docs/microsoft-oauth.md +2 -2
  183. package/package.json +11 -5
  184. package/pithy.manifest.json +2 -2
  185. package/pithy.mcp.manifest.json +36 -0
  186. package/src/audit/actions.ts +39 -0
  187. package/src/audit/emit.ts +63 -0
  188. package/src/audit/evidence.ts +8 -4
  189. package/src/capability.ts +80 -23
  190. package/src/client/api.ts +69 -19
  191. package/src/client/bearer.ts +388 -0
  192. package/src/client/handoff.ts +172 -0
  193. package/src/client/mcp.ts +140 -0
  194. package/src/data/betterAuth.ts +8 -4
  195. package/src/data/kitFields.ts +2 -0
  196. package/src/data/tables.ts +4 -2
  197. package/src/data/userLifecycle.ts +15 -3
  198. package/src/data/verificationOutcome.ts +86 -0
  199. package/src/email/send.ts +2 -2
  200. package/src/http/adminRoutes.ts +68 -3
  201. package/src/http/csrf.ts +4 -1
  202. package/src/http/guards.ts +48 -11
  203. package/src/http/handoff.ts +350 -0
  204. package/src/http/middleware.ts +29 -3
  205. package/src/http/resolve.ts +25 -25
  206. package/src/http/responses.ts +134 -8
  207. package/src/http/routes.ts +63 -4
  208. package/src/http/schemas.ts +85 -0
  209. package/src/http/views.ts +46 -2
  210. package/src/index.ts +2 -0
  211. package/src/instance/auth.ts +51 -1
  212. package/src/instance/plugins.ts +20 -2
  213. package/src/ledger/read.ts +133 -0
  214. package/src/ledger/record.ts +198 -0
  215. package/src/lifecycle/erasure.ts +118 -0
  216. package/src/lifecycle/inactivity.ts +56 -0
  217. package/src/lifecycle/transitions.ts +75 -5
  218. package/src/mcp/argumentClass.ts +112 -0
  219. package/src/mcp/capability.ts +194 -0
  220. package/src/mcp/clientMetadata.ts +81 -0
  221. package/src/mcp/consent.ts +95 -0
  222. package/src/mcp/dispatch.ts +154 -0
  223. package/src/mcp/floor.ts +62 -0
  224. package/src/mcp/host.ts +36 -0
  225. package/src/mcp/http/redirectList.ts +26 -0
  226. package/src/mcp/http/responses.ts +157 -0
  227. package/src/mcp/http/routes.ts +635 -0
  228. package/src/mcp/http/schemas.ts +37 -0
  229. package/src/mcp/marker.ts +18 -0
  230. package/src/mcp/provider.ts +151 -0
  231. package/src/mcp/purge.ts +39 -0
  232. package/src/mcp/rpc.ts +135 -0
  233. package/src/mcp/toolAudit.ts +132 -0
  234. package/src/migrations/0006_verification_outcomes.ts +51 -0
  235. package/src/migrations/0007_erasure_record.ts +43 -0
  236. package/src/migrations/0008_last_active.ts +30 -0
  237. package/src/migrations/set.ts +7 -1
  238. package/src/processing/activities.ts +14 -0
  239. package/src/purge/contribution.ts +37 -10
  240. package/src/purge/run.ts +179 -16
  241. package/src/purge/workflow.ts +65 -7
  242. package/src/seeds/example.ts +2 -2
  243. package/src/test-utils/accountFootprint.ts +10 -1
  244. package/src/test-utils/liveApp.ts +10 -1
  245. package/src/token/handoff.ts +180 -0
  246. package/src/version.generated.ts +1 -1
@@ -0,0 +1,50 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type Capability } from "@pithy-sh/core/src/capability/capability";
4
+ import { type AppTool } from "@pithy-sh/core/src/mcp/tools";
5
+ import { z } from "zod";
6
+ import type { McpWiring } from "./host";
7
+ /**
8
+ * The MCP capability: the app's own agent surface, authorized as a user (`docs/AGENT-ACCESS.md` §4).
9
+ *
10
+ * **An agent that uses an application is a user of it.** It acts *as somebody*, with that person's authorization,
11
+ * through the app's own routes — never through the control-plane seam, which creates no user and no session. So
12
+ * this capability composes an OAuth 2.1 authorization server into the auth instance (`./provider.ts`), serves a
13
+ * streamable HTTP MCP endpoint (`./routes.ts`), and offers each caller the routes their role reaches as tools
14
+ * (`@pithy-sh/core/src/mcp/tools.ts`). Composing it mounts the endpoint; the adopter writes no route.
15
+ *
16
+ * **The default is closed.** It is off until composed, and composing it means choosing a {@link McpFloor}.
17
+ */
18
+ /** The migration order of the provider's tables in the `app` database. */
19
+ export declare const MCP_MIGRATION_ORDER = 1700;
20
+ /** The MCP capability's configuration. */
21
+ export declare const McpConfig: z.ZodObject<{
22
+ path: z.ZodDefault<z.ZodString>;
23
+ floor: z.ZodUnion<readonly [z.ZodLiteral<"signed-in">, z.ZodObject<{
24
+ power: z.ZodString;
25
+ }, z.core.$strict>, z.ZodObject<{
26
+ entitlement: z.ZodString;
27
+ }, z.core.$strict>]>;
28
+ consentPath: z.ZodDefault<z.ZodString>;
29
+ database: z.ZodDefault<z.ZodString>;
30
+ }, z.core.$strip>;
31
+ export type McpConfig = z.output<typeof McpConfig>;
32
+ export type McpConfigInput = z.input<typeof McpConfig>;
33
+ /** The MCP capability, with its resolved config attached for inspection. */
34
+ export interface McpCapability extends Capability {
35
+ readonly mcpConfig: McpConfig;
36
+ /** What auth composes into its instance. */
37
+ readonly mcpWiring: McpWiring;
38
+ /** Every tool the composed app offers, before any caller's role filters it. Empty until the app is built. */
39
+ readonly tools: () => readonly AppTool[];
40
+ /** Whether the endpoint is open to every signed-in user, and the floor in one line. Read by `pithy doctor`. */
41
+ readonly floorReport: {
42
+ readonly open: boolean;
43
+ readonly line: string;
44
+ };
45
+ }
46
+ /** The one migration that plan holds: the plugin's tables, under this capability's own namespace. */
47
+ export declare const PROVIDER_MIGRATION: import("kysely/migration").Migration;
48
+ /** The MCP capability. */
49
+ export declare function mcp(options: McpConfigInput): McpCapability;
50
+ //# sourceMappingURL=capability.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"capability.d.ts","sourceRoot":"","sources":["../../src/mcp/capability.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,UAAU,EAAuC,MAAM,0CAA0C,CAAC;AAGhH,OAAO,EAAE,KAAK,OAAO,EAAY,MAAM,8BAA8B,CAAC;AAGtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAMxB,OAAO,KAAK,EAAW,SAAS,EAAE,MAAM,QAAQ,CAAC;AAMjD;;;;;;;;;;GAUG;AAEH,0EAA0E;AAC1E,eAAO,MAAM,mBAAmB,OAAO,CAAC;AAExC,0CAA0C;AAC1C,eAAO,MAAM,SAAS;;;;;;;;;iBAoB8B,CAAC;AACrD,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,SAAS,CAAC,CAAC;AACnD,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,CAAC;AAEvD,4EAA4E;AAC5E,MAAM,WAAW,aAAc,SAAQ,UAAU;IAC/C,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,4CAA4C;IAC5C,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,6GAA6G;IAC7G,QAAQ,CAAC,KAAK,EAAE,MAAM,SAAS,OAAO,EAAE,CAAC;IACzC,+GAA+G;IAC/G,QAAQ,CAAC,WAAW,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;QAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CACzE;AAWD,qGAAqG;AACrG,eAAO,MAAM,kBAAkB,sCAS3B,CAAC;AA6BL,0BAA0B;AAC1B,wBAAgB,GAAG,CAAC,OAAO,EAAE,cAAc,GAAG,aAAa,CAwE1D"}
@@ -0,0 +1,140 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { mcpAuthorizationServer } from "./provider.js";
4
+ import "./marker.js";
5
+ import { authPluginPlan } from "../migrations/pluginTables.js";
6
+ import { PACKAGE_NAME, PACKAGE_VERSION } from "../version.generated.js";
7
+ import { isAuthCapability } from "../capability.js";
8
+ import { clientMetadataDiscovery } from "./clientMetadata.js";
9
+ import { McpFloor, floorLine, isOpenToEverySignedInUser } from "./floor.js";
10
+ import { registerMcpRoutes } from "./http/routes.js";
11
+ import { eraseMcpUser, exportMcpUser } from "./purge.js";
12
+ import { defineCapability } from "@pithy-sh/core/src/capability/capability";
13
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
14
+ import { z } from "zod";
15
+ import { appTools } from "@pithy-sh/core/src/mcp/tools";
16
+ import { routeGroupsOf } from "@pithy-sh/core/src/openapi/routeGroups";
17
+ //#region src/mcp/capability.ts
18
+ /**
19
+ * The MCP capability: the app's own agent surface, authorized as a user (`docs/AGENT-ACCESS.md` §4).
20
+ *
21
+ * **An agent that uses an application is a user of it.** It acts *as somebody*, with that person's authorization,
22
+ * through the app's own routes — never through the control-plane seam, which creates no user and no session. So
23
+ * this capability composes an OAuth 2.1 authorization server into the auth instance (`./provider.ts`), serves a
24
+ * streamable HTTP MCP endpoint (`./routes.ts`), and offers each caller the routes their role reaches as tools
25
+ * (`@pithy-sh/core/src/mcp/tools.ts`). Composing it mounts the endpoint; the adopter writes no route.
26
+ *
27
+ * **The default is closed.** It is off until composed, and composing it means choosing a {@link McpFloor}.
28
+ */
29
+ /** The migration order of the provider's tables in the `app` database. */
30
+ const MCP_MIGRATION_ORDER = 1700;
31
+ /** The MCP capability's configuration. */
32
+ const McpConfig = z.object({
33
+ path: z.string().regex(/^\/[a-z0-9/_-]*[a-z0-9]$/, "A path like `/mcp`.").default("/mcp").describe("Where the MCP endpoint mounts. A client is pointed at `<origin><path>`. Defaults to `/mcp`."),
34
+ floor: McpFloor,
35
+ consentPath: z.string().regex(/^\/[A-Za-z0-9/_-]*$/, "A path like `/agent-consent`.").default("/agent-consent").describe("The scaffolded consent screen's path in this Worker's front end. Both sign-in and consent for an agent land there. Defaults to `/agent-consent`, which `pithy ui` writes."),
36
+ database: z.string().default("DB").describe("The D1 binding auth uses. The provider's tables live beside auth's. Must match `auth({ database })`.")
37
+ }).describe("Configuration for the MCP capability.");
38
+ /** The provider's tables, derived once from the plugin itself. Its options shape no column, so any resource does. */
39
+ const providerPlan = authPluginPlan([mcpAuthorizationServer({
40
+ resource: "https://schema.invalid/mcp",
41
+ consentPage: "/agent-consent",
42
+ clientDiscovery: clientMetadataDiscovery()
43
+ })[0]]);
44
+ /** The one migration that plan holds: the plugin's tables, under this capability's own namespace. */
45
+ const PROVIDER_MIGRATION = (() => {
46
+ const [migration] = Object.values(providerPlan.migrations);
47
+ if (migration === void 0) throw new ValidationError({
48
+ message: "The OAuth provider declared no tables.",
49
+ detail: "authPluginPlan derived no migration for the oauth-provider plugin"
50
+ });
51
+ return migration;
52
+ })();
53
+ /** Refuse a composition this capability cannot serve, naming what to change. */
54
+ function hostFrom(capabilities, config) {
55
+ const authCap = capabilities.find(isAuthCapability);
56
+ if (!authCap) throw new ValidationError({
57
+ message: "The mcp capability requires the auth capability.",
58
+ action: "Add `auth(...)` to your capabilities. An agent acts as a signed-in user, and auth is who signs them in."
59
+ });
60
+ if (authCap.authConfig.database !== config.database) throw new ValidationError({
61
+ message: "The mcp capability and the auth capability name different databases.",
62
+ action: `Set mcp({ database: "${authCap.authConfig.database}" }). The provider's tables live beside auth's.`,
63
+ detail: `mcp database ${config.database}, auth database ${authCap.authConfig.database}`
64
+ });
65
+ if (authCap.authConfig.plugins.map((plugin) => plugin.id).includes("oauth-provider")) throw new ValidationError({
66
+ message: "auth({ plugins }) already composes an OAuth provider.",
67
+ action: "Remove oauthProvider() from auth({ plugins: [...] }). The mcp capability composes the one this endpoint uses."
68
+ });
69
+ return authCap.mcpHost;
70
+ }
71
+ /** The MCP capability. */
72
+ function mcp(options) {
73
+ const config = McpConfig.parse(options);
74
+ const wiring = {
75
+ path: config.path,
76
+ consentPage: config.consentPath,
77
+ clientDiscovery: clientMetadataDiscovery()
78
+ };
79
+ let host;
80
+ let app;
81
+ let tools;
82
+ const ready = (value, what) => {
83
+ if (value === void 0) throw new ValidationError({
84
+ message: "The mcp capability is not composed.",
85
+ action: "Compose it through createBackend; it needs the auth capability beside it.",
86
+ detail: `mcp read its ${what} before createBackend composed it`
87
+ });
88
+ return value;
89
+ };
90
+ const capability = defineCapability({
91
+ name: "mcp",
92
+ version: PACKAGE_VERSION,
93
+ package: PACKAGE_NAME,
94
+ config: McpConfig,
95
+ dependsOn: ["auth"],
96
+ requiredBindings: [{
97
+ type: "d1",
98
+ name: config.database
99
+ }],
100
+ databases: { app: {
101
+ binding: config.database,
102
+ tables: {},
103
+ migrationOrder: MCP_MIGRATION_ORDER,
104
+ migrations: { "0001_init": PROVIDER_MIGRATION }
105
+ } },
106
+ purge: [{
107
+ subject: "user",
108
+ summary: "Every application the person let act as them: the consents, and the access and refresh tokens minted under them. A dynamically registered client is the application's, not the person's, and stays.",
109
+ erase: (context) => eraseMcpUser(context, config.database),
110
+ export: (context) => exportMcpUser(context, config.database)
111
+ }],
112
+ compose: ({ capabilities }) => {
113
+ host = hostFrom(capabilities, config);
114
+ },
115
+ routes: (router) => {
116
+ app = router;
117
+ registerMcpRoutes(router, {
118
+ path: config.path,
119
+ floor: config.floor,
120
+ host: () => ready(host, "auth host"),
121
+ app: () => ready(app, "router"),
122
+ tools: () => {
123
+ tools ??= appTools(routeGroupsOf(ready(app, "router")) ?? []);
124
+ return tools;
125
+ }
126
+ });
127
+ }
128
+ });
129
+ return Object.assign(capability, {
130
+ mcpConfig: config,
131
+ mcpWiring: wiring,
132
+ tools: () => tools ?? (app ? appTools(routeGroupsOf(app) ?? []) : []),
133
+ floorReport: {
134
+ open: isOpenToEverySignedInUser(config.floor),
135
+ line: floorLine(config.floor)
136
+ }
137
+ });
138
+ }
139
+ //#endregion
140
+ export { MCP_MIGRATION_ORDER, McpConfig, PROVIDER_MIGRATION, mcp };
@@ -0,0 +1,40 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { ClientDiscovery, ClientMetadataResourceFetch } from "@better-auth/oauth-provider";
4
+ /**
5
+ * Client ID Metadata Documents: a client whose `client_id` is an HTTPS URL, and whose registration is the document
6
+ * served there (`docs/AGENT-ACCESS.md` §4.0).
7
+ *
8
+ * **Composed, not written.** `@better-auth/cimd` fetches the document, refuses one whose `client_id` is not its own
9
+ * URL, caps it at 5 KB and 5 seconds, caches it by its own caching headers within {@link METADATA_CACHE_CEILING}, and
10
+ * persists the client it describes. The MCP profile requires `client_name` and `redirect_uris`. What this module adds
11
+ * is the network boundary the plugin asks its host to own, and the one fact the consent screen may present as
12
+ * verified.
13
+ */
14
+ /** The longest a fetched document is trusted before it is fetched again, whatever its caching headers say. */
15
+ export declare const METADATA_CACHE_CEILING = "60m";
16
+ /** The discovery id the provider stores on every client a metadata document created. */
17
+ export declare const CLIENT_METADATA_DISCOVERY_ID = "cimd";
18
+ /**
19
+ * The fetch a metadata document, or a resource it names, is read over: HTTPS to a public host, a read, and never a
20
+ * redirect followed — a 3xx comes back as itself, and the plugin refuses anything but a 200.
21
+ *
22
+ * The host is classified before anything leaves. A name that resolves to private space is refused by Cloudflare's
23
+ * network at connection time, which is the resolve-and-pin guarantee a Worker cannot implement over `fetch` itself.
24
+ */
25
+ export declare const fetchClientMetadata: ClientMetadataResourceFetch;
26
+ /**
27
+ * The provider's discovery for metadata-document clients. Built once per composed `mcp()`, so its cache and its
28
+ * fetch budget outlive the per-request auth instance.
29
+ */
30
+ export declare function clientMetadataDiscovery(): ClientDiscovery;
31
+ /**
32
+ * The host a client's identity was proven by, or `null` when nothing was. A metadata-document client is whoever
33
+ * serves the document at its id, so its id's host is verified; a dynamically registered client named itself, and
34
+ * nothing about it is.
35
+ */
36
+ export declare function verifiedHost(client: {
37
+ readonly clientId: string;
38
+ readonly clientDiscoveryId?: string | null;
39
+ }): string | null;
40
+ //# sourceMappingURL=clientMetadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clientMetadata.d.ts","sourceRoot":"","sources":["../../src/mcp/clientMetadata.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,eAAe,EAAE,2BAA2B,EAAE,MAAM,6BAA6B,CAAC;AAEhG;;;;;;;;;GASG;AAEH,8GAA8G;AAC9G,eAAO,MAAM,sBAAsB,QAAQ,CAAC;AAE5C,wFAAwF;AACxF,eAAO,MAAM,4BAA4B,SAAS,CAAC;AAQnD;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,EAAE,2BAgBjC,CAAC;AAEF;;;GAGG;AACH,wBAAgB,uBAAuB,IAAI,eAAe,CAMzD;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE;IACnC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C,GAAG,MAAM,GAAG,IAAI,CAKhB"}
@@ -0,0 +1,68 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { createCimdClientDiscovery } from "@better-auth/cimd";
4
+ import { isPublicRoutableHost } from "@better-auth/core/utils/host";
5
+ //#region src/mcp/clientMetadata.ts
6
+ /**
7
+ * Client ID Metadata Documents: a client whose `client_id` is an HTTPS URL, and whose registration is the document
8
+ * served there (`docs/AGENT-ACCESS.md` §4.0).
9
+ *
10
+ * **Composed, not written.** `@better-auth/cimd` fetches the document, refuses one whose `client_id` is not its own
11
+ * URL, caps it at 5 KB and 5 seconds, caches it by its own caching headers within {@link METADATA_CACHE_CEILING}, and
12
+ * persists the client it describes. The MCP profile requires `client_name` and `redirect_uris`. What this module adds
13
+ * is the network boundary the plugin asks its host to own, and the one fact the consent screen may present as
14
+ * verified.
15
+ */
16
+ /** The longest a fetched document is trusted before it is fetched again, whatever its caching headers say. */
17
+ const METADATA_CACHE_CEILING = "60m";
18
+ /** The discovery id the provider stores on every client a metadata document created. */
19
+ const CLIENT_METADATA_DISCOVERY_ID = "cimd";
20
+ /** Where a request is going, whichever form it arrived in. */
21
+ function targetOf(input) {
22
+ if (input instanceof URL) return input;
23
+ return new URL(typeof input === "string" ? input : input.url);
24
+ }
25
+ /**
26
+ * The fetch a metadata document, or a resource it names, is read over: HTTPS to a public host, a read, and never a
27
+ * redirect followed — a 3xx comes back as itself, and the plugin refuses anything but a 200.
28
+ *
29
+ * The host is classified before anything leaves. A name that resolves to private space is refused by Cloudflare's
30
+ * network at connection time, which is the resolve-and-pin guarantee a Worker cannot implement over `fetch` itself.
31
+ */
32
+ const fetchClientMetadata = async (input, init) => {
33
+ const url = targetOf(input);
34
+ if (url.protocol !== "https:") throw new TypeError(`A client metadata document is fetched over HTTPS only: ${url}`);
35
+ if (!isPublicRoutableHost(url.hostname)) throw new TypeError(`A client metadata document is fetched from a public host only: ${url.hostname}`);
36
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
37
+ if (method !== "GET" && method !== "HEAD") throw new TypeError(`A client metadata document is read with GET or HEAD only, not ${method}`);
38
+ return fetch(url, {
39
+ method,
40
+ redirect: "manual",
41
+ ...init?.headers === void 0 ? {} : { headers: init.headers },
42
+ ...init?.signal == null ? {} : { signal: init.signal }
43
+ });
44
+ };
45
+ /**
46
+ * The provider's discovery for metadata-document clients. Built once per composed `mcp()`, so its cache and its
47
+ * fetch budget outlive the per-request auth instance.
48
+ */
49
+ function clientMetadataDiscovery() {
50
+ return createCimdClientDiscovery({
51
+ fetchClientMetadataResource: fetchClientMetadata,
52
+ metadataProfile: "mcp-2026-07-28",
53
+ metadataRevalidationInterval: "60m"
54
+ });
55
+ }
56
+ /**
57
+ * The host a client's identity was proven by, or `null` when nothing was. A metadata-document client is whoever
58
+ * serves the document at its id, so its id's host is verified; a dynamically registered client named itself, and
59
+ * nothing about it is.
60
+ */
61
+ function verifiedHost(client) {
62
+ if (client.clientDiscoveryId !== "cimd") return null;
63
+ if (!URL.canParse(client.clientId)) return null;
64
+ const url = new URL(client.clientId);
65
+ return url.protocol === "https:" ? url.host : null;
66
+ }
67
+ //#endregion
68
+ export { CLIENT_METADATA_DISCOVERY_ID, METADATA_CACHE_CEILING, clientMetadataDiscovery, fetchClientMetadata, verifiedHost };
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { type AppTool, type ToolCaller } from "@pithy-sh/core/src/mcp/tools";
4
+ import type { ConsentCapability, ConsentScope, ConsentView } from "./http/responses";
5
+ /**
6
+ * What the consent screen shows, built from the tools and the signer (`docs/AGENT-ACCESS.md` §4.3).
7
+ *
8
+ * **The unit of consent is a capability, not a tool.** One row per composed capability the user can reach, each
9
+ * listing what the client will then be able to do, in the capability's own words — each route's own summary —
10
+ * counted: *3 of 5 operations*. Per-tool consent cannot work, because a tool list changes without a deploy; a
11
+ * capability changes when a Worker deploys, which is a cadence a grant can survive.
12
+ *
13
+ * **Never a permission the user does not hold.** A row lists only the operations the signer's role reaches, and a
14
+ * capability with none is not listed at all. What the role withholds is a count, never a name — the screen says
15
+ * *two need a role you do not hold*, which discloses nothing a list would not.
16
+ *
17
+ * **Informational.** Nothing on it is selectable: one decision, *let this client act as you in this application*,
18
+ * with these rows as its consequence. The role is the ceiling either way, and the screen says so.
19
+ *
20
+ * **Codes, never sentences.** Everything here is data the screen words in the reader's language; a sentence built
21
+ * on the server would reach a Spanish screen in English.
22
+ */
23
+ /** Why a scope the client asked for is not granted: the role does not reach it, or no such permission exists. */
24
+ export type NotGrantedReason = ConsentScope["reason"];
25
+ /** The client, as the screen presents it. */
26
+ export interface ConsentClient {
27
+ readonly id: string;
28
+ /** The host a metadata document proved the client by, or `null` when it registered itself. */
29
+ readonly verifiedHost: string | null;
30
+ readonly reportedName: string | null;
31
+ readonly reportedUri: string | null;
32
+ readonly redirectUri: string;
33
+ }
34
+ /** The capability rows: only what the caller reaches, grouped, counted. */
35
+ export declare function consentCapabilities(tools: readonly AppTool[], caller: ToolCaller): ConsentCapability[];
36
+ /**
37
+ * Each scope the client asked for, and what approving does with it. **A request the user cannot give is explained,
38
+ * not hidden**: the client named it, so saying it is not granted discloses nothing, and leaving it off would let the
39
+ * user believe they had granted it.
40
+ */
41
+ export declare function consentScopes(requested: readonly string[], tools: readonly AppTool[], caller: ToolCaller): ConsentScope[];
42
+ /** Everything the consent screen shows. */
43
+ export declare function consentView(input: {
44
+ readonly client: ConsentClient;
45
+ readonly tools: readonly AppTool[];
46
+ readonly caller: ToolCaller;
47
+ readonly requestedScopes: readonly string[];
48
+ }): ConsentView;
49
+ //# sourceMappingURL=consent.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consent.d.ts","sourceRoot":"","sources":["../../src/mcp/consent.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,OAAO,EAAW,KAAK,UAAU,EAAE,MAAM,8BAA8B,CAAC;AACtF,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGrF;;;;;;;;;;;;;;;;;GAiBG;AAEH,iHAAiH;AACjH,MAAM,MAAM,gBAAgB,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;AAEtD,6CAA6C;AAC7C,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,8FAA8F;IAC9F,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,QAAQ,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED,2EAA2E;AAC3E,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,OAAO,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,iBAAiB,EAAE,CAsBtG;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,SAAS,EAAE,SAAS,MAAM,EAAE,EAC5B,KAAK,EAAE,SAAS,OAAO,EAAE,EACzB,MAAM,EAAE,UAAU,GACjB,YAAY,EAAE,CAOhB;AAED,2CAA2C;AAC3C,wBAAgB,WAAW,CAAC,KAAK,EAAE;IACjC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,SAAS,OAAO,EAAE,CAAC;IACnC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;IAC5B,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C,GAAG,WAAW,CAMd"}
@@ -0,0 +1,69 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { MCP_SCOPES } from "./provider.js";
4
+ import { mayCall } from "@pithy-sh/core/src/mcp/tools";
5
+ //#region src/mcp/consent.ts
6
+ /** The capability rows: only what the caller reaches, grouped, counted. */
7
+ function consentCapabilities(tools, caller) {
8
+ const rows = /* @__PURE__ */ new Map();
9
+ for (const tool of tools) {
10
+ const row = rows.get(tool.capability) ?? {
11
+ reachable: [],
12
+ total: 0
13
+ };
14
+ row.total += 1;
15
+ if (mayCall(tool, caller)) row.reachable.push(tool);
16
+ rows.set(tool.capability, row);
17
+ }
18
+ return [...rows.entries()].filter(([, row]) => row.reachable.length > 0).map(([capability, row]) => ({
19
+ capability,
20
+ operations: row.reachable.map((tool) => ({
21
+ tool: tool.name,
22
+ summary: tool.summary,
23
+ effect: tool.effect
24
+ })),
25
+ reachable: row.reachable.length,
26
+ total: row.total,
27
+ effects: {
28
+ writes: row.reachable.filter((tool) => tool.effect === "writes").length,
29
+ sends: row.reachable.filter((tool) => tool.effect === "sends").length,
30
+ charges: row.reachable.filter((tool) => tool.effect === "charges").length,
31
+ deletes: row.reachable.filter((tool) => tool.effect === "deletes").length
32
+ }
33
+ }));
34
+ }
35
+ /**
36
+ * Each scope the client asked for, and what approving does with it. **A request the user cannot give is explained,
37
+ * not hidden**: the client named it, so saying it is not granted discloses nothing, and leaving it off would let the
38
+ * user believe they had granted it.
39
+ */
40
+ function consentScopes(requested, tools, caller) {
41
+ return requested.map((scope) => {
42
+ if (MCP_SCOPES.includes(scope)) return {
43
+ scope,
44
+ granted: true,
45
+ reason: null
46
+ };
47
+ const tool = tools.find((entry) => entry.name === scope);
48
+ if (tool !== void 0 && !mayCall(tool, caller)) return {
49
+ scope,
50
+ granted: false,
51
+ reason: "role"
52
+ };
53
+ return {
54
+ scope,
55
+ granted: false,
56
+ reason: "unknown"
57
+ };
58
+ });
59
+ }
60
+ /** Everything the consent screen shows. */
61
+ function consentView(input) {
62
+ return {
63
+ client: input.client,
64
+ capabilities: consentCapabilities(input.tools, input.caller),
65
+ requested: consentScopes(input.requestedScopes, input.tools, input.caller)
66
+ };
67
+ }
68
+ //#endregion
69
+ export { consentCapabilities, consentScopes, consentView };
@@ -0,0 +1,35 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { AuthContext } from "@pithy-sh/core/src/http/authContext";
4
+ import type { AppTool } from "@pithy-sh/core/src/mcp/tools";
5
+ /** The identity a dispatched request runs as, or `undefined` for every request that arrived over the network. */
6
+ export declare function dispatchedAuth(request: Request): AuthContext | undefined;
7
+ /** A call's arguments, as the tool's input schema shaped them: `{ path, query, body }`. */
8
+ export interface ToolArguments {
9
+ readonly path?: Record<string, unknown>;
10
+ readonly query?: Record<string, unknown>;
11
+ readonly body?: unknown;
12
+ }
13
+ /** Split a call's arguments back out along the three keys the input schema joined them under. */
14
+ export declare function toolArguments(args: Record<string, unknown>): ToolArguments;
15
+ /**
16
+ * The URL path and query a call reaches: Hono's `:name` and `:name{pattern}` filled from `path`, each segment
17
+ * encoded so a value cannot add a segment of its own, and `query` as a search string. A value that is a dot
18
+ * segment is refused, since it would climb out of the tool's route into one that never declared itself a tool.
19
+ */
20
+ export declare function toolUrl(tool: AppTool, args: ToolArguments): string;
21
+ /**
22
+ * The request a call makes to its route, registered to run as `auth`. Refused when the URL parser would read the
23
+ * built path as any other path: whatever the reason, the request would then reach a route the tool is not.
24
+ *
25
+ * `correlation` is copied onto it — the request id as `cf-ray`, where every route reads it, and the caller's address
26
+ * and user agent — so the rows the route writes join the tool call's own. None of it is a credential.
27
+ */
28
+ export declare function dispatchRequest(origin: string, tool: AppTool, args: ToolArguments, auth: AuthContext, correlation?: Readonly<Record<string, string>>): Request;
29
+ /** A route's answer, as a tool call reports it: the status, the body parsed when it is JSON, and its size in bytes. */
30
+ export declare function dispatchedOutcome(response: Response): Promise<{
31
+ status: number;
32
+ body: unknown;
33
+ bytes: number;
34
+ }>;
35
+ //# sourceMappingURL=dispatch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../src/mcp/dispatch.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,8BAA8B,CAAC;AAoB5D,iHAAiH;AACjH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,GAAG,WAAW,GAAG,SAAS,CAExE;AAED,2FAA2F;AAC3F,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACxC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACzC,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;CACzB;AAQD,iGAAiG;AACjG,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,aAAa,CAQ1E;AA4BD;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,aAAa,GAAG,MAAM,CAqBlE;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,OAAO,EACb,IAAI,EAAE,aAAa,EACnB,IAAI,EAAE,WAAW,EACjB,WAAW,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAM,GACjD,OAAO,CAiBT;AAED,uHAAuH;AACvH,wBAAsB,iBAAiB,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,OAAO,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAYrH"}
@@ -0,0 +1,135 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
4
+ //#region src/mcp/dispatch.ts
5
+ /**
6
+ * A tool call, made as the user it acts for (`docs/AGENT-ACCESS.md` §4.1).
7
+ *
8
+ * **A call is a request to the route, through the whole app, and nothing else.** The MCP endpoint builds the
9
+ * request the route would have received from the user's own client — its method, its path with the parameters
10
+ * filled in, its query and its JSON body — and hands it to the composed app. Every middleware runs, every guard
11
+ * runs, the route's `describeRoute({ power })` gate runs, and the route's own in-handler checks run. So the tool
12
+ * does exactly what the route allows this user, and **nothing consults the token for permission**: the endpoint
13
+ * verified who the caller is, and the role decides what they may do. There is no second gate to keep in step.
14
+ *
15
+ * **Who it is, carried in process.** The request carries no credential. The verified identity rides beside it in
16
+ * a `WeakMap` keyed by the request object itself, which nothing outside this isolate can reach or forge — a header
17
+ * would be a credential a client could send. The session middleware reads it ({@link dispatchedAuth}) and publishes
18
+ * it as `c.var.auth`, exactly as it would a session it resolved.
19
+ */
20
+ const dispatched = /* @__PURE__ */ new WeakMap();
21
+ /** The identity a dispatched request runs as, or `undefined` for every request that arrived over the network. */
22
+ function dispatchedAuth(request) {
23
+ return dispatched.get(request);
24
+ }
25
+ function record(value) {
26
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
27
+ }
28
+ /** Split a call's arguments back out along the three keys the input schema joined them under. */
29
+ function toolArguments(args) {
30
+ const path = record(args.path);
31
+ const query = record(args.query);
32
+ return {
33
+ ...path === void 0 ? {} : { path },
34
+ ...query === void 0 ? {} : { query },
35
+ ...args.body === void 0 ? {} : { body: args.body }
36
+ };
37
+ }
38
+ function missing(name, tool) {
39
+ throw new ValidationError({
40
+ message: `The tool ${tool.name} needs path.${name}.`,
41
+ detail: `tool ${tool.name} (${tool.method} ${tool.path}) was called without path parameter ${name}`
42
+ });
43
+ }
44
+ function elsewhere(tool, detail) {
45
+ throw new ValidationError({
46
+ message: `The tool ${tool.name} cannot be called with that path.`,
47
+ detail: `tool ${tool.name} (${tool.method} ${tool.path}): ${detail}`
48
+ });
49
+ }
50
+ /** `.` and `..` survive `encodeURIComponent`, and the URL parser collapses them into a different route. */
51
+ function isDotSegment(segment) {
52
+ return segment === "." || segment === "..";
53
+ }
54
+ /** One path segment, encoded so it stays one segment, and refused when it is empty or a dot segment. */
55
+ function segment(name, value, tool) {
56
+ if (value.length === 0) return missing(name, tool);
57
+ if (isDotSegment(value)) return elsewhere(tool, `path.${name} is the dot segment "${value}"`);
58
+ return encodeURIComponent(value);
59
+ }
60
+ /**
61
+ * The URL path and query a call reaches: Hono's `:name` and `:name{pattern}` filled from `path`, each segment
62
+ * encoded so a value cannot add a segment of its own, and `query` as a search string. A value that is a dot
63
+ * segment is refused, since it would climb out of the tool's route into one that never declared itself a tool.
64
+ */
65
+ function toolUrl(tool, args) {
66
+ const path = tool.path.replace(/:([A-Za-z0-9_]+)(\{[^}]*\})?\??/g, (_match, name) => {
67
+ const value = args.path?.[name];
68
+ if (value === void 0 || value === null) return missing(name, tool);
69
+ return segment(name, String(value), tool);
70
+ }).replace(/\*$/, () => {
71
+ const value = args.path?.path;
72
+ if (value === void 0) return missing("path", tool);
73
+ const segments = String(value).split("/");
74
+ if (segments.some(isDotSegment)) return elsewhere(tool, "path.path holds a dot segment");
75
+ return segments.map(encodeURIComponent).join("/");
76
+ });
77
+ const search = new URLSearchParams();
78
+ for (const [key, value] of Object.entries(args.query ?? {})) {
79
+ if (value === void 0 || value === null) continue;
80
+ for (const item of Array.isArray(value) ? value : [value]) search.append(key, String(item));
81
+ }
82
+ const query = search.toString();
83
+ return query.length === 0 ? path : `${path}?${query}`;
84
+ }
85
+ /**
86
+ * The request a call makes to its route, registered to run as `auth`. Refused when the URL parser would read the
87
+ * built path as any other path: whatever the reason, the request would then reach a route the tool is not.
88
+ *
89
+ * `correlation` is copied onto it — the request id as `cf-ray`, where every route reads it, and the caller's address
90
+ * and user agent — so the rows the route writes join the tool call's own. None of it is a credential.
91
+ */
92
+ function dispatchRequest(origin, tool, args, auth, correlation = {}) {
93
+ const hasBody = args.body !== void 0 && tool.method !== "GET" && tool.method !== "HEAD";
94
+ const built = toolUrl(tool, args);
95
+ const url = new URL(built, origin);
96
+ const builtPath = built.split("?")[0] ?? built;
97
+ if (url.pathname !== builtPath) elsewhere(tool, `${builtPath} resolves to ${url.pathname}`);
98
+ const request = new Request(url, {
99
+ method: tool.method,
100
+ headers: {
101
+ ...correlation,
102
+ accept: "application/json",
103
+ ...hasBody ? { "content-type": "application/json" } : {}
104
+ },
105
+ ...hasBody ? { body: JSON.stringify(args.body) } : {}
106
+ });
107
+ dispatched.set(request, auth);
108
+ return request;
109
+ }
110
+ /** A route's answer, as a tool call reports it: the status, the body parsed when it is JSON, and its size in bytes. */
111
+ async function dispatchedOutcome(response) {
112
+ const raw = new Uint8Array(await response.arrayBuffer());
113
+ const text = new TextDecoder().decode(raw);
114
+ const bytes = raw.byteLength;
115
+ if ((response.headers.get("content-type") ?? "").includes("json")) try {
116
+ return {
117
+ status: response.status,
118
+ body: JSON.parse(text),
119
+ bytes
120
+ };
121
+ } catch {
122
+ return {
123
+ status: response.status,
124
+ body: text,
125
+ bytes
126
+ };
127
+ }
128
+ return {
129
+ status: response.status,
130
+ body: text,
131
+ bytes
132
+ };
133
+ }
134
+ //#endregion
135
+ export { dispatchRequest, dispatchedAuth, dispatchedOutcome, toolArguments, toolUrl };
@@ -0,0 +1,37 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * Who the MCP endpoint admits at all (`docs/AGENT-ACCESS.md` §4).
6
+ *
7
+ * **The default is closed.** Correct route gates are not the whole question: an endpoint that lets any signed-in
8
+ * user drive an agent against the application is remote automation of a surface built for a person at a keyboard,
9
+ * which changes rate, cost and abuse patterns even when every gate holds. So the capability is off unless composed,
10
+ * and composing it means choosing one of three floors — there is no default to fall into:
11
+ *
12
+ * - `{ power }` — a caller whose role in the acting organization holds this power.
13
+ * - `{ entitlement }` — a caller holding this entitlement, a tier floor.
14
+ * - `"signed-in"` — every signed-in user. A decision, stated in config, and `pithy doctor` says it out loud.
15
+ *
16
+ * The floor is the endpoint's, not a tool's. Above it, every tool is still gated by its own route.
17
+ */
18
+ export declare const McpFloor: z.ZodUnion<readonly [z.ZodLiteral<"signed-in">, z.ZodObject<{
19
+ power: z.ZodString;
20
+ }, z.core.$strict>, z.ZodObject<{
21
+ entitlement: z.ZodString;
22
+ }, z.core.$strict>]>;
23
+ export type McpFloor = z.infer<typeof McpFloor>;
24
+ /** What a caller holds, for {@link floorAdmits}. */
25
+ export interface FloorCaller {
26
+ /** Whether the caller's role holds a power, or `null` when no organization is in force. */
27
+ readonly roleAllows: ((power: string) => boolean) | null;
28
+ /** The entitlement keys the caller holds and that grant access now. */
29
+ readonly entitlements: () => Promise<ReadonlySet<string>>;
30
+ }
31
+ /** Whether the floor admits this signed-in caller. */
32
+ export declare function floorAdmits(floor: McpFloor, caller: FloorCaller): Promise<boolean>;
33
+ /** Whether the endpoint is open to every signed-in user. What `pithy doctor` reports. */
34
+ export declare function isOpenToEverySignedInUser(floor: McpFloor): boolean;
35
+ /** The floor in one line, for `pithy doctor` and the manifest. */
36
+ export declare function floorLine(floor: McpFloor): string;
37
+ //# sourceMappingURL=floor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"floor.d.ts","sourceRoot":"","sources":["../../src/mcp/floor.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ;;;;oBAclB,CAAC;AACJ,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,QAAQ,CAAC,CAAC;AAEhD,oDAAoD;AACpD,MAAM,WAAW,WAAW;IAC1B,2FAA2F;IAC3F,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,IAAI,CAAC;IACzD,uEAAuE;IACvE,QAAQ,CAAC,YAAY,EAAE,MAAM,OAAO,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;CAC3D;AAED,sDAAsD;AACtD,wBAAsB,WAAW,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAIxF;AAED,yFAAyF;AACzF,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAElE;AAED,kEAAkE;AAClE,wBAAgB,SAAS,CAAC,KAAK,EAAE,QAAQ,GAAG,MAAM,CAIjD"}