@prunellejs/mcp 0.1.1 → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -4,14 +4,15 @@
4
4
 
5
5
  ## Imports
6
6
 
7
- - `@prunellejs/mcp`: `mcp`, `mcpTool`, `inspectMcpFootprint`, `formatMcpFootprint`, `formatLines`, `formatTable`, `pruneEmpty`, `truncateOutput`, `compactSchema`, `schemaToJsonSchema`, `MCP_PROTOCOL_VERSION`, `MAX_BATCH_SIZE`; types `McpOptions`, `McpTool`, `McpActionTool`, `McpHandlerTool`, `McpToolsRecord`, `McpResource`, `McpTokenSource`, `McpToolAnnotations`, `McpBudgetOptions`, `McpFootprint`, `McpToolFootprint`, `McpContentBlock`, `McpToolResult`, `McpPruneMode`, `PruneEmptyOptions`, `CompactListOptions`, `CompactSchemaOptions`, `JsonSchemaObject`.
7
+ - `@prunellejs/mcp`: `mcp`, `mcpTool`, `inspectMcpFootprint`, `formatMcpFootprint`, `formatLines`, `formatTable`, `pruneEmpty`, `truncateOutput`, `compactSchema`, `schemaToJsonSchema`, `MCP_PROTOCOL_VERSION`, `MAX_BATCH_SIZE` (50 calls), `BATCH_TIME_BUDGET_MS` (30 s: no batched call starts past it, each skipped request answering a `-32000` error to resend it alone); types `McpOptions`, `McpTool`, `McpActionTool`, `McpHandlerTool`, `McpToolsRecord`, `McpResource`, `McpTokenSource`, `McpToolAnnotations`, `McpBudgetOptions`, `McpFootprint`, `McpToolFootprint`, `McpContentBlock`, `McpToolResult`, `McpPruneMode`, `PruneEmptyOptions`, `CompactListOptions`, `CompactSchemaOptions`, `JsonSchemaObject`.
8
8
 
9
9
  ## Plugin Setup (`mcp(options)`)
10
10
 
11
11
  - `name` (`'prunelle-mcp'`), `version` (`'1.0.0'`), `instructions` (returned in `initialize`).
12
12
  - `path`: HTTP endpoint (default `'/mcp/tools'`).
13
13
  - `rateLimit`: `{ max, windowMs, key? } | false` (default 120 calls a minute per address, each method counted apart; past it `429` with `Retry-After`).
14
- - `token`: `string | { env: string } | { file: string } | (() => string | undefined | Promise<string | undefined>)`. Unconfigured token returns `404`, and a production start refuses until it is set; missing/invalid `Authorization: Bearer <token>` returns `401`.
14
+ - `token`: `string | { env: string } | { file: string } | (() => string | undefined | Promise<string | undefined>)`. Unconfigured or shorter than 32 bytes returns `404`, and a production start refuses until it is set (`openssl rand -hex 32` makes one); missing/invalid `Authorization: Bearer <token>` returns `401`, and a client past 10 failed attempts a minute gets `429` with `Retry-After` until the window passes, even with the right token.
15
+ - A tool backed by an `action()` counts each call against that action's `rateLimit` (or `protect.rateLimit`), in a counter apart from the web form's, and answers an error result `Too many requests to <tool>: retry after N s`. `protect.honeypot` and `protect.minTime` do not apply: they guard a rendered form, and the bearer token is the machine client's proof.
15
16
  - `tools`: `Record<string, McpTool>` — each entry either wraps an existing Prunelle `action` (`{ action, description, ... }`) or defines `{ schema?, handler(input, ctx), description, ... }`. Wrap with `mcpTool(...)` for strict `format`/`handler` inference.
16
17
  - Per-tool options: `inputSchema`, `schemaRef` (references `options.schemas` to emit a compact stub in `tools/list` while keeping full server validation), `annotations` (`title`, `readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`), `format(output, input)`, `maxOutputChars`, `pruneEmpty`.
17
18
  - `schemas`: shared schemas exposed on demand via auto-added `describe_schema` tool and `prunelle://schemas/<name>` resources.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/mcp",
3
- "version": "0.1.1",
3
+ "version": "0.7.2",
4
4
  "description": "Zero-dependency MCP Streamable HTTP (2025-03-26) plugin exposing Prunelle server actions as AI agent tools",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,6 @@
21
21
  "directory": "packages/plugin-mcp"
22
22
  },
23
23
  "peerDependencies": {
24
- "prunelle": "^0.1.1"
24
+ "prunelle": "^0.7.2"
25
25
  }
26
26
  }
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  // over a bearer-authenticated endpoint via `PrunellePlugin.server`, keeping core free of MCP code.
4
4
 
5
5
  import type { PrunellePlugin } from 'prunelle/config'
6
- import type { ActionContext, InferOutput, RateLimit, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
6
+ import type { ActionContext, InferOutput, RateLimit, RateLimiter, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
7
7
  import type { McpBudgetOptions, McpFootprint } from './footprint'
8
8
  import type { McpPruneMode, McpToolResult } from './format'
9
9
  import type { ListedTool, McpToolAnnotations, ResolvedResource, ResolvedToolEntry } from './rpc'
@@ -11,7 +11,8 @@ import type { CompactSchemaOptions, JsonSchemaObject } from './schema'
11
11
 
12
12
  import { readFile, stat } from 'node:fs/promises'
13
13
  import { definePlugin } from 'prunelle/config'
14
- import { nodeEnv, safeEqual } from 'prunelle/server'
14
+ import { rateLimitKey } from 'prunelle/internal/server'
15
+ import { isTrustedOrigin, nodeEnv, safeEqual } from 'prunelle/server'
15
16
  import { collectBudgetViolations, computeFootprint, formatMcpFootprint } from './footprint'
16
17
  import { createRpcDispatcher } from './rpc'
17
18
  import { isPlainRecord, isStandardSchema, normalizeObjectSchema, schemaToJsonSchema } from './schema'
@@ -20,7 +21,7 @@ export { formatMcpFootprint } from './footprint'
20
21
  export type { McpBudgetOptions, McpFootprint, McpToolFootprint } from './footprint'
21
22
  export { formatLines, formatTable, pruneEmpty, truncateOutput } from './format'
22
23
  export type { CompactListOptions, McpContentBlock, McpPruneMode, McpToolResult, PruneEmptyOptions } from './format'
23
- export { MAX_BATCH_SIZE, MCP_PROTOCOL_VERSION } from './rpc'
24
+ export { BATCH_TIME_BUDGET_MS, MAX_BATCH_SIZE, MCP_PROTOCOL_VERSION } from './rpc'
24
25
  export type { McpToolAnnotations } from './rpc'
25
26
  export { compactSchema, schemaToJsonSchema } from './schema'
26
27
  export type { CompactSchemaOptions, JsonSchemaObject } from './schema'
@@ -429,6 +430,18 @@ function extractBearerToken(request: Request): string | undefined {
429
430
  return token && token.length > 0 ? token : undefined
430
431
  }
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
+
432
445
  export function mcp<T extends Record<string, unknown>>(
433
446
  options: Omit<McpOptions, 'tools'> & { tools: McpToolsRecord<T> },
434
447
  ): PrunellePlugin
@@ -463,15 +476,26 @@ export function mcp(options: McpOptions): PrunellePlugin {
463
476
  listedResources,
464
477
  formatResult: options.formatResult,
465
478
  mapError: options.mapError,
479
+ limiterFor: limit => actionLimiter?.(limit),
466
480
  })
467
481
 
468
- async function authorize(request: Request): Promise<Response | undefined> {
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> {
469
488
  const configured = await resolveToken(options.token, readTokenFile)
470
- if (configured === undefined)
489
+ if (configured === undefined || Buffer.byteLength(configured) < MIN_TOKEN_BYTES)
471
490
  return new Response('Not Found', { status: 404 })
472
491
 
473
- const provided = extractBearerToken(request)
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)
474
497
  if (provided === undefined || !safeEqual(provided, configured)) {
498
+ failures?.hit(key)
475
499
  return Response.json(
476
500
  { error: 'Unauthorized' },
477
501
  { status: 401, headers: { 'www-authenticate': 'Bearer' } },
@@ -484,8 +508,11 @@ export function mcp(options: McpOptions): PrunellePlugin {
484
508
  name: '@prunellejs/mcp',
485
509
 
486
510
  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 }`.']
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\`.`]
489
516
  : []
490
517
  },
491
518
 
@@ -495,22 +522,59 @@ export function mcp(options: McpOptions): PrunellePlugin {
495
522
  warnSink(msg)
496
523
  }
497
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
+
498
550
  api.route('POST', endpoint, async (ctx) => {
499
- const denied = await authorize(ctx.request)
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)
500
558
  if (denied !== undefined)
501
559
  return denied
502
- return rpc.handlePost(ctx, api.dev)
503
- }, { csrf: false, rateLimit })
560
+ return rpc.handlePost(ctx, api.dev, consumePostTokens)
561
+ }, { csrf: false })
504
562
 
505
563
  api.route('GET', endpoint, async (ctx) => {
506
- const denied = await authorize(ctx.request)
564
+ const originDenied = checkOrigin(ctx)
565
+ if (originDenied !== undefined)
566
+ return originDenied
567
+ const denied = await authorize(ctx)
507
568
  if (denied !== undefined)
508
569
  return denied
509
570
  return new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST, DELETE' } })
510
571
  }, { rateLimit })
511
572
 
512
573
  api.route('DELETE', endpoint, async (ctx) => {
513
- const denied = await authorize(ctx.request)
574
+ const originDenied = checkOrigin(ctx)
575
+ if (originDenied !== undefined)
576
+ return originDenied
577
+ const denied = await authorize(ctx)
514
578
  if (denied !== undefined)
515
579
  return denied
516
580
  return new Response(null, { status: 204 })
package/src/rpc.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  // JSON-RPC 2.0 & MCP Streamable HTTP (2025-03-26) dispatcher with bounded batch execution.
2
2
 
3
- import type { ActionContext, ActionResult, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
3
+ import type { ActionContext, ActionResult, RateLimit, RateLimiter, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
4
4
  import type { McpPruneMode, McpToolResult } from './format'
5
5
  import type { JsonSchemaObject } from './schema'
6
+ import { rateLimitKey } from 'prunelle/internal/server'
6
7
  import { formatSchemaIssues, nodeEnv, validateSchema } from 'prunelle/server'
7
8
  import { applyOutputBudget, finalizeToolValue, formatFieldErrors, formatResponseResult } from './format'
8
9
 
9
10
  export const MCP_PROTOCOL_VERSION = '2025-03-26'
10
11
  export const MAX_BATCH_SIZE = 50
12
+ /** No batched call starts once a batch has run this long, so one request cannot hold the server for 50 slow calls. */
13
+ export const BATCH_TIME_BUDGET_MS = 30_000
11
14
 
12
15
  export interface McpToolAnnotations {
13
16
  title?: string | undefined
@@ -66,6 +69,8 @@ export interface RpcDispatcherConfig {
66
69
  listedResources: readonly { uri: string, name: string, description?: string, mimeType: string }[]
67
70
  formatResult?: ((output: unknown, toolName: string, input: unknown) => unknown) | undefined
68
71
  mapError?: ((error: unknown) => string | { message: string } | undefined) | undefined
72
+ /** A limiter counting under `limit`, or undefined before the server runs; one per action is kept. */
73
+ limiterFor?: ((limit: RateLimit<ActionContext>) => RateLimiter | undefined) | undefined
69
74
  }
70
75
 
71
76
  function shouldExposeErrors(dev: boolean): boolean {
@@ -97,12 +102,91 @@ function formatActionFailure(invoked: Extract<ActionResult<unknown>, { ok: false
97
102
  return fields ? `${invoked.error} (${fields})` : invoked.error
98
103
  }
99
104
 
105
+ async function handleResourceRead(
106
+ cfg: RpcDispatcherConfig,
107
+ id: string | number | null,
108
+ params: Record<string, unknown> | undefined,
109
+ ctx: RequestContext,
110
+ dev: boolean,
111
+ ): Promise<JsonRpcResponse> {
112
+ if (cfg.resourceMap.size === 0)
113
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found: resources/read' } }
114
+ const uri = typeof params?.uri === 'string' ? params.uri : undefined
115
+ if (uri === undefined)
116
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: 'Missing resource uri' } }
117
+ const resource = cfg.resourceMap.get(uri)
118
+ if (resource === undefined)
119
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: `Unknown resource: ${uri}` } }
120
+ try {
121
+ const text = await resource.read(ctx)
122
+ return {
123
+ jsonrpc: '2.0',
124
+ id,
125
+ result: {
126
+ contents: [{ uri: resource.uri, mimeType: resource.mimeType, text }],
127
+ },
128
+ }
129
+ }
130
+ catch (err) {
131
+ const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
132
+ return { jsonrpc: '2.0', id, error: { code: -32603, message } }
133
+ }
134
+ }
135
+
136
+ export type BatchRateLimitCheck = (ctx: RequestContext, extraCalls: number) => Response | undefined
137
+
138
+ function budgetSpent(item: unknown): JsonRpcResponse | null {
139
+ const id = typeof item === 'object' && item !== null ? (item as Partial<JsonRpcRequest>).id : undefined
140
+ if (id === undefined)
141
+ return null
142
+ return { jsonrpc: '2.0', id, error: { code: -32000, message: `Batch time budget of ${BATCH_TIME_BUDGET_MS / 1000} s spent before this call started: send it again in a new request` } }
143
+ }
144
+
145
+ async function runBatch(payload: readonly unknown[], handle: (item: unknown) => Promise<JsonRpcResponse | null>): Promise<JsonRpcResponse[]> {
146
+ const responses: JsonRpcResponse[] = []
147
+ const deadline = Date.now() + BATCH_TIME_BUDGET_MS
148
+ for (const item of payload) {
149
+ const res = Date.now() < deadline ? await handle(item) : budgetSpent(item)
150
+ if (res !== null)
151
+ responses.push(res)
152
+ }
153
+ return responses
154
+ }
155
+
156
+ // The action's own `rateLimit`, which `executeAction` applies to a web submit and a tool call would skip. `protect.honeypot` and `protect.minTime` guard a rendered form, which an authenticated machine client never has.
157
+ function createActionGuard(limiterFor: RpcDispatcherConfig['limiterFor']): (act: ServerAction<unknown, unknown>, ctx: RequestContext) => number {
158
+ const limiters = new WeakMap<object, RateLimiter>()
159
+ return (act, ctx) => {
160
+ if (act.rateLimit === undefined)
161
+ return 0
162
+ let limiter = limiters.get(act)
163
+ if (limiter === undefined) {
164
+ limiter = limiterFor?.(act.rateLimit)
165
+ if (limiter === undefined)
166
+ return 0
167
+ limiters.set(act, limiter)
168
+ }
169
+ return limiter.hit(rateLimitKey(act.rateLimit, ctx))
170
+ }
171
+ }
172
+
173
+ async function shapeResult(cfg: RpcDispatcherConfig, tool: ResolvedToolEntry, name: string, rawResult: unknown, input: unknown): Promise<McpToolResult> {
174
+ if (rawResult instanceof Response)
175
+ return formatResponseResult(rawResult, tool.pruneEmpty)
176
+ const formatted = tool.format !== undefined
177
+ ? tool.format(rawResult, input)
178
+ : (cfg.formatResult !== undefined ? cfg.formatResult(rawResult, name, input) : rawResult)
179
+ return finalizeToolValue(formatted, tool.pruneEmpty)
180
+ }
181
+
100
182
  export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
101
183
  const hasResources = cfg.resourceMap.size > 0
102
184
  const availableNamesHint = cfg.toolMap.size > 0 && cfg.toolMap.size <= 12
103
185
  ? ` (available: ${[...cfg.toolMap.keys()].join(', ')})`
104
186
  : ''
105
187
 
188
+ const actionRetryAfter = createActionGuard(cfg.limiterFor)
189
+
106
190
  async function callTool(name: string, args: unknown, ctx: RequestContext, dev: boolean): Promise<McpToolResult> {
107
191
  const tool = cfg.toolMap.get(name)
108
192
  if (tool === undefined)
@@ -126,6 +210,13 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
126
210
  try {
127
211
  let rawResult: unknown
128
212
  if (tool.action !== undefined) {
213
+ const retryAfter = actionRetryAfter(tool.action, ctx)
214
+ if (retryAfter > 0) {
215
+ return {
216
+ content: [{ type: 'text', text: `Too many requests to ${name}: retry after ${retryAfter} s` }],
217
+ isError: true,
218
+ }
219
+ }
129
220
  const invoked = await tool.action(input)
130
221
  if (!invoked.ok) {
131
222
  return applyOutputBudget({
@@ -138,17 +229,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
138
229
  else {
139
230
  rawResult = await tool.handler(input, ctx)
140
231
  }
141
- let mcpResult: McpToolResult
142
- if (rawResult instanceof Response) {
143
- mcpResult = await formatResponseResult(rawResult, tool.pruneEmpty)
144
- }
145
- else {
146
- const formatted = tool.format !== undefined
147
- ? tool.format(rawResult, input)
148
- : (cfg.formatResult !== undefined ? cfg.formatResult(rawResult, name, input) : rawResult)
149
- mcpResult = await finalizeToolValue(formatted, tool.pruneEmpty)
150
- }
151
- return applyOutputBudget(mcpResult, tool.maxOutputChars)
232
+ return applyOutputBudget(await shapeResult(cfg, tool, name, rawResult, input), tool.maxOutputChars)
152
233
  }
153
234
  catch (err) {
154
235
  const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
@@ -229,30 +310,8 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
229
310
  }
230
311
  }
231
312
 
232
- case 'resources/read': {
233
- if (!hasResources)
234
- return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${req.method}` } }
235
- const uri = typeof req.params?.uri === 'string' ? req.params.uri : undefined
236
- if (uri === undefined)
237
- return { jsonrpc: '2.0', id, error: { code: -32602, message: 'Missing resource uri' } }
238
- const resource = cfg.resourceMap.get(uri)
239
- if (resource === undefined)
240
- return { jsonrpc: '2.0', id, error: { code: -32602, message: `Unknown resource: ${uri}` } }
241
- try {
242
- const text = await resource.read(ctx)
243
- return {
244
- jsonrpc: '2.0',
245
- id,
246
- result: {
247
- contents: [{ uri: resource.uri, mimeType: resource.mimeType, text }],
248
- },
249
- }
250
- }
251
- catch (err) {
252
- const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
253
- return { jsonrpc: '2.0', id, error: { code: -32603, message } }
254
- }
255
- }
313
+ case 'resources/read':
314
+ return handleResourceRead(cfg, id, req.params, ctx, dev)
256
315
 
257
316
  default:
258
317
  return {
@@ -263,7 +322,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
263
322
  }
264
323
  }
265
324
 
266
- async function handlePost(ctx: RequestContext, dev = false): Promise<Response> {
325
+ async function handlePost(ctx: RequestContext, dev = false, checkBatchRateLimit?: BatchRateLimitCheck): Promise<Response> {
267
326
  let payload: unknown
268
327
  try {
269
328
  payload = await ctx.request.json()
@@ -289,12 +348,12 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
289
348
  { status: 400 },
290
349
  )
291
350
  }
292
- const responses: JsonRpcResponse[] = []
293
- for (const item of payload) {
294
- const res = await handleMessage(item, ctx, dev)
295
- if (res !== null)
296
- responses.push(res)
351
+ if (checkBatchRateLimit !== undefined && payload.length > 1) {
352
+ const limited = checkBatchRateLimit(ctx, payload.length - 1)
353
+ if (limited !== undefined)
354
+ return limited
297
355
  }
356
+ const responses = await runBatch(payload, item => handleMessage(item, ctx, dev))
298
357
  if (responses.length === 0)
299
358
  return new Response(null, { status: 202 })
300
359
  return Response.json(responses, { status: 200 })
package/src/schema.ts CHANGED
@@ -232,7 +232,8 @@ function pruneUnusedDefs(root: JsonSchemaObject): void {
232
232
  for (const ref of found) {
233
233
  if (!ref.startsWith(prefix))
234
234
  continue
235
- const name = ref.slice(prefix.length)
235
+ const rawSegment = ref.slice(prefix.length).split('/')[0] ?? ''
236
+ const name = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~')
236
237
  if (!visitedDefs.has(name) && Object.prototype.hasOwnProperty.call(defsRecord, name)) {
237
238
  visitedDefs.add(name)
238
239
  referenced.add(name)