@dapplelight/signet-server 0.0.0-stage → 0.3.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 (171) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +799 -2
  3. package/dist/analytics/engine.d.ts +35 -0
  4. package/dist/analytics/engine.d.ts.map +1 -0
  5. package/dist/analytics/engine.js +65 -0
  6. package/dist/analytics/engine.js.map +1 -0
  7. package/dist/analytics/index.d.ts +3 -0
  8. package/dist/analytics/index.d.ts.map +1 -0
  9. package/dist/analytics/index.js +3 -0
  10. package/dist/analytics/index.js.map +1 -0
  11. package/dist/analytics/ingest.d.ts +16 -0
  12. package/dist/analytics/ingest.d.ts.map +1 -0
  13. package/dist/analytics/ingest.js +37 -0
  14. package/dist/analytics/ingest.js.map +1 -0
  15. package/dist/auth/bearer.d.ts +9 -0
  16. package/dist/auth/bearer.d.ts.map +1 -0
  17. package/dist/auth/bearer.js +31 -0
  18. package/dist/auth/bearer.js.map +1 -0
  19. package/dist/auth/better-auth.d.ts +65 -0
  20. package/dist/auth/better-auth.d.ts.map +1 -0
  21. package/dist/auth/better-auth.js +44 -0
  22. package/dist/auth/better-auth.js.map +1 -0
  23. package/dist/auth/guards.d.ts +10 -0
  24. package/dist/auth/guards.d.ts.map +1 -0
  25. package/dist/auth/guards.js +26 -0
  26. package/dist/auth/guards.js.map +1 -0
  27. package/dist/auth/hono.d.ts +13 -0
  28. package/dist/auth/hono.d.ts.map +1 -0
  29. package/dist/auth/hono.js +44 -0
  30. package/dist/auth/hono.js.map +1 -0
  31. package/dist/auth/index.d.ts +6 -0
  32. package/dist/auth/index.d.ts.map +1 -0
  33. package/dist/auth/index.js +6 -0
  34. package/dist/auth/index.js.map +1 -0
  35. package/dist/auth/passcode.d.ts +3 -0
  36. package/dist/auth/passcode.d.ts.map +1 -0
  37. package/dist/auth/passcode.js +36 -0
  38. package/dist/auth/passcode.js.map +1 -0
  39. package/dist/auth/session.d.ts +20 -0
  40. package/dist/auth/session.d.ts.map +1 -0
  41. package/dist/auth/session.js +92 -0
  42. package/dist/auth/session.js.map +1 -0
  43. package/dist/doctor/check.d.ts +36 -0
  44. package/dist/doctor/check.d.ts.map +1 -0
  45. package/dist/doctor/check.js +167 -0
  46. package/dist/doctor/check.js.map +1 -0
  47. package/dist/doctor/cli.d.ts +3 -0
  48. package/dist/doctor/cli.d.ts.map +1 -0
  49. package/dist/doctor/cli.js +45 -0
  50. package/dist/doctor/cli.js.map +1 -0
  51. package/dist/env/index.d.ts +3 -0
  52. package/dist/env/index.d.ts.map +1 -0
  53. package/dist/env/index.js +3 -0
  54. package/dist/env/index.js.map +1 -0
  55. package/dist/env/runtime.d.ts +4 -0
  56. package/dist/env/runtime.d.ts.map +1 -0
  57. package/dist/env/runtime.js +14 -0
  58. package/dist/env/runtime.js.map +1 -0
  59. package/dist/env/schema.d.ts +8 -0
  60. package/dist/env/schema.d.ts.map +1 -0
  61. package/dist/env/schema.js +48 -0
  62. package/dist/env/schema.js.map +1 -0
  63. package/dist/http/errors.d.ts +27 -0
  64. package/dist/http/errors.d.ts.map +1 -0
  65. package/dist/http/errors.js +50 -0
  66. package/dist/http/errors.js.map +1 -0
  67. package/dist/http/index.d.ts +3 -0
  68. package/dist/http/index.d.ts.map +1 -0
  69. package/dist/http/index.js +3 -0
  70. package/dist/http/index.js.map +1 -0
  71. package/dist/http/status-codes.d.ts +2 -0
  72. package/dist/http/status-codes.d.ts.map +1 -0
  73. package/dist/http/status-codes.js +13 -0
  74. package/dist/http/status-codes.js.map +1 -0
  75. package/dist/http/validate.d.ts +6 -0
  76. package/dist/http/validate.d.ts.map +1 -0
  77. package/dist/http/validate.js +42 -0
  78. package/dist/http/validate.js.map +1 -0
  79. package/dist/mcp/errors.d.ts +40 -0
  80. package/dist/mcp/errors.d.ts.map +1 -0
  81. package/dist/mcp/errors.js +69 -0
  82. package/dist/mcp/errors.js.map +1 -0
  83. package/dist/mcp/hono.d.ts +15 -0
  84. package/dist/mcp/hono.d.ts.map +1 -0
  85. package/dist/mcp/hono.js +22 -0
  86. package/dist/mcp/hono.js.map +1 -0
  87. package/dist/mcp/index.d.ts +4 -0
  88. package/dist/mcp/index.d.ts.map +1 -0
  89. package/dist/mcp/index.js +4 -0
  90. package/dist/mcp/index.js.map +1 -0
  91. package/dist/mcp/interaction.d.ts +18 -0
  92. package/dist/mcp/interaction.d.ts.map +1 -0
  93. package/dist/mcp/interaction.js +75 -0
  94. package/dist/mcp/interaction.js.map +1 -0
  95. package/dist/mcp/primitives.d.ts +84 -0
  96. package/dist/mcp/primitives.d.ts.map +1 -0
  97. package/dist/mcp/primitives.js +174 -0
  98. package/dist/mcp/primitives.js.map +1 -0
  99. package/dist/mcp/server.d.ts +88 -0
  100. package/dist/mcp/server.d.ts.map +1 -0
  101. package/dist/mcp/server.js +139 -0
  102. package/dist/mcp/server.js.map +1 -0
  103. package/dist/middleware/cors.d.ts +8 -0
  104. package/dist/middleware/cors.d.ts.map +1 -0
  105. package/dist/middleware/cors.js +19 -0
  106. package/dist/middleware/cors.js.map +1 -0
  107. package/dist/middleware/index.d.ts +5 -0
  108. package/dist/middleware/index.d.ts.map +1 -0
  109. package/dist/middleware/index.js +5 -0
  110. package/dist/middleware/index.js.map +1 -0
  111. package/dist/middleware/rate-limit-do.d.ts +23 -0
  112. package/dist/middleware/rate-limit-do.d.ts.map +1 -0
  113. package/dist/middleware/rate-limit-do.js +41 -0
  114. package/dist/middleware/rate-limit-do.js.map +1 -0
  115. package/dist/middleware/rate-limit.d.ts +23 -0
  116. package/dist/middleware/rate-limit.d.ts.map +1 -0
  117. package/dist/middleware/rate-limit.js +65 -0
  118. package/dist/middleware/rate-limit.js.map +1 -0
  119. package/dist/middleware/request-id.d.ts +8 -0
  120. package/dist/middleware/request-id.d.ts.map +1 -0
  121. package/dist/middleware/request-id.js +16 -0
  122. package/dist/middleware/request-id.js.map +1 -0
  123. package/dist/middleware/secure-headers.d.ts +11 -0
  124. package/dist/middleware/secure-headers.d.ts.map +1 -0
  125. package/dist/middleware/secure-headers.js +31 -0
  126. package/dist/middleware/secure-headers.js.map +1 -0
  127. package/dist/notify/email.d.ts +17 -0
  128. package/dist/notify/email.d.ts.map +1 -0
  129. package/dist/notify/email.js +46 -0
  130. package/dist/notify/email.js.map +1 -0
  131. package/dist/notify/index.d.ts +4 -0
  132. package/dist/notify/index.d.ts.map +1 -0
  133. package/dist/notify/index.js +4 -0
  134. package/dist/notify/index.js.map +1 -0
  135. package/dist/notify/push.d.ts +24 -0
  136. package/dist/notify/push.d.ts.map +1 -0
  137. package/dist/notify/push.js +29 -0
  138. package/dist/notify/push.js.map +1 -0
  139. package/dist/notify/telegram.d.ts +10 -0
  140. package/dist/notify/telegram.d.ts.map +1 -0
  141. package/dist/notify/telegram.js +35 -0
  142. package/dist/notify/telegram.js.map +1 -0
  143. package/dist/oauth-rs/hono.d.ts +13 -0
  144. package/dist/oauth-rs/hono.d.ts.map +1 -0
  145. package/dist/oauth-rs/hono.js +56 -0
  146. package/dist/oauth-rs/hono.js.map +1 -0
  147. package/dist/oauth-rs/index.d.ts +4 -0
  148. package/dist/oauth-rs/index.d.ts.map +1 -0
  149. package/dist/oauth-rs/index.js +4 -0
  150. package/dist/oauth-rs/index.js.map +1 -0
  151. package/dist/oauth-rs/jwks.d.ts +33 -0
  152. package/dist/oauth-rs/jwks.d.ts.map +1 -0
  153. package/dist/oauth-rs/jwks.js +105 -0
  154. package/dist/oauth-rs/jwks.js.map +1 -0
  155. package/dist/oauth-rs/metadata.d.ts +22 -0
  156. package/dist/oauth-rs/metadata.d.ts.map +1 -0
  157. package/dist/oauth-rs/metadata.js +20 -0
  158. package/dist/oauth-rs/metadata.js.map +1 -0
  159. package/dist/oauth-rs/verify.d.ts +39 -0
  160. package/dist/oauth-rs/verify.d.ts.map +1 -0
  161. package/dist/oauth-rs/verify.js +111 -0
  162. package/dist/oauth-rs/verify.js.map +1 -0
  163. package/dist/observability/logger.d.ts +40 -0
  164. package/dist/observability/logger.d.ts.map +1 -0
  165. package/dist/observability/logger.js +167 -0
  166. package/dist/observability/logger.js.map +1 -0
  167. package/dist/observability/sentry.d.ts +32 -0
  168. package/dist/observability/sentry.d.ts.map +1 -0
  169. package/dist/observability/sentry.js +76 -0
  170. package/dist/observability/sentry.js.map +1 -0
  171. package/package.json +187 -4
package/README.md CHANGED
@@ -1,3 +1,800 @@
1
- # Temporary Holding Version
1
+ # @dapplelight/signet-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Backend primitives. Auth first, because the audit found it was the most
4
+ duplicated concern with no shared implementation.
5
+
6
+ ## What the audit actually found
7
+
8
+ `STARTER-KIT-AUDIT.md` §9 claimed "6 products, 6 auth implementations, zero
9
+ overlap". That was inferred from filenames. **Reading the code corrected it:**
10
+ there are **three shapes**, and the two products with a real user system had
11
+ already converged on the same library.
12
+
13
+ | Shape | Products | Answer |
14
+ |---|---|---|
15
+ | Full user system, OAuth, user table | app-a, app-b — **both already on Better Auth** | `auth/better-auth` — defaults only, not a reimplementation |
16
+ | Shared passcode, no user table | app-c, invite tier (`pin-gate`, `LoginScreen`) | `auth/session` + `auth/passcode` |
17
+ | Single bearer token for machines | app-h, app-a API tokens | `auth/bearer` |
18
+
19
+ They are three different problems, not three failed attempts at one. This
20
+ package ships all three rather than forcing them together.
21
+
22
+ ## Modules
23
+
24
+ | Import | Deps | Use |
25
+ |---|---|---|
26
+ | `@dapplelight/signet-server/auth/session` | none | Stateless HMAC cookie session. Workers and Node. |
27
+ | `@dapplelight/signet-server/auth/passcode` | none | PBKDF2 passcode hash + constant-time verify. |
28
+ | `@dapplelight/signet-server/auth/bearer` | none | API tokens, prefixed and stored hashed. |
29
+ | `@dapplelight/signet-server/auth/guards` | none | Config guards that fail loudly. |
30
+ | `@dapplelight/signet-server/auth/better-auth` | none | Opinionated Better Auth options object. |
31
+ | `@dapplelight/signet-server/auth/hono` | `hono` (optional peer) | `requireAuth`, `requireSession`. |
32
+ | `@dapplelight/signet-server/mcp` | `@modelcontextprotocol/server` ^2.1, `zod` >=4.2 (optional peers; not `hono`) | `defineTool`, `createMcpServer`; stdio via the SDK's `serveStdio`. See [MCP servers](#mcp-servers). |
33
+ | `@dapplelight/signet-server/mcp/hono` | the above, plus `hono` | `mountMcp`, `mcpHandler`: streamable HTTP through the SDK's `createMcpHandler`, 2026-07-28 and 2025 clients, per request. |
34
+
35
+ Everything but the Hono middleware is dependency-free Web Crypto.
36
+
37
+ ## Passcode gate
38
+
39
+ ```ts
40
+ import { verifyPasscode } from "@dapplelight/signet-server/auth/passcode"
41
+ import { issueSession, sessionCookie } from "@dapplelight/signet-server/auth/session"
42
+
43
+ const opts = { cookieName: "rsvp_session", secret: env.SESSION_SECRET, sameSite: "none" as const }
44
+
45
+ if (!(await verifyPasscode(body.passcode, env.PASSCODE_HASH))) return c.json({ error: "Wrong passcode" }, 401)
46
+ c.header("Set-Cookie", sessionCookie(await issueSession(opts), opts))
47
+ ```
48
+
49
+ Generate the stored hash offline and put it in a secret — never the passcode:
50
+ ```ts
51
+ await hashPasscode("your-passcode") // -> "a1b2…:c3d4…"
52
+ ```
53
+
54
+ ## User system
55
+
56
+ ```ts
57
+ import { betterAuthDefaults, socialProviders } from "@dapplelight/signet-server/auth/better-auth"
58
+
59
+ betterAuth({
60
+ ...betterAuthDefaults(env),
61
+ database: drizzleAdapter(db, { provider: "pg", schema }),
62
+ socialProviders: socialProviders(
63
+ { google: { clientId: env.GOOGLE_CLIENT_ID, clientSecret: env.GOOGLE_CLIENT_SECRET } },
64
+ (p, reason) => logger.warn("auth.provider_skipped", { provider: p, reason }),
65
+ ),
66
+ })
67
+ ```
68
+
69
+ Returns a plain options object, so this package needs no Better Auth dependency
70
+ and no version coupling.
71
+
72
+ **Anything that changes Better Auth's behaviour is opt-in**, and the default is
73
+ Better Auth's own. An earlier version shipped app-a's settings as defaults, which
74
+ would have quietly weakened every other app. Each option says what it costs:
75
+
76
+ | Option | Effect | Cost |
77
+ |---|---|---|
78
+ | `cookieCacheSeconds` | trusts the signed cookie, skipping a DB read | a deleted account or revoked session stays signed in this long |
79
+ | `skipStateCookieCheck` | drops the OAuth state-cookie check | that check is CSRF protection on the callback |
80
+ | `sessionSeconds` | session lifetime (else `SESSION_DURATION_SECONDS`, else 7 days) | |
81
+ | `rateLimit` | Better Auth's own limiter on `/api/auth/*` | a second limiter on top of the app's |
82
+ | `baseURL`, `trustedOrigins` | override `BETTER_AUTH_URL` / `WEB_URL` and the env-built origin list | |
83
+
84
+ ## Carried forward deliberately
85
+
86
+ Things one product got right that the others lacked:
87
+
88
+ - **`isDevAuthEnabled` throws in production/staging** rather than returning false.
89
+ A dev-auth flag reaching prod is a total authentication bypass; failing the boot
90
+ is correct. From app-a, the only implementation that had this.
91
+ - **Constant-time signature compare.** app-c used `!==`, which leaks
92
+ signature bytes through response timing. `timingSafeEqual` is from app-h,
93
+ which was the only one doing it.
94
+ - **Half-configured social providers are skipped and logged**, not silently
95
+ broken at redirect time. From app-b.
96
+ - **`SameSite=None; Secure`** with optional `Domain`, for Pages → Worker
97
+ cross-origin fetches. Both user-system products needed it.
98
+ - **Tokens stored hashed** with a greppable prefix, so a database leak yields no
99
+ live credentials.
100
+
101
+ ## Not carried forward
102
+
103
+ app-a's `auth.ts` also contains households, seeded dev users, an email allowlist
104
+ with blind-index hashing, and PII encryption. Those are app-a's domain, not a
105
+ design system's — the same class of leak as the finance-green Badge default that
106
+ `@dapplelight/signet-ui` had to strip. Expose them via Better Auth's `databaseHooks` in the
107
+ app, not here.
108
+
109
+ ## Test
110
+
111
+ `bun run test` — 39 assertions covering signature tampering, expiry, wrong
112
+ secrets, constant-time compare, passcode salting, token prefixes and the
113
+ production guard.
114
+
115
+ ## HTTP — error envelope and validation
116
+
117
+ `@dapplelight/signet-server/http` is the server half of the contract in `@dapplelight/signet-lib/api`.
118
+
119
+ ```ts
120
+ import { errorHandler, ApiException } from "@dapplelight/signet-server/http"
121
+ import { parseBody } from "@dapplelight/signet-server/http/validate"
122
+
123
+ app.onError(errorHandler({
124
+ isProduction: () => getRuntimeEnv().NODE_ENV === "production",
125
+ onError: (err, meta) => captureException(err, meta),
126
+ }))
127
+
128
+ app.post("/things", async (c) => {
129
+ const body = await parseBody(c, thingSchema) // 400 + structured field errors
130
+ if (!allowed) throw new ApiException(403, "Not allowed", "NOT_IN_HOUSEHOLD")
131
+ return c.json(await create(body))
132
+ })
133
+ ```
134
+
135
+ Unhandled error messages are replaced in production — they carry connection
136
+ strings, file paths and query text. `isProduction` is a function so it is read
137
+ per request; a module-scope `process.env` read is unreliable on Workers.
138
+
139
+ Validation failures put `flatten()` output in `details`, where the envelope has
140
+ a place for it. app-a stringified it into the message field, forcing the client
141
+ to `JSON.parse` an error string to render field errors.
142
+
143
+ ## Env — Workers-safe configuration
144
+
145
+ ```ts
146
+ import { initRuntimeEnv, createEnv } from "@dapplelight/signet-server/env"
147
+
148
+ export default {
149
+ fetch(req, env, ctx) {
150
+ initRuntimeEnv(env) // first thing — Workers pass secrets here, not process.env
151
+ return app.fetch(req, env, ctx)
152
+ },
153
+ }
154
+
155
+ export const env = createEnv(
156
+ z.object({ DATABASE_URL: z.string().url(), SENTRY_DSN: z.string().url().optional() }),
157
+ { optionalFeatures: [["SENTRY_DSN", "error reporting"]] },
158
+ )
159
+ ```
160
+
161
+ `createEnv` validates on **first property access**, not at import. Cloudflare runs
162
+ top-level module code during deploy validation with no secrets injected, so
163
+ eager validation fails the deploy of a working Worker. From app-a, which was the
164
+ only product that had hit this.
165
+
166
+ `getRuntimeEnv()` merges injected bindings over `process.env`, injected winning.
167
+ app-a's version short-circuited to `process.env` whenever Bun was present, which
168
+ silently discarded injected values when running a Worker locally under Bun.
169
+
170
+ ## Middleware
171
+
172
+ ```ts
173
+ app.use("*", requestId({ childLogger: (id) => logger.child({ reqId: id }) }))
174
+ app.use("*", secureHeaders({ relaxedPaths: ["/docs", "/openapi.json"] }))
175
+ app.use("*", corsMiddleware({ originEnvKeys: ["WEB_URL", "ADMIN_URL"] }))
176
+ app.use("/api/*", rateLimit({ max: 100, windowSeconds: 60 }))
177
+ app.use("/api/auth/login", rateLimit({
178
+ scope: "login", max: 5, windowSeconds: 60,
179
+ store: (c) => durableObjectStore(c.env.RATE_LIMIT), // built per request: bindings live on c.env
180
+ failOpen: false, // a login limit is a security control
181
+ }))
182
+ ```
183
+
184
+ ### Rate limiting has a pluggable store, on purpose
185
+
186
+ The audit found two implementations with opposite tradeoffs. app-a used an
187
+ in-memory Map — fast, zero setup, but **per-isolate on Workers**, so the real
188
+ limit is `max × isolates`. app-c used D1 — correct across isolates, costs
189
+ a query.
190
+
191
+ Neither is wrong. `memoryStore()` (the default) is fine for smoothing general
192
+ API traffic. **A login limiter needs a durable store**, or an attacker just
193
+ spreads attempts across POPs.
194
+
195
+ **For an exact count on Workers, use the Durable Object store.** Cloudflare's
196
+ rate-limit binding is approximate too: app-b saw it allow 300 of 300
197
+ requests on workers.dev. `@dapplelight/signet-server/middleware/rate-limit-do` has a
198
+ `RateLimitCounter` class (one object per `scope:key`, so the count is exact) and
199
+ `durableObjectStore(namespace)`. Export the class from your worker entry and bind
200
+ it; the module's header has the wrangler config. Checked on workerd: 300
201
+ concurrent requests against `max: 100` gave exactly 100 allowed, 200 limited.
202
+
203
+ **A store failure fails open by default** — a limiter outage should not take the
204
+ API down. Only the store call is guarded, so a handler error is never retried or
205
+ mistaken for one. Set `failOpen: false` where the limit is the security control;
206
+ the request then gets a 503 `RATE_LIMIT_UNAVAILABLE`. `onStoreError` hears about
207
+ every failure either way.
208
+
209
+ A 429 carries `code: "RATE_LIMITED"` and the `requestId`, like every other error.
210
+
211
+ **Check the setup with `npx signet-doctor [dir]`.** The Durable Object needs a
212
+ binding and a migration in wrangler config and an export from the Worker entry —
213
+ three places no library can reach, each failing differently when wrong. The
214
+ doctor checks all three, that the code's `c.env.X` matches the binding, and that
215
+ the entry exports no plain values, and prints the snippet for each gap —
216
+ including swapping out hono-rate-limiter's `DurableObjectRateLimiter`. Exits 1
217
+ on a problem, so it fits in CI. `create-signet-app --template api` scaffolds a
218
+ Worker that passes it.
219
+
220
+ **Your own request-id middleware?** `errorHandler` and `rateLimit` read
221
+ `c.get("reqId")` by default; pass `getRequestId: (c) => ...` to either. Pass your
222
+ app's env type, `rateLimit<AppEnv>({...})`, for typed variables in `keyFor`,
223
+ `store` and `onStoreError`. `X-RateLimit-Reset` is epoch seconds (GitHub's
224
+ convention), not the IETF draft's seconds-from-now `RateLimit-Reset`.
225
+
226
+ **A dependency being down** is a deliberate error, not a crash: `throw new
227
+ ApiException(503, "Store unreachable", "STORE_UNAVAILABLE")`. `ApiException`
228
+ accepts 502, 503 and 504 for this, and does not go to `onError`.
229
+
230
+ `clientIp()` prefers `CF-Connecting-IP`, which the edge sets and a client cannot
231
+ spoof, and only falls back to `x-forwarded-for`, which a client *can*. Do not
232
+ reorder those.
233
+
234
+ 429s use the same error envelope as everything else, so the client's `ApiError`
235
+ path handles them without a special case.
236
+
237
+ ## Logging
238
+
239
+ ```ts
240
+ import { createLogger, type Logger } from "@dapplelight/signet-server/observability/logger"
241
+ import { requestId } from "@dapplelight/signet-server/middleware/request-id"
242
+
243
+ export const log = createLogger({ level: "info", base: { service: "api" } })
244
+
245
+ const app = new Hono<{ Variables: { reqId: string; logger: Logger } }>()
246
+ app.use("*", requestId({ childLogger: (id) => log.child({ reqId: id }) }))
247
+ app.get("/x", (c) => {
248
+ c.get("logger").info({ userId: "u1" }, "handled")
249
+ return c.text("ok")
250
+ })
251
+ ```
252
+
253
+ ```json
254
+ {"level":"info","time":"2026-09-25T07:15:49.201Z","msg":"handled","service":"api","reqId":"9f3c…","userId":"u1"}
255
+ ```
256
+
257
+ One JSON line per entry, written through `console`, with no dependencies. pino
258
+ is Node-flavoured: its pretty transport needs `worker_threads`, which is why
259
+ app-a deploys with `--external:pino-pretty --external:worker_threads`.
260
+
261
+ - **pino's call shapes**: `log.info({ ...fields }, "msg")`, `log.info("msg")`,
262
+ `log.error(err, "msg")` (the error goes under `err`), and also
263
+ `log.info("msg", { ...fields })`, app-b's. `trace` to `fatal`.
264
+ printf interpolation (`%s`) is not supported.
265
+ - **Levels are live.** `log.level = cfEnv.LOG_LEVEL` takes a string and throws
266
+ on an unknown one. A child follows its parent's level, including later
267
+ changes, until given its own (`child.level = …` or `child(b, { level })`).
268
+ `silent` writes nothing.
269
+ - **Secrets are redacted by default**, at any depth: in fields, child bindings,
270
+ arrays, `Headers`, `Map`s and error properties. The keys are password,
271
+ passwd, token, secret, authorization, cookie and apiKey. Matching ignores
272
+ case, `_` and `-`, and takes suffixes, so `accessToken`, `x-api-key` and
273
+ `set-cookie` are covered while `maxTokens` is not. `redact: ["email",
274
+ "user.phone", "items.*.card"]` adds a key name (any depth) or a path from the
275
+ top of the fields. Values become `"[redacted]"`. Strings are not scanned: a
276
+ secret inside `msg` or an error message goes out as written.
277
+ - **Errors** anywhere in the fields become `{ name, message, stack, cause,
278
+ ...own props }`. `production: true` drops `stack`.
279
+ - **It never throws on data.** Cycles become `"[Circular]"`, bigints become
280
+ strings, functions are dropped. A throwing getter still yields the line, with
281
+ a `logError` field saying why the fields are missing.
282
+ - **`write(line, level)`** defaults to `console.error` for error and fatal,
283
+ `console.warn` for warn and `console.log` otherwise; Workers Logs takes
284
+ severity from the console method. `messageKey` renames `msg`.
285
+ - **`redactFields(ctx)`** is the same cleaning on its own, for context sent
286
+ elsewhere: `createSentry` scrubs error text but not context.
287
+ - It takes config and never reads env.
288
+
289
+ ### Migrating app-a: yes, it can drop pino
290
+
291
+ `lib/logger.ts` (30 lines) becomes:
292
+
293
+ ```ts
294
+ import { createLogger } from "@dapplelight/signet-server/observability/logger"
295
+ import { getRuntimeEnv } from "./runtime-env"
296
+
297
+ export const logger = createLogger({ level: getRuntimeEnv().LOG_LEVEL ?? "info" })
298
+ ```
299
+
300
+ Every call site keeps working. They are all `(fields, msg)`, `(fields)` or
301
+ `(msg)`, and none uses `%s`. `index.ts`'s per-fetch `logger.level =
302
+ cfEnv.LOG_LEVEL` compiles as is, and `middleware/request-id.ts` does not change.
303
+ Remove `pino` and `pino-pretty` from `package.json`, and both `--external` flags
304
+ from `deploy:api`. `{ err: e }` still serialises the error.
305
+
306
+ If anything reads the logs, four things change on the wire: `level` is
307
+ `"info"`, not `30`; `time` is ISO, not epoch ms; there is no `pid` or
308
+ `hostname`; and the error has `name` where pino's serializer wrote `type`. The
309
+ loss is pino-pretty's coloured local output. A `write` for local dev covers most
310
+ of it:
311
+
312
+ ```ts
313
+ write: isDev
314
+ ? (line) => {
315
+ const { level, time, msg, ...rest } = JSON.parse(line)
316
+ console.log(`${time.slice(11, 19)} ${level.toUpperCase().padEnd(5)} ${msg ?? ""}`, rest)
317
+ }
318
+ : undefined,
319
+ ```
320
+
321
+ Unlike pino as app-a configured it, which had no `redact`, it redacts by default.
322
+
323
+ ### Migrating app-b
324
+
325
+ Its call sites are `logger.info("event", fields)`, not pino's shape. That form
326
+ is supported, so they stay. `packages/observability/src/logger.ts` (43 lines)
327
+ becomes a shim that keeps the `event` key and writes every line to
328
+ `console.log`, because `index.test.ts` captures `console.log`, error lines
329
+ included:
330
+
331
+ ```ts
332
+ import { createLogger as create, type Logger } from "@dapplelight/signet-server/observability/logger"
333
+ import type { RunContext } from "./context"
334
+
335
+ export type { Logger }
336
+ export { redactFields as redact } from "@dapplelight/signet-server/observability/logger"
337
+
338
+ export const createLogger = (context: RunContext, write = (line: string) => console.log(line)): Logger =>
339
+ create({ base: context, messageKey: "event", write })
340
+ ```
341
+
342
+ `context.ts` and `hono.ts` stay: the `req_` and `trace_` ids, the `traceparent`
343
+ parse and the request start and complete lines belong to it. Three things
344
+ change. The line has `time`, not `timestamp`. The censor is `"[redacted]"`, not
345
+ `"[REDACTED]"`, which is one assertion in `logger.test.ts`. And a sink now
346
+ receives the JSON line, so that test pushes `JSON.parse(line)`. Its old
347
+ redaction matched a secret word anywhere in a top-level key: `tokenCount` was
348
+ redacted and a nested `apiKey` was not. This one matches the suffix at any
349
+ depth. It gains level filtering and error serialisation, so `request.failed`
350
+ can log the error itself instead of `error.message`.
351
+
352
+ ## Notifications and reporting
353
+
354
+ ```ts
355
+ import { createEmailer } from "@dapplelight/signet-server/notify/email"
356
+ import { createTelegram } from "@dapplelight/signet-server/notify/telegram"
357
+ import { createPusher } from "@dapplelight/signet-server/notify/push"
358
+ import { createSentry } from "@dapplelight/signet-server/observability/sentry"
359
+ ```
360
+
361
+ All plain `fetch` — they run on Workers, where the official Sentry SDK does not.
362
+ All return `false` rather than throwing: a failed notification must not fail the
363
+ request that triggered it.
364
+
365
+ **`createPusher` prunes dead subscriptions.** A push endpoint returning 404 or
366
+ 410 is permanently gone, and one that is never pruned is retried on every future
367
+ notification forever. A transient 500 is *not* pruned. VAPID signing is injected
368
+ rather than implemented, because `web-push` is Node-only and would make this
369
+ module unusable on Workers.
370
+
371
+ **`createTelegram` is operator-level only.** The chat is a single owned channel,
372
+ so no user or household data belongs in it — amounts, names, account
373
+ identifiers. Use push for per-user messages. That warning is carried from
374
+ app-a, where it was the reason the two were separate functions.
375
+
376
+ `createSentry` takes configuration rather than reading a module-level env
377
+ singleton, which is what made app-a's version untestable and non-portable.
378
+
379
+ **Error text is scrubbed before it leaves.** Messages and stacks routinely
380
+ carry credentials and personal data — a failed query with an email in it, a URL
381
+ with a token. `redactSecrets` runs over both by default (bearer tokens, JWTs,
382
+ `password=`/`token:`-style secrets, emails, 9+ digit runs). Pass `scrub` to
383
+ extend it, `includeStack: false` to drop stacks, and `beforeSend` to allowlist
384
+ context or drop an event (`return null`). Context values are not scrubbed —
385
+ pass only what you mean to send.
386
+
387
+ **`captureException` returns its request — keep it alive on Workers.** It
388
+ resolves to whether Sentry accepted the event and never rejects. A Worker's
389
+ isolate is frozen once the response is sent, so an unawaited report is cut off
390
+ mid-flight; pass it to `ctx.waitUntil`. `errorHandler` does this for you when
391
+ `onError` returns the promise, as in the example above. Do not sleep instead.
392
+
393
+ ```ts
394
+ c.executionCtx.waitUntil(sentry.captureException(err, { job: "sync" }))
395
+ ```
396
+
397
+ ### Not lifted
398
+
399
+ `scheduled.ts` is a map from cron expressions to app-a's own task names
400
+ (`zerodha-sync`, `monthly-reports`). The pattern is trivial and the content is
401
+ entirely product-specific, so there is nothing general to share.
402
+
403
+ ## OAuth 2.1 resource server
404
+
405
+ For making a product **agent-reachable**: an MCP server, or any API an agent
406
+ calls holding a token someone else issued. This is the opposite side from
407
+ `auth/` — that logs users in; this accepts tokens minted elsewhere.
408
+
409
+ ```ts
410
+ import { createTokenVerifier } from "@dapplelight/signet-server/oauth-rs"
411
+ import { registerProtectedResourceMetadata, requireToken, requireScopes }
412
+ from "@dapplelight/signet-server/oauth-rs/hono"
413
+
414
+ const RESOURCE = "https://mcp.example.com"
415
+ const META = `${RESOURCE}/.well-known/oauth-protected-resource`
416
+
417
+ registerProtectedResourceMetadata(app, {
418
+ resource: RESOURCE,
419
+ authorizationServers: ["https://auth.example.com"],
420
+ scopesSupported: ["read", "write"],
421
+ })
422
+
423
+ const verifier = createTokenVerifier({
424
+ issuer: "https://auth.example.com",
425
+ audience: RESOURCE, // REQUIRED — see below
426
+ jwksUri: "https://auth.example.com/.well-known/jwks.json",
427
+ })
428
+
429
+ app.use("/mcp/*", requireToken({ verifier, resourceMetadataUrl: META }))
430
+ app.post("/mcp/orders", requireScopes(META, "write"), handler)
431
+ ```
432
+
433
+ ### The audience check is the whole point
434
+
435
+ `audience` is required, not optional. A token signed by the correct issuer but
436
+ minted for a **different** resource passes signature and expiry checks and looks
437
+ entirely valid. Omit the `aud` check and you have an open door that passes every
438
+ test you are likely to write — any token from that issuer, for any service, is
439
+ accepted.
440
+
441
+ RFC 8707 exists for this. The test suite mints a real token for a different
442
+ audience and asserts rejection, because a positive test cannot catch this.
443
+
444
+ ### What else is enforced
445
+
446
+ - **Algorithm allow-list.** `none` and symmetric algorithms are rejected before
447
+ key selection — the classic alg-confusion bypass. Asserted for both.
448
+ - **Issuer, expiry, not-before, subject**, with configurable clock skew.
449
+ - **Scope step-up.** A 403 carries `WWW-Authenticate` naming the scope required,
450
+ so a client can request a new token instead of just failing.
451
+ - **Key rotation.** An unknown `kid` triggers a refetch, rate-limited to once a
452
+ minute. That is a deliberate tradeoff and both halves are tested: 20 bogus
453
+ `kid`s cause at most one fetch, and a rotated key is picked up once the
454
+ cooldown passes. A rotation can therefore fail for up to a minute; lower
455
+ `minRefetchSeconds` if that matters more than the flood guard.
456
+ - **The raw token never reaches the context.** Only claims are set, so
457
+ forwarding a client's token to a provider is harder to do by accident.
458
+
459
+ ### Not included
460
+
461
+ Token introspection (RFC 7662) for opaque tokens — this verifies JWTs locally.
462
+ Dynamic client registration. Being an authorization server; this is only the
463
+ resource side.
464
+
465
+ ## MCP servers
466
+
467
+ `@dapplelight/signet-server/mcp` and `/mcp/hono`: typed tools on the official MCP
468
+ TypeScript SDK **v2** (`@modelcontextprotocol/server` `^2.1`), served over
469
+ streamable HTTP from a Hono route or over stdio. One endpoint serves both
470
+ protocol eras, per request:
471
+
472
+ - **2026-07-28**, the stateless revision: no `initialize` and no
473
+ `Mcp-Session-Id`; each request carries its version, client info and
474
+ capabilities in `_meta`; `server/discover` replaces the handshake; results
475
+ carry `resultType`; `Mcp-Method` / `Mcp-Name` headers are required.
476
+ - **2025-era** clients (up to 2025-11-25), through the SDK's stateless legacy
477
+ fallback: `initialize` and every other request answered by a fresh server.
478
+
479
+ The SDK does all of that; Signet adds typed tools, the error envelope, scope
480
+ checks and the per-request Hono context. `@modelcontextprotocol/server` and
481
+ `zod` (`>=4.2`) are optional peers; `hono` is one for `/mcp/hono` only. `/mcp`
482
+ imports hono for types alone and recognises an `HTTPException` (or
483
+ `ApiException`) by shape, so a stdio server built with `createMcpServer` loads
484
+ without hono installed.
485
+
486
+ ```ts
487
+ import { ApiException } from "@dapplelight/signet-server/http"
488
+ import { defineTool } from "@dapplelight/signet-server/mcp"
489
+ import { mountMcp } from "@dapplelight/signet-server/mcp/hono"
490
+ import { registerProtectedResourceMetadata, requireToken } from "@dapplelight/signet-server/oauth-rs/hono"
491
+
492
+ const RESOURCE = "https://api.example.com/mcp"
493
+ const META = "https://api.example.com/.well-known/oauth-protected-resource"
494
+
495
+ // Module scope: defined once, shared by every request.
496
+ const tools = [
497
+ defineTool({
498
+ name: "get_order",
499
+ description: "Read back an order by id.",
500
+ input: z.object({ id: z.string().uuid(), expand: z.boolean().default(false) }),
501
+ scopes: ["orders:read"], // checked against the verified token
502
+ annotations: { readOnlyHint: true },
503
+ handler: async ({ id, expand }, { token, c }) => { // typed from the schema
504
+ const order = await ordersFor(c!.env).get(id, token!.claims.sub)
505
+ if (!order) throw new ApiException(404, "Order not found", "ORDER_NOT_FOUND")
506
+ return expand ? order : { id: order.id, status: order.status } // sent as JSON text
507
+ },
508
+ }),
509
+ ]
510
+
511
+ registerProtectedResourceMetadata(app, {
512
+ resource: RESOURCE,
513
+ authorizationServers: ["https://auth.example.com"],
514
+ })
515
+ mountMcp(app, "/mcp", {
516
+ name: "orders",
517
+ version: "1.0.0",
518
+ tools,
519
+ middleware: [requireToken({ verifier, resourceMetadataUrl: META })], // verifier as above
520
+ onError: (err, { tool }) => sentry.captureException(err, { tool }),
521
+ })
522
+ ```
523
+
524
+ **Typed output.** Give a tool `output: z.object(...)` beside `input` and it is
525
+ advertised as `outputSchema`; the handler must then return `z.input` of it (or a
526
+ promise of it, or a `toolResult`), which is sent as `structuredContent` plus the
527
+ same JSON as a text block for older clients. The SDK validates it against the
528
+ schema and answers a mismatch, or a `toolResult` without `structuredContent`, with
529
+ an `Output validation error` result; error results are exempt. `title` and
530
+ `annotations` are forwarded too, and tools list in the order of the array.
531
+
532
+ **Unlisted tools.** `listed: false` keeps a tool callable, with scopes, input
533
+ validation and error mapping unchanged, but leaves it out of `tools/list`. Use it
534
+ for deprecated aliases that old clients still call. The SDK's `disable()` does not
535
+ work for this, because it also refuses the call. Signet filters the SDK's own
536
+ list, so the listed tools, their order, and the 2026-07-28 `resultType`,
537
+ `ttlMs` and `cacheScope` fields are unchanged.
538
+
539
+ **Resources and prompts.** `createMcpServer({ tools, resources, prompts })`
540
+ takes both, with the same `scopes`, `mapError` and `onError` as tools:
541
+
542
+ ```ts
543
+ import { definePrompt, defineResource } from "@dapplelight/signet-server/mcp"
544
+
545
+ const resources = [
546
+ defineResource({ name: "categories", uri: "app://categories", read: () => api.categories() }),
547
+ defineResource({
548
+ name: "transaction",
549
+ template: "app://transactions/{id}",
550
+ scopes: ["finance:read"],
551
+ read: ({ variables }) => api.transaction(variables.id), // null means not found
552
+ }),
553
+ ]
554
+ const prompts = [
555
+ definePrompt({
556
+ name: "monthly_review",
557
+ args: z.object({ month: z.string() }), // prompt arguments are strings
558
+ render: ({ month }) => `Review ${month}. Call \`get_report\` first.`,
559
+ }),
560
+ ]
561
+ ```
562
+
563
+ - `read` returns an object (JSON), a string (text/plain), bytes (a blob),
564
+ `resourceResult(...)` for an exact result, or null for not found. `mimeType`
565
+ overrides the type. A template's optional `list` adds its instances to
566
+ resources/list; without the scope, it lists nothing.
567
+ - `render` returns a string (one user message), a list of strings and
568
+ messages, or a whole `GetPromptResult`.
569
+ - A failed read or render is a JSON-RPC error, since the protocol has no error
570
+ result for these: `CODE: message`, with the envelope in `data`. It uses -32603
571
+ for a 5xx and -32602 otherwise, and "Internal error" with no data for anything
572
+ unexpected. `onError` hears the last case with `meta.kind` set to "resource"
573
+ or "prompt". `errorResult` is for tools only.
574
+ - The resources and prompts capabilities are declared only when there are
575
+ some, with `listChanged: false`, like tools.
576
+
577
+ **Confirm before a destructive action, and report progress.** Plain
578
+ functions a handler calls with its `ToolContext` — no new registration shape:
579
+
580
+ ```ts
581
+ import { confirm, isConfirmPending, progress } from "@dapplelight/signet-server/mcp"
582
+
583
+ createMcpServer({
584
+ name, version, tools,
585
+ confirm: { key: process.env.CONFIRM_KEY }, // >= 32 bytes; binds the answer to the args below
586
+ })
587
+
588
+ // in a tool's handler:
589
+ handler: async (input, ctx) => {
590
+ const ok = await confirm(ctx, { message: `Delete ${input.count} transactions?`, args: input })
591
+ if (isConfirmPending(ok)) return ok // ask, then retry on the client's answer
592
+ if (ok === "unsupported") {
593
+ if (!input.confirmDeleteAll) return "Pass confirmDeleteAll to delete without asking."
594
+ } else if (ok !== "confirmed") {
595
+ return "Cancelled."
596
+ }
597
+ for (let i = 0; i < input.count; i++) {
598
+ await deleteOne(i)
599
+ await progress(ctx, i + 1, input.count) // no-op if the caller sent no progressToken
600
+ }
601
+ return "Deleted."
602
+ }
603
+ ```
604
+
605
+ `confirm` is built on the SDK's multi-round-trip input (`inputRequired`), not
606
+ a new mechanism, and resolves to one of three outcomes:
607
+
608
+ - `"unsupported"` — the client declared no elicitation capability. `confirm`
609
+ never asks it (that would only hang or error); fall back to the tool's own
610
+ pre-confirmation flag or a dry-run step, the way a client with no
611
+ multi-round-trip support has always been handled.
612
+ - `"declined"` — a no, a cancel, or (see below) an accepted answer that no
613
+ longer matches what was asked about.
614
+ - `"confirmed"` — only this means run the action.
615
+
616
+ With `createMcpServer`'s `confirm.key` configured and `args` passed to
617
+ `confirm`, the accepted answer is cryptographically bound (the SDK's
618
+ `createRequestStateCodec`, HMAC-SHA256, fail-closed) to a fingerprint of
619
+ those exact arguments: a client that gets "yes" for one call and replays
620
+ that answer against a different one — Codex flagged this forgeability
621
+ concern in an app's own hand-rolled version — reads as `"declined"`, not
622
+ `"confirmed"`. Without a key, `confirm` still asks and still resolves to all
623
+ three outcomes, but cannot detect that swap.
624
+
625
+ `progress` sends the spec's `notifications/progress`, once per call, and
626
+ never throws (a client that dropped the connection mid-import must not fail
627
+ the import).
628
+
629
+ `mountMcp` routes GET, POST and DELETE through the middleware, in order, to
630
+ `mcpHandler`, so auth runs before MCP does and an unauthenticated GET is a 401,
631
+ not a 405. Use `mcpHandler(options)` directly to place it yourself, or pass
632
+ `server: (c, { era }) => McpServer` instead of `tools` to build the server in
633
+ full (subscriptions, completions, anything the kit does not wrap) — a new one per
634
+ call.
635
+
636
+ `http` is passed to the SDK's `createMcpHandler`: `legacy: "reject"` makes the
637
+ endpoint 2026-07-28 only (a 2025 client gets `-32022`), `responseMode: "sse"`
638
+ always streams, and `maxRequestBodySize` / `keepAliveMs` / `onerror` are the
639
+ SDK's.
640
+
641
+ ### stdio
642
+
643
+ app-a's server is stdio. The same tools, through the SDK's `serveStdio`, which
644
+ also serves both eras — the connection's first message picks one:
645
+
646
+ ```ts
647
+ import { serveStdio } from "@modelcontextprotocol/server/stdio"
648
+ import { createMcpServer } from "@dapplelight/signet-server/mcp"
649
+
650
+ serveStdio(() => createMcpServer({ name: "app-a", version: "1.0.0", tools, errorResult, onError }))
651
+ ```
652
+
653
+ A stdio tool gets no `c` and no `token`; a scoped tool is refused there. The
654
+ factory is called once per connection (and once more for a `server/discover`
655
+ probe that the client then abandons for `initialize`), so keep it cheap —
656
+ building from a module-scope `tools` array is.
657
+
658
+ ### A handler per request, never shared
659
+
660
+ A Hono route gets a fresh `createMcpHandler` and a fresh McpServer for every
661
+ request, built by a factory that closes over that request's `c` and verified
662
+ token. That is what app-b settled on for Workers, where one isolate
663
+ serves many users, and it is the only way to reach `c` from a tool: the SDK's
664
+ factory sees the raw `Request` alone, and on the legacy leg a clone of it. The
665
+ **tools** are the shared part, and each handler gets its request through
666
+ `ctx`: `c` (bindings, variables), `token` (claims from `requireToken`, never the
667
+ raw token), `signal`, and `mcp`, the SDK's own handler context
668
+ (`mcp.mcpReq.envelope` for the 2026 per-request client info,
669
+ `mcp.mcpReq.inputResponses`, `mcp.http?.req`). Building the handler and a server
670
+ from 120 tools and listing them takes about 4 ms (the tests print it).
671
+
672
+ The SDK now answers what the kit used to hand-roll: GET and DELETE (2025
673
+ session operations) get its 405, `server/discover` and the 2026 header checks
674
+ are its own, and a 2026 POST without `Mcp-Method`, or with an `Mcp-Name` that
675
+ disagrees with the body, is refused before a tool runs.
676
+
677
+ The tool list is advertised as fixed (`tools: { listChanged: false }`), so a
678
+ 2026 client opens no `subscriptions/listen` stream waiting for a change that
679
+ cannot come — and a Worker is not billed for holding one open.
680
+
681
+ **Response shape.** A 2026 request is answered with one JSON body unless a tool
682
+ sends progress first (`responseMode: "auto"`). A 2025 request is answered as a
683
+ short SSE stream that closes after the result: that is the SDK's stateless
684
+ fallback, and unlike 0.1.x there is no JSON-only mode for it.
685
+
686
+ **Not `@modelcontextprotocol/hono`.** Its `createMcpHonoApp` builds an app of
687
+ its own rather than a route on yours, and its Host/Origin validators — DNS
688
+ rebinding protection, which matters for a server bound to localhost, not a
689
+ public Worker — wrap helpers `@modelcontextprotocol/server` already exports.
690
+ If a local server needs them, put `hostHeaderValidation(...)` from that package
691
+ in `middleware`.
692
+
693
+ ### Errors
694
+
695
+ A handler throws; the client gets an MCP error result (`isError: true`), with
696
+ `CODE: message` as text and the Signet envelope as `structuredContent`:
697
+
698
+ | Thrown | Result |
699
+ |---|---|
700
+ | `ApiException(404, "Order not found", "ORDER_NOT_FOUND")` | its code, message and `details` |
701
+ | Hono `HTTPException` (by shape: a numeric `status` and `getResponse()`, or the name) | code from the status, as `errorHandler` does |
702
+ | a `ZodError` (by shape, any copy of zod) | `VALIDATION_FAILED` with `fieldErrors` |
703
+ | your own type | whatever `mapError` returns for it; undefined falls through |
704
+ | anything else | `INTERNAL_ERROR: Internal error`, and the error goes to `onError` |
705
+
706
+ An unknown error's message never reaches the client, in any environment: the
707
+ SDK's own fallback sends `error.message` verbatim, connection strings included.
708
+ A missing scope is `insufficient_scope`, naming the scope, and a scoped tool
709
+ called with no token is refused, not allowed. `onError`'s promise goes to
710
+ `waitUntil`, as with `errorHandler`. The results are the same in both eras.
711
+
712
+ **Bad input never reaches a handler.** The SDK validates arguments against the
713
+ schema first and answers with its own error result, text starting `Input
714
+ validation error:` and naming the field. That result has no `code`: the SDK's
715
+ validation is private and runs before any hook. **An unknown tool** is a
716
+ JSON-RPC `-32602` error in SDK v2, not an `isError` result as in v1.
717
+
718
+ A proxy to an API built on `@dapplelight/signet-lib/api` passes the upstream code
719
+ through:
720
+
721
+ ```ts
722
+ mapError: (e) => (e instanceof ApiError ? { code: e.code ?? "HTTP_ERROR", message: e.message } : undefined)
723
+ ```
724
+
725
+ **Keeping an existing error shape.** An app moving onto `createMcpServer` whose
726
+ clients (or the LLM) already read its error text can build the whole result
727
+ with `errorResult(err, { tool })`. It runs first, before `mapError` and the
728
+ table above; a returned result is sent as-is, undefined falls through to them.
729
+ app-a keeps its plain `{ content: [{ type: "text", text: err.message }], isError: true }`:
730
+
731
+ ```ts
732
+ errorResult: (err) =>
733
+ toolResult({ isError: true, content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }] }),
734
+ ```
735
+
736
+ The result is byte-identical, in both eras, to what the SDK sends for that
737
+ object returned from a raw `registerTool` callback. It sends every message
738
+ verbatim, including the unexpected ones the default would hide, so only use it
739
+ where that is already the case. Reporting does not change: `onError` still gets
740
+ exactly the errors that would otherwise have been `Internal error` (not claimed
741
+ by `mapError` or the defaults), whether or not `errorResult` answered them. An
742
+ `errorResult` that throws counts as undefined. It never sees a missing scope or
743
+ the SDK's input validation; those keep their own results.
744
+
745
+ ### Why `defineTool` and not `server.registerTool`
746
+
747
+ In SDK v1, `registerTool` was generic over the zod shape through its v3/v4
748
+ compat types, and app-a's `tsc` ran out of memory on it at ~80 tools — so app-a
749
+ typed its server as a local interface with `handler: (args: any)` and
750
+ `@ts-nocheck` on the wiring, giving up the typed input its schemas existed for.
751
+ v2's `registerTool` is generic over Standard Schema instead and is cheap: on
752
+ TypeScript 7 and zod 4.6, calling it directly for the fixture's 120 tools
753
+ checks in 0.04 s (68k instantiations), against 0.08 s for the fixture through
754
+ `defineTool`. `defineTool` stays for what it gives beyond that: one array type
755
+ for tools with different schemas, so a module-scope `tools` list can be shared
756
+ by the HTTP route and stdio, and handlers typed as `z.output` of the tool's
757
+ own schema. `createMcpServer` registers through an erased signature, so the
758
+ SDK's generic is never instantiated whatever its types do next.
759
+
760
+ `input` must be a `z.object(...)`; omit it for a tool with no arguments (the
761
+ SDK then calls back with `ctx` alone; `createMcpServer` still hands the handler
762
+ `{}` and a `ToolContext`). A handler's return value is sent as one text block,
763
+ a string as-is and anything else as JSON; return `toolResult({...})` to send an
764
+ exact `CallToolResult`. The SDK adds `resultType` on 2026-07-28 results.
765
+
766
+ **Multi round-trip.** A handler may `return inputRequired({...})` (from
767
+ `@modelcontextprotocol/server`) to ask the client for input; it passes through
768
+ untouched, the client answers, and the retried call reads the answer from
769
+ `ctx.mcp.mcpReq.inputResponses` (the tests do this with a 2026 client over
770
+ HTTP). For 2025 clients the SDK's legacy shim turns it into real
771
+ server-to-client requests, which needs a connection: over stdio it works, but
772
+ over stateless HTTP the SDK documents a clean capability refusal instead.
773
+ Signet's tests do not cover the 2025 paths.
774
+
775
+ ### zod: one copy, 4.2 or later
776
+
777
+ The SDK converts each tool's schema to JSON Schema through the schema's own
778
+ `~standard.jsonSchema`, which zod has from 4.2. app-a hit a crash in the
779
+ converter, `ctx.deferred.push`, when the app and the SDK resolved different zod
780
+ copies: keep a single zod 4 (`>=4.2`) in the tree — `bun why zod` / `npm ls zod`
781
+ should show one version — and author tool schemas with it. The peer range is
782
+ `>=4.2.0` for that reason.
783
+
784
+ ### Migrating from 0.1.x
785
+
786
+ 0.2.0 is breaking for MCP users only; nothing else in signet-server changed.
787
+
788
+ - **Dependencies.** Replace `@modelcontextprotocol/sdk` with
789
+ `@modelcontextprotocol/server@^2.1`, and bump zod to `>=4.2` (see above).
790
+ Imports of the SDK in your own code move to v2 (the SDK ships a codemod:
791
+ `npx @modelcontextprotocol/codemod@latest v1-to-v2`). A `server:` factory must
792
+ return a v2 `McpServer`.
793
+ - **`mountMcp` / `mcpHandler`.** `json` and `transport` are gone; `http` takes
794
+ the SDK's `createMcpHandler` options instead. A `server:` factory gets a
795
+ second argument, `{ era, requestInfo }`.
796
+ - **stdio.** `server.connect(new StdioServerTransport())` still works but
797
+ speaks 2025 only; `serveStdio(() => createMcpServer(...))` serves both eras.
798
+ - **Behaviour.** An unknown tool is now a `-32602` JSON-RPC error. 2025 clients
799
+ get SSE responses rather than JSON. GET and DELETE still get a 405, now the
800
+ SDK's (without an `Allow` header). `ToolContext` gains `mcp`.