@prunellejs/mcp 0.0.0-stage → 0.5.1

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