@prunellejs/mcp 0.0.0-stage → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,604 @@
1
+ // @prunellejs/mcp — Zero-dependency MCP Streamable HTTP (2025-03-26) plugin for Prunelle.
2
+ // Exposes typed Prunelle server `action()` handlers (and standalone tool handlers) as MCP tools
3
+ // over a bearer-authenticated endpoint via `PrunellePlugin.server`, keeping core free of MCP code.
4
+
5
+ import type { PrunellePlugin } from 'prunelle/config'
6
+ import type { ActionContext, InferOutput, RateLimit, RateLimiter, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
7
+ import type { McpBudgetOptions, McpFootprint } from './footprint'
8
+ import type { McpPruneMode, McpToolResult } from './format'
9
+ import type { ListedTool, McpToolAnnotations, ResolvedResource, ResolvedToolEntry } from './rpc'
10
+ import type { CompactSchemaOptions, JsonSchemaObject } from './schema'
11
+
12
+ import { readFile, stat } from 'node:fs/promises'
13
+ import { definePlugin } from 'prunelle/config'
14
+ import { rateLimitKey } from 'prunelle/internal/server'
15
+ import { isTrustedOrigin, nodeEnv, safeEqual } from 'prunelle/server'
16
+ import { collectBudgetViolations, computeFootprint, formatMcpFootprint } from './footprint'
17
+ import { createRpcDispatcher } from './rpc'
18
+ import { isPlainRecord, isStandardSchema, normalizeObjectSchema, schemaToJsonSchema } from './schema'
19
+
20
+ export { formatMcpFootprint } from './footprint'
21
+ export type { McpBudgetOptions, McpFootprint, McpToolFootprint } from './footprint'
22
+ export { formatLines, formatTable, pruneEmpty, truncateOutput } from './format'
23
+ export type { CompactListOptions, McpContentBlock, McpPruneMode, McpToolResult, PruneEmptyOptions } from './format'
24
+ export { BATCH_TIME_BUDGET_MS, MAX_BATCH_SIZE, MCP_PROTOCOL_VERSION } from './rpc'
25
+ export type { McpToolAnnotations } from './rpc'
26
+ export { compactSchema, schemaToJsonSchema } from './schema'
27
+ export type { CompactSchemaOptions, JsonSchemaObject } from './schema'
28
+
29
+ export interface McpResource {
30
+ /** Display name shown in `resources/list` (defaults to the resource URI/key). */
31
+ name?: string | undefined
32
+ /** Short one-line description shown in `resources/list`. */
33
+ description?: string | undefined
34
+ /** MIME type returned on `resources/read` (default: 'text/plain'). */
35
+ mimeType?: string | undefined
36
+ /** Static text or lazy reader invoked on `resources/read`. */
37
+ read: string | ((ctx: RequestContext) => string | Promise<string>)
38
+ }
39
+
40
+ export interface McpActionTool<Input = unknown, Output = unknown> {
41
+ /** Existing Prunelle `action()` handler to expose as an MCP tool. */
42
+ action: ServerAction<Input, Output>
43
+ handler?: never
44
+ /** Human/agent-facing tool description shown in `tools/list`. */
45
+ description: string
46
+ /** Optional explicit JSON Schema override (otherwise derived from Standard JSON Schema v1). */
47
+ inputSchema?: JsonSchemaObject | undefined
48
+ /** Reference a shared schema in `options.schemas` to emit a tiny stub in `tools/list` while keeping full server-side validation. */
49
+ schemaRef?: string | undefined
50
+ /** Optional MCP 2025-03-26 tool annotations (only emitted when provided). */
51
+ annotations?: McpToolAnnotations | undefined
52
+ /** Optional token-lean formatter transforming the action's output before sending to the agent. */
53
+ format?: ((output: Output, input: Input) => unknown) | undefined
54
+ /** Per-tool character cap on text output before truncation with a recovery hint. */
55
+ maxOutputChars?: number | undefined
56
+ /** Per-tool override for stripping null/undefined/empty values from JSON outputs. */
57
+ pruneEmpty?: McpPruneMode | undefined
58
+ }
59
+
60
+ export interface McpHandlerTool<S extends StandardSchemaV1 | undefined = undefined, R = unknown> {
61
+ action?: never
62
+ description: string
63
+ schema?: S
64
+ inputSchema?: JsonSchemaObject | undefined
65
+ /** Reference a shared schema in `options.schemas` to emit a tiny stub in `tools/list` while keeping full server-side validation. */
66
+ schemaRef?: string | undefined
67
+ /** Optional MCP 2025-03-26 tool annotations (only emitted when provided). */
68
+ annotations?: McpToolAnnotations | undefined
69
+ handler: (input: [S] extends [StandardSchemaV1] ? InferOutput<S> : Record<string, unknown>, ctx: ActionContext) => R | Promise<R>
70
+ /** Optional token-lean formatter transforming the handler's output before sending to the agent. */
71
+ format?: ((output: Awaited<R>, input: [S] extends [StandardSchemaV1] ? InferOutput<S> : Record<string, unknown>) => unknown) | undefined
72
+ /** Per-tool character cap on text output before truncation with a recovery hint. */
73
+ maxOutputChars?: number | undefined
74
+ /** Per-tool override for stripping null/undefined/empty values from JSON outputs. */
75
+ pruneEmpty?: McpPruneMode | undefined
76
+ }
77
+
78
+ /** Variance-safe erased action tool shape (carries no `any`). */
79
+ export interface ErasedMcpActionTool {
80
+ action: ServerAction<never, unknown>
81
+ handler?: never
82
+ description: string
83
+ inputSchema?: JsonSchemaObject | undefined
84
+ schemaRef?: string | undefined
85
+ annotations?: McpToolAnnotations | undefined
86
+ format?: ((output: never, input: never) => unknown) | undefined
87
+ maxOutputChars?: number | undefined
88
+ pruneEmpty?: McpPruneMode | undefined
89
+ }
90
+
91
+ /** Variance-safe erased handler tool shape (carries no `any`). */
92
+ export interface ErasedMcpHandlerTool {
93
+ action?: never
94
+ description: string
95
+ schema?: StandardSchemaV1 | undefined
96
+ inputSchema?: JsonSchemaObject | undefined
97
+ schemaRef?: string | undefined
98
+ annotations?: McpToolAnnotations | undefined
99
+ handler: (input: never, ctx: ActionContext) => unknown | Promise<unknown>
100
+ format?: ((output: never, input: never) => unknown) | undefined
101
+ maxOutputChars?: number | undefined
102
+ pruneEmpty?: McpPruneMode | undefined
103
+ }
104
+
105
+ export type McpTool = ErasedMcpActionTool | ErasedMcpHandlerTool
106
+
107
+ type ActionInput<A> = A extends ServerAction<infer I, unknown> ? I : never
108
+ type ActionOutput<A> = A extends ServerAction<never, infer O> ? O : unknown
109
+
110
+ type McpToolEntry<Spec> =
111
+ | {
112
+ action: Spec & ServerAction<never, unknown>
113
+ handler?: never
114
+ description: string
115
+ inputSchema?: JsonSchemaObject | undefined
116
+ schemaRef?: string | undefined
117
+ annotations?: McpToolAnnotations | undefined
118
+ format?: ((output: ActionOutput<Spec>, input: ActionInput<Spec>) => unknown) | undefined
119
+ maxOutputChars?: number | undefined
120
+ pruneEmpty?: McpPruneMode | undefined
121
+ }
122
+ | {
123
+ action?: never
124
+ description: string
125
+ schema?: Spec & (StandardSchemaV1 | undefined)
126
+ inputSchema?: JsonSchemaObject | undefined
127
+ schemaRef?: string | undefined
128
+ annotations?: McpToolAnnotations | undefined
129
+ handler: (input: [Spec] extends [StandardSchemaV1] ? InferOutput<Spec> : Record<string, unknown>, ctx: ActionContext) => unknown | Promise<unknown>
130
+ format?: ((output: never, input: [Spec] extends [StandardSchemaV1] ? InferOutput<Spec> : Record<string, unknown>) => unknown) | undefined
131
+ maxOutputChars?: number | undefined
132
+ pruneEmpty?: McpPruneMode | undefined
133
+ }
134
+
135
+ export type McpToolsRecord<T extends Record<string, unknown>> = {
136
+ [K in keyof T]: McpToolEntry<T[K]>
137
+ }
138
+
139
+ /** Preserves strict `Input`/`Output` inference for `format` and `handler` callbacks inside `mcp({ tools })`. */
140
+ export function mcpTool<Input, Output>(tool: McpActionTool<Input, Output>): McpActionTool<Input, Output>
141
+ export function mcpTool<S extends StandardSchemaV1, R = unknown>(tool: McpHandlerTool<S, R> & { schema: S }): McpHandlerTool<S, R>
142
+ export function mcpTool<R = unknown>(tool: McpHandlerTool<undefined, R> & { schema?: undefined }): McpHandlerTool<undefined, R>
143
+ export function mcpTool(tool: McpTool): McpTool {
144
+ return tool
145
+ }
146
+
147
+ export type McpTokenSource =
148
+ | string
149
+ | { env: string }
150
+ | { file: string }
151
+ | (() => string | undefined | Promise<string | undefined>)
152
+
153
+ export interface McpOptions {
154
+ /** Server name reported in `initialize` `serverInfo.name` (default: 'prunelle-mcp'). */
155
+ name?: string | undefined
156
+ /** Server version reported in `initialize` `serverInfo.version` (default: '1.0.0'). */
157
+ version?: string | undefined
158
+ /** Optional server-level instructions returned in `initialize`. */
159
+ instructions?: string | undefined
160
+ /** HTTP endpoint path (default: '/mcp/tools'). */
161
+ path?: string | undefined
162
+ /** Bearer token source: inline string, `{ env }`, `{ file }`, or resolver function. */
163
+ token?: McpTokenSource | undefined
164
+ /** Map of MCP tool names to Prunelle `action()` or handler definitions. */
165
+ tools: Record<string, McpTool>
166
+ /** Optional on-demand MCP resources exposed via `resources/list` and `resources/read`. */
167
+ resources?: Record<string, McpResource> | undefined
168
+ /** Shared schemas exposed on demand via `describe_schema` tool and `prunelle://schemas/<name>` resources for tools using `schemaRef`. */
169
+ schemas?: Record<string, StandardSchemaV1 | JsonSchemaObject> | undefined
170
+ /** Optional domain-error formatter for thrown errors (defaults to `err.message`). */
171
+ mapError?: ((error: unknown) => string | { message: string } | undefined) | undefined
172
+ /** Strip JSON Schema boilerplate, form-coercion unions, `x-*` keys, and homogeneous records in `tools/list` (default: true). */
173
+ compactSchemas?: boolean | CompactSchemaOptions | undefined
174
+ /** Strip `null`/`undefined` (`'nullish'`) or also empty `[]`/`{}` (`true`) from JSON tool outputs (default: false). */
175
+ pruneEmpty?: McpPruneMode | undefined
176
+ /** Maximum characters per tool call output before truncating with a hint (default: unlimited). */
177
+ maxOutputChars?: number | undefined
178
+ /** Optional server-wide fallback formatter used when a tool does not define its own `format`. */
179
+ formatResult?: ((output: unknown, toolName: string, input: unknown) => unknown) | undefined
180
+ /** Tool & catalog byte budget checked in dev startup and `prunelle check` (default: `{ maxToolBytes: 2048 }`; `false` disables). */
181
+ budget?: McpBudgetOptions | false | undefined
182
+ /** Calls one client may make to the endpoint, each method counted apart (default: 120 per minute per address; `false` disables). */
183
+ rateLimit?: RateLimit<RequestContext> | false | undefined
184
+ }
185
+
186
+ function cleanAnnotations(annotations: McpToolAnnotations | undefined): McpToolAnnotations | undefined {
187
+ if (annotations === undefined)
188
+ return undefined
189
+ const out: McpToolAnnotations = {}
190
+ let hasAny = false
191
+ if (annotations.title !== undefined) {
192
+ out.title = annotations.title
193
+ hasAny = true
194
+ }
195
+ if (annotations.readOnlyHint !== undefined) {
196
+ out.readOnlyHint = annotations.readOnlyHint
197
+ hasAny = true
198
+ }
199
+ if (annotations.destructiveHint !== undefined) {
200
+ out.destructiveHint = annotations.destructiveHint
201
+ hasAny = true
202
+ }
203
+ if (annotations.idempotentHint !== undefined) {
204
+ out.idempotentHint = annotations.idempotentHint
205
+ hasAny = true
206
+ }
207
+ if (annotations.openWorldHint !== undefined) {
208
+ out.openWorldHint = annotations.openWorldHint
209
+ hasAny = true
210
+ }
211
+ return hasAny ? out : undefined
212
+ }
213
+
214
+ function isActionTool(tool: McpTool): tool is ErasedMcpActionTool {
215
+ return 'action' in tool
216
+ }
217
+
218
+ function buildCatalog(
219
+ options: Pick<McpOptions, 'tools' | 'resources' | 'schemas' | 'compactSchemas' | 'maxOutputChars' | 'pruneEmpty'>,
220
+ ): {
221
+ listedTools: ListedTool[]
222
+ toolMap: Map<string, ResolvedToolEntry>
223
+ resourceMap: Map<string, ResolvedResource>
224
+ } {
225
+ const compact = options.compactSchemas ?? true
226
+ const defaultPrune: McpPruneMode = options.pruneEmpty ?? false
227
+
228
+ const sharedJsonSchemas = new Map<string, string>()
229
+ const sharedValidators = new Map<string, StandardSchemaV1>()
230
+ const resourceMap = new Map<string, ResolvedResource>()
231
+
232
+ if (options.resources !== undefined) {
233
+ for (const [uri, res] of Object.entries(options.resources)) {
234
+ const reader = typeof res.read === 'function' ? res.read : () => res.read as string
235
+ resourceMap.set(uri, {
236
+ uri,
237
+ name: res.name ?? uri,
238
+ ...(res.description !== undefined ? { description: res.description } : {}),
239
+ mimeType: res.mimeType ?? 'text/plain',
240
+ read: reader,
241
+ })
242
+ }
243
+ }
244
+
245
+ if (options.schemas !== undefined) {
246
+ for (const [name, def] of Object.entries(options.schemas)) {
247
+ const jsonSchema = isStandardSchema(def)
248
+ ? schemaToJsonSchema(def, { compact })
249
+ : normalizeObjectSchema(def, compact)
250
+ if (isStandardSchema(def))
251
+ sharedValidators.set(name, def)
252
+ const serialized = JSON.stringify(jsonSchema)
253
+ sharedJsonSchemas.set(name, serialized)
254
+ const uri = `prunelle://schemas/${name}`
255
+ if (!resourceMap.has(uri)) {
256
+ resourceMap.set(uri, {
257
+ uri,
258
+ name: `schema:${name}`,
259
+ description: `JSON Schema for "${name}".`,
260
+ mimeType: 'application/json',
261
+ read: () => serialized,
262
+ })
263
+ }
264
+ }
265
+ }
266
+
267
+ const listedTools: ListedTool[] = []
268
+ const toolMap = new Map<string, ResolvedToolEntry>()
269
+
270
+ for (const [name, def] of Object.entries(options.tools)) {
271
+ const rawSchema = isActionTool(def) ? def.action.schema : def.schema
272
+ const schema = rawSchema ?? (def.schemaRef !== undefined ? sharedValidators.get(def.schemaRef) : undefined)
273
+ const handler = isActionTool(def)
274
+ ? ((input: unknown, ctx: ActionContext) => def.action.handler(input as never, ctx))
275
+ : ((input: unknown, ctx: ActionContext) => def.handler(input as never, ctx))
276
+
277
+ let inputSchema: JsonSchemaObject
278
+ if (def.inputSchema !== undefined) {
279
+ inputSchema = normalizeObjectSchema(def.inputSchema, compact)
280
+ }
281
+ else if (def.schemaRef !== undefined && sharedJsonSchemas.has(def.schemaRef)) {
282
+ inputSchema = {
283
+ type: 'object',
284
+ description: `Matches schema "${def.schemaRef}" (call describe_schema or read prunelle://schemas/${def.schemaRef}).`,
285
+ }
286
+ }
287
+ else {
288
+ inputSchema = schemaToJsonSchema(schema, { compact })
289
+ }
290
+
291
+ const annotations = cleanAnnotations(def.annotations)
292
+ listedTools.push({
293
+ name,
294
+ description: def.description,
295
+ inputSchema,
296
+ ...(annotations !== undefined ? { annotations } : {}),
297
+ })
298
+
299
+ toolMap.set(name, {
300
+ name,
301
+ action: isActionTool(def) ? def.action as ServerAction<unknown, unknown> : undefined,
302
+ schema,
303
+ handler,
304
+ format: def.format as ((output: unknown, input: unknown) => unknown) | undefined,
305
+ maxOutputChars: def.maxOutputChars ?? options.maxOutputChars,
306
+ pruneEmpty: def.pruneEmpty !== undefined ? def.pruneEmpty : defaultPrune,
307
+ })
308
+ }
309
+
310
+ // Auto-register a tiny `describe_schema` lookup tool when `options.schemas` is provided.
311
+ if (sharedJsonSchemas.size > 0 && !toolMap.has('describe_schema')) {
312
+ const schemaNames = [...sharedJsonSchemas.keys()]
313
+ const inputSchema: JsonSchemaObject = {
314
+ type: 'object',
315
+ properties: { name: { type: 'string', enum: schemaNames } },
316
+ required: ['name'],
317
+ }
318
+ const annotations: McpToolAnnotations = { readOnlyHint: true, idempotentHint: true }
319
+ listedTools.push({
320
+ name: 'describe_schema',
321
+ description: 'Return full JSON Schema for a shared schema name.',
322
+ inputSchema,
323
+ annotations,
324
+ })
325
+ toolMap.set('describe_schema', {
326
+ name: 'describe_schema',
327
+ schema: undefined,
328
+ handler(input) {
329
+ const key = isPlainRecord(input) && typeof input.name === 'string' ? input.name : ''
330
+ const found = sharedJsonSchemas.get(key)
331
+ if (found === undefined) {
332
+ return {
333
+ content: [{ type: 'text', text: `Unknown schema "${key}" (available: ${schemaNames.join(', ')})` }],
334
+ isError: true,
335
+ } satisfies McpToolResult
336
+ }
337
+ return found
338
+ },
339
+ format: undefined,
340
+ maxOutputChars: options.maxOutputChars,
341
+ pruneEmpty: false,
342
+ })
343
+ }
344
+
345
+ return { listedTools, toolMap, resourceMap }
346
+ }
347
+
348
+ /** Measures the up-front `instructions` + `tools/list` byte/char/token footprint (sorted largest tool first). */
349
+ export function inspectMcpFootprint(
350
+ options: Pick<McpOptions, 'instructions' | 'tools' | 'resources' | 'schemas' | 'compactSchemas'>,
351
+ ): McpFootprint {
352
+ const { listedTools } = buildCatalog(options)
353
+ return computeFootprint(options.instructions, listedTools)
354
+ }
355
+
356
+ interface CachedTokenFile {
357
+ mtimeNs: bigint
358
+ ctimeNs: bigint
359
+ size: bigint
360
+ ino: bigint
361
+ token: string | undefined
362
+ }
363
+
364
+ function createTokenFileReader(): (filePath: string) => Promise<string | undefined> {
365
+ const cache = new Map<string, CachedTokenFile>()
366
+
367
+ return async (filePath: string): Promise<string | undefined> => {
368
+ try {
369
+ const info = await stat(filePath, { bigint: true })
370
+ const prev = cache.get(filePath)
371
+ if (
372
+ prev !== undefined
373
+ && prev.mtimeNs === info.mtimeNs
374
+ && prev.ctimeNs === info.ctimeNs
375
+ && prev.size === info.size
376
+ && prev.ino === info.ino
377
+ ) {
378
+ return prev.token
379
+ }
380
+ const raw = (await readFile(filePath, 'utf8')).trim()
381
+ const token = raw.length > 0 ? raw : undefined
382
+ cache.set(filePath, {
383
+ mtimeNs: info.mtimeNs,
384
+ ctimeNs: info.ctimeNs,
385
+ size: info.size,
386
+ ino: info.ino,
387
+ token,
388
+ })
389
+ return token
390
+ }
391
+ catch {
392
+ cache.delete(filePath)
393
+ return undefined
394
+ }
395
+ }
396
+ }
397
+
398
+ async function resolveToken(
399
+ src: McpTokenSource | undefined,
400
+ readTokenFile: (filePath: string) => Promise<string | undefined>,
401
+ ): Promise<string | undefined> {
402
+ if (src === undefined)
403
+ return undefined
404
+ if (typeof src === 'function') {
405
+ const val = (await src())?.trim()
406
+ return val && val.length > 0 ? val : undefined
407
+ }
408
+ if (typeof src === 'string') {
409
+ const val = src.trim()
410
+ return val.length > 0 ? val : undefined
411
+ }
412
+ if ('env' in src) {
413
+ const val = process.env[src.env]?.trim()
414
+ return val && val.length > 0 ? val : undefined
415
+ }
416
+ if ('file' in src)
417
+ return readTokenFile(src.file)
418
+ return undefined
419
+ }
420
+
421
+
422
+ function extractBearerToken(request: Request): string | undefined {
423
+ const header = request.headers.get('authorization')
424
+ if (header === null)
425
+ return undefined
426
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim())
427
+ if (!match)
428
+ return undefined
429
+ const token = match[1]?.trim()
430
+ return token && token.length > 0 ? token : undefined
431
+ }
432
+
433
+ /** The shortest bearer token the endpoint accepts: 32 bytes, the size of a random key. */
434
+ const MIN_TOKEN_BYTES = 32
435
+ /** Wrong or missing bearer tokens one client may send per window before the endpoint answers 429. */
436
+ const FAILED_AUTH_LIMIT = { max: 10, windowMs: 60_000 }
437
+
438
+ function mcpTooManyRequests(retryAfter: number): Response {
439
+ return Response.json(
440
+ { ok: false, status: 429, error: 'Too many requests' },
441
+ { status: 429, headers: { 'retry-after': String(retryAfter) } },
442
+ )
443
+ }
444
+
445
+ export function mcp<T extends Record<string, unknown>>(
446
+ options: Omit<McpOptions, 'tools'> & { tools: McpToolsRecord<T> },
447
+ ): PrunellePlugin
448
+ export function mcp(options: McpOptions): PrunellePlugin
449
+ export function mcp(options: McpOptions): PrunellePlugin {
450
+ const rawPath = options.path ?? '/mcp/tools'
451
+ const endpoint = rawPath === '/' ? '/' : `/${rawPath.replace(/^\/+|\/+$/g, '')}`
452
+ const rateLimit = options.rateLimit === false ? undefined : options.rateLimit ?? { max: 120, windowMs: 60_000 }
453
+ const serverName = options.name ?? 'prunelle-mcp'
454
+ const serverVersion = options.version ?? '1.0.0'
455
+
456
+ const { listedTools, toolMap, resourceMap } = buildCatalog(options)
457
+ const listedResources = [...resourceMap.values()].map(r => ({
458
+ uri: r.uri,
459
+ name: r.name,
460
+ ...(r.description !== undefined ? { description: r.description } : {}),
461
+ mimeType: r.mimeType,
462
+ }))
463
+
464
+ const footprint = computeFootprint(options.instructions, listedTools)
465
+ const customWarn = options.budget !== false ? options.budget?.onWarn : undefined
466
+ const warnSink = customWarn ?? ((msg: string) => console.warn(msg))
467
+ const readTokenFile = createTokenFileReader()
468
+
469
+ const rpc = createRpcDispatcher({
470
+ serverName,
471
+ serverVersion,
472
+ instructions: options.instructions,
473
+ listedTools,
474
+ toolMap,
475
+ resourceMap,
476
+ listedResources,
477
+ formatResult: options.formatResult,
478
+ mapError: options.mapError,
479
+ limiterFor: limit => actionLimiter?.(limit),
480
+ })
481
+
482
+ // Set by server(): failed bearer attempts per client, counted apart from the call limit.
483
+ let failures: RateLimiter | undefined
484
+ // Set by server(): counts a tool's calls against the `rateLimit` of the action behind it.
485
+ let actionLimiter: ((limit: RateLimit<ActionContext>) => RateLimiter) | undefined
486
+
487
+ async function authorize(ctx: RequestContext): Promise<Response | undefined> {
488
+ const configured = await resolveToken(options.token, readTokenFile)
489
+ if (configured === undefined || Buffer.byteLength(configured) < MIN_TOKEN_BYTES)
490
+ return new Response('Not Found', { status: 404 })
491
+
492
+ const key = rateLimitKey(FAILED_AUTH_LIMIT, ctx)
493
+ const retryAfter = failures?.peek(key) ?? 0
494
+ if (retryAfter > 0)
495
+ return mcpTooManyRequests(retryAfter)
496
+ const provided = extractBearerToken(ctx.request)
497
+ if (provided === undefined || !safeEqual(provided, configured)) {
498
+ failures?.hit(key)
499
+ return Response.json(
500
+ { error: 'Unauthorized' },
501
+ { status: 401, headers: { 'www-authenticate': 'Bearer' } },
502
+ )
503
+ }
504
+ return undefined
505
+ }
506
+
507
+ return definePlugin({
508
+ name: '@prunellejs/mcp',
509
+
510
+ async requires() {
511
+ const configured = await resolveToken(options.token, readTokenFile)
512
+ if (configured === undefined)
513
+ return ['no `token`, so the endpoint answers 404 to every call: pass `token: { env: \'MCP_TOKEN\' }` and set `MCP_TOKEN`, or `token: { file }`.']
514
+ return Buffer.byteLength(configured) < MIN_TOKEN_BYTES
515
+ ? [`the \`token\` is under ${MIN_TOKEN_BYTES} bytes, so the endpoint answers 404 to every call: use ${MIN_TOKEN_BYTES} random bytes or more, such as \`openssl rand -hex 32\`.`]
516
+ : []
517
+ },
518
+
519
+ server(api) {
520
+ if (api.dev || nodeEnv() !== 'production') {
521
+ for (const msg of collectBudgetViolations(footprint, options.budget))
522
+ warnSink(msg)
523
+ }
524
+
525
+ const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
526
+ const checkOrigin = (ctx: RequestContext): Response | undefined => {
527
+ const origin = ctx.request.headers.get('origin')
528
+ if (origin === null)
529
+ return undefined
530
+ if (isTrustedOrigin(origin, ctx.request, trustedOrigins, api.trustProxy, ctx.url))
531
+ return undefined
532
+ return Response.json({ error: `Forbidden: untrusted origin ${origin}` }, { status: 403 })
533
+ }
534
+
535
+ failures = api.rateLimiter(FAILED_AUTH_LIMIT)
536
+ actionLimiter = api.rateLimiter
537
+ const postLimiter = rateLimit !== undefined ? api.rateLimiter(rateLimit) : undefined
538
+ const consumePostTokens = postLimiter !== undefined && rateLimit !== undefined
539
+ ? (ctx: RequestContext, count: number): Response | undefined => {
540
+ const key = rateLimitKey(rateLimit, ctx)
541
+ for (let i = 0; i < count; i++) {
542
+ const retryAfter = postLimiter.hit(key)
543
+ if (retryAfter > 0)
544
+ return mcpTooManyRequests(retryAfter)
545
+ }
546
+ return undefined
547
+ }
548
+ : undefined
549
+
550
+ api.route('POST', endpoint, async (ctx) => {
551
+ const limited = consumePostTokens?.(ctx, 1)
552
+ if (limited !== undefined)
553
+ return limited
554
+ const originDenied = checkOrigin(ctx)
555
+ if (originDenied !== undefined)
556
+ return originDenied
557
+ const denied = await authorize(ctx)
558
+ if (denied !== undefined)
559
+ return denied
560
+ return rpc.handlePost(ctx, api.dev, consumePostTokens)
561
+ }, { csrf: false })
562
+
563
+ api.route('GET', endpoint, async (ctx) => {
564
+ const originDenied = checkOrigin(ctx)
565
+ if (originDenied !== undefined)
566
+ return originDenied
567
+ const denied = await authorize(ctx)
568
+ if (denied !== undefined)
569
+ return denied
570
+ return new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST, DELETE' } })
571
+ }, { rateLimit })
572
+
573
+ api.route('DELETE', endpoint, async (ctx) => {
574
+ const originDenied = checkOrigin(ctx)
575
+ if (originDenied !== undefined)
576
+ return originDenied
577
+ const denied = await authorize(ctx)
578
+ if (denied !== undefined)
579
+ return denied
580
+ return new Response(null, { status: 204 })
581
+ }, { csrf: false, rateLimit })
582
+ },
583
+
584
+ check(ctx) {
585
+ const violations = collectBudgetViolations(footprint, options.budget)
586
+ const strict = options.budget !== false && options.budget?.strict === true
587
+ for (const msg of violations) {
588
+ if (strict) {
589
+ ctx.error(msg)
590
+ }
591
+ else {
592
+ ctx.warn(msg)
593
+ customWarn?.(msg)
594
+ }
595
+ }
596
+ },
597
+
598
+ commands: {
599
+ 'mcp-footprint': () => {
600
+ console.log(formatMcpFootprint(footprint, options.budget))
601
+ },
602
+ },
603
+ })
604
+ }