@prunellejs/mcp 0.6.0 → 0.7.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/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.6.0",
3
+ "version": "0.7.1",
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.6.0"
24
+ "prunelle": "^0.7.1"
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,6 +11,7 @@ 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 { rateLimitKey } from 'prunelle/internal/server'
14
15
  import { isTrustedOrigin, nodeEnv, safeEqual } from 'prunelle/server'
15
16
  import { collectBudgetViolations, computeFootprint, formatMcpFootprint } from './footprint'
16
17
  import { createRpcDispatcher } from './rpc'
@@ -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,12 +430,10 @@ function extractBearerToken(request: Request): string | undefined {
429
430
  return token && token.length > 0 ? token : undefined
430
431
  }
431
432
 
432
- function resolveRateLimitKey(limit: RateLimit<RequestContext>, ctx: RequestContext): string {
433
- const custom = limit.key?.(ctx)
434
- if (custom !== undefined)
435
- return `k:${custom}`
436
- return ctx.ip !== undefined && ctx.ip !== '' ? `ip:${ctx.ip}` : 'ip:unknown'
437
- }
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 }
438
437
 
439
438
  function mcpTooManyRequests(retryAfter: number): Response {
440
439
  return Response.json(
@@ -477,15 +476,26 @@ export function mcp(options: McpOptions): PrunellePlugin {
477
476
  listedResources,
478
477
  formatResult: options.formatResult,
479
478
  mapError: options.mapError,
479
+ limiterFor: limit => actionLimiter?.(limit),
480
480
  })
481
481
 
482
- 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> {
483
488
  const configured = await resolveToken(options.token, readTokenFile)
484
- if (configured === undefined)
489
+ if (configured === undefined || Buffer.byteLength(configured) < MIN_TOKEN_BYTES)
485
490
  return new Response('Not Found', { status: 404 })
486
491
 
487
- 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)
488
497
  if (provided === undefined || !safeEqual(provided, configured)) {
498
+ failures?.hit(key)
489
499
  return Response.json(
490
500
  { error: 'Unauthorized' },
491
501
  { status: 401, headers: { 'www-authenticate': 'Bearer' } },
@@ -498,8 +508,11 @@ export function mcp(options: McpOptions): PrunellePlugin {
498
508
  name: '@prunellejs/mcp',
499
509
 
500
510
  async requires() {
501
- return await resolveToken(options.token, readTokenFile) === undefined
502
- ? ['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\`.`]
503
516
  : []
504
517
  },
505
518
 
@@ -519,10 +532,12 @@ export function mcp(options: McpOptions): PrunellePlugin {
519
532
  return Response.json({ error: `Forbidden: untrusted origin ${origin}` }, { status: 403 })
520
533
  }
521
534
 
535
+ failures = api.rateLimiter(FAILED_AUTH_LIMIT)
536
+ actionLimiter = api.rateLimiter
522
537
  const postLimiter = rateLimit !== undefined ? api.rateLimiter(rateLimit) : undefined
523
538
  const consumePostTokens = postLimiter !== undefined && rateLimit !== undefined
524
539
  ? (ctx: RequestContext, count: number): Response | undefined => {
525
- const key = resolveRateLimitKey(rateLimit, ctx)
540
+ const key = rateLimitKey(rateLimit, ctx)
526
541
  for (let i = 0; i < count; i++) {
527
542
  const retryAfter = postLimiter.hit(key)
528
543
  if (retryAfter > 0)
@@ -539,7 +554,7 @@ export function mcp(options: McpOptions): PrunellePlugin {
539
554
  const originDenied = checkOrigin(ctx)
540
555
  if (originDenied !== undefined)
541
556
  return originDenied
542
- const denied = await authorize(ctx.request)
557
+ const denied = await authorize(ctx)
543
558
  if (denied !== undefined)
544
559
  return denied
545
560
  return rpc.handlePost(ctx, api.dev, consumePostTokens)
@@ -549,7 +564,7 @@ export function mcp(options: McpOptions): PrunellePlugin {
549
564
  const originDenied = checkOrigin(ctx)
550
565
  if (originDenied !== undefined)
551
566
  return originDenied
552
- const denied = await authorize(ctx.request)
567
+ const denied = await authorize(ctx)
553
568
  if (denied !== undefined)
554
569
  return denied
555
570
  return new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST, DELETE' } })
@@ -559,7 +574,7 @@ export function mcp(options: McpOptions): PrunellePlugin {
559
574
  const originDenied = checkOrigin(ctx)
560
575
  if (originDenied !== undefined)
561
576
  return originDenied
562
- const denied = await authorize(ctx.request)
577
+ const denied = await authorize(ctx)
563
578
  if (denied !== undefined)
564
579
  return denied
565
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 {
@@ -130,12 +135,58 @@ async function handleResourceRead(
130
135
 
131
136
  export type BatchRateLimitCheck = (ctx: RequestContext, extraCalls: number) => Response | undefined
132
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
+
133
182
  export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
134
183
  const hasResources = cfg.resourceMap.size > 0
135
184
  const availableNamesHint = cfg.toolMap.size > 0 && cfg.toolMap.size <= 12
136
185
  ? ` (available: ${[...cfg.toolMap.keys()].join(', ')})`
137
186
  : ''
138
187
 
188
+ const actionRetryAfter = createActionGuard(cfg.limiterFor)
189
+
139
190
  async function callTool(name: string, args: unknown, ctx: RequestContext, dev: boolean): Promise<McpToolResult> {
140
191
  const tool = cfg.toolMap.get(name)
141
192
  if (tool === undefined)
@@ -159,6 +210,13 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
159
210
  try {
160
211
  let rawResult: unknown
161
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
+ }
162
220
  const invoked = await tool.action(input)
163
221
  if (!invoked.ok) {
164
222
  return applyOutputBudget({
@@ -171,17 +229,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
171
229
  else {
172
230
  rawResult = await tool.handler(input, ctx)
173
231
  }
174
- let mcpResult: McpToolResult
175
- if (rawResult instanceof Response) {
176
- mcpResult = await formatResponseResult(rawResult, tool.pruneEmpty)
177
- }
178
- else {
179
- const formatted = tool.format !== undefined
180
- ? tool.format(rawResult, input)
181
- : (cfg.formatResult !== undefined ? cfg.formatResult(rawResult, name, input) : rawResult)
182
- mcpResult = await finalizeToolValue(formatted, tool.pruneEmpty)
183
- }
184
- return applyOutputBudget(mcpResult, tool.maxOutputChars)
232
+ return applyOutputBudget(await shapeResult(cfg, tool, name, rawResult, input), tool.maxOutputChars)
185
233
  }
186
234
  catch (err) {
187
235
  const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
@@ -305,12 +353,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
305
353
  if (limited !== undefined)
306
354
  return limited
307
355
  }
308
- const responses: JsonRpcResponse[] = []
309
- for (const item of payload) {
310
- const res = await handleMessage(item, ctx, dev)
311
- if (res !== null)
312
- responses.push(res)
313
- }
356
+ const responses = await runBatch(payload, item => handleMessage(item, ctx, dev))
314
357
  if (responses.length === 0)
315
358
  return new Response(null, { status: 202 })
316
359
  return Response.json(responses, { status: 200 })