@prunellejs/mcp 0.1.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/mcp",
3
- "version": "0.1.1",
3
+ "version": "0.6.0",
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.6.0"
25
25
  }
26
26
  }
package/src/index.ts CHANGED
@@ -11,7 +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 { nodeEnv, safeEqual } from 'prunelle/server'
14
+ import { isTrustedOrigin, nodeEnv, safeEqual } from 'prunelle/server'
15
15
  import { collectBudgetViolations, computeFootprint, formatMcpFootprint } from './footprint'
16
16
  import { createRpcDispatcher } from './rpc'
17
17
  import { isPlainRecord, isStandardSchema, normalizeObjectSchema, schemaToJsonSchema } from './schema'
@@ -429,6 +429,20 @@ function extractBearerToken(request: Request): string | undefined {
429
429
  return token && token.length > 0 ? token : undefined
430
430
  }
431
431
 
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
+ }
438
+
439
+ function mcpTooManyRequests(retryAfter: number): Response {
440
+ return Response.json(
441
+ { ok: false, status: 429, error: 'Too many requests' },
442
+ { status: 429, headers: { 'retry-after': String(retryAfter) } },
443
+ )
444
+ }
445
+
432
446
  export function mcp<T extends Record<string, unknown>>(
433
447
  options: Omit<McpOptions, 'tools'> & { tools: McpToolsRecord<T> },
434
448
  ): PrunellePlugin
@@ -495,14 +509,46 @@ export function mcp(options: McpOptions): PrunellePlugin {
495
509
  warnSink(msg)
496
510
  }
497
511
 
512
+ const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
513
+ const checkOrigin = (ctx: RequestContext): Response | undefined => {
514
+ const origin = ctx.request.headers.get('origin')
515
+ if (origin === null)
516
+ return undefined
517
+ if (isTrustedOrigin(origin, ctx.request, trustedOrigins, api.trustProxy, ctx.url))
518
+ return undefined
519
+ return Response.json({ error: `Forbidden: untrusted origin ${origin}` }, { status: 403 })
520
+ }
521
+
522
+ const postLimiter = rateLimit !== undefined ? api.rateLimiter(rateLimit) : undefined
523
+ const consumePostTokens = postLimiter !== undefined && rateLimit !== undefined
524
+ ? (ctx: RequestContext, count: number): Response | undefined => {
525
+ const key = resolveRateLimitKey(rateLimit, ctx)
526
+ for (let i = 0; i < count; i++) {
527
+ const retryAfter = postLimiter.hit(key)
528
+ if (retryAfter > 0)
529
+ return mcpTooManyRequests(retryAfter)
530
+ }
531
+ return undefined
532
+ }
533
+ : undefined
534
+
498
535
  api.route('POST', endpoint, async (ctx) => {
536
+ const limited = consumePostTokens?.(ctx, 1)
537
+ if (limited !== undefined)
538
+ return limited
539
+ const originDenied = checkOrigin(ctx)
540
+ if (originDenied !== undefined)
541
+ return originDenied
499
542
  const denied = await authorize(ctx.request)
500
543
  if (denied !== undefined)
501
544
  return denied
502
- return rpc.handlePost(ctx, api.dev)
503
- }, { csrf: false, rateLimit })
545
+ return rpc.handlePost(ctx, api.dev, consumePostTokens)
546
+ }, { csrf: false })
504
547
 
505
548
  api.route('GET', endpoint, async (ctx) => {
549
+ const originDenied = checkOrigin(ctx)
550
+ if (originDenied !== undefined)
551
+ return originDenied
506
552
  const denied = await authorize(ctx.request)
507
553
  if (denied !== undefined)
508
554
  return denied
@@ -510,6 +556,9 @@ export function mcp(options: McpOptions): PrunellePlugin {
510
556
  }, { rateLimit })
511
557
 
512
558
  api.route('DELETE', endpoint, async (ctx) => {
559
+ const originDenied = checkOrigin(ctx)
560
+ if (originDenied !== undefined)
561
+ return originDenied
513
562
  const denied = await authorize(ctx.request)
514
563
  if (denied !== undefined)
515
564
  return denied
package/src/rpc.ts CHANGED
@@ -97,6 +97,39 @@ function formatActionFailure(invoked: Extract<ActionResult<unknown>, { ok: false
97
97
  return fields ? `${invoked.error} (${fields})` : invoked.error
98
98
  }
99
99
 
100
+ async function handleResourceRead(
101
+ cfg: RpcDispatcherConfig,
102
+ id: string | number | null,
103
+ params: Record<string, unknown> | undefined,
104
+ ctx: RequestContext,
105
+ dev: boolean,
106
+ ): Promise<JsonRpcResponse> {
107
+ if (cfg.resourceMap.size === 0)
108
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found: resources/read' } }
109
+ const uri = typeof params?.uri === 'string' ? params.uri : undefined
110
+ if (uri === undefined)
111
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: 'Missing resource uri' } }
112
+ const resource = cfg.resourceMap.get(uri)
113
+ if (resource === undefined)
114
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: `Unknown resource: ${uri}` } }
115
+ try {
116
+ const text = await resource.read(ctx)
117
+ return {
118
+ jsonrpc: '2.0',
119
+ id,
120
+ result: {
121
+ contents: [{ uri: resource.uri, mimeType: resource.mimeType, text }],
122
+ },
123
+ }
124
+ }
125
+ catch (err) {
126
+ const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
127
+ return { jsonrpc: '2.0', id, error: { code: -32603, message } }
128
+ }
129
+ }
130
+
131
+ export type BatchRateLimitCheck = (ctx: RequestContext, extraCalls: number) => Response | undefined
132
+
100
133
  export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
101
134
  const hasResources = cfg.resourceMap.size > 0
102
135
  const availableNamesHint = cfg.toolMap.size > 0 && cfg.toolMap.size <= 12
@@ -229,30 +262,8 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
229
262
  }
230
263
  }
231
264
 
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
- }
265
+ case 'resources/read':
266
+ return handleResourceRead(cfg, id, req.params, ctx, dev)
256
267
 
257
268
  default:
258
269
  return {
@@ -263,7 +274,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
263
274
  }
264
275
  }
265
276
 
266
- async function handlePost(ctx: RequestContext, dev = false): Promise<Response> {
277
+ async function handlePost(ctx: RequestContext, dev = false, checkBatchRateLimit?: BatchRateLimitCheck): Promise<Response> {
267
278
  let payload: unknown
268
279
  try {
269
280
  payload = await ctx.request.json()
@@ -289,6 +300,11 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
289
300
  { status: 400 },
290
301
  )
291
302
  }
303
+ if (checkBatchRateLimit !== undefined && payload.length > 1) {
304
+ const limited = checkBatchRateLimit(ctx, payload.length - 1)
305
+ if (limited !== undefined)
306
+ return limited
307
+ }
292
308
  const responses: JsonRpcResponse[] = []
293
309
  for (const item of payload) {
294
310
  const res = await handleMessage(item, ctx, dev)
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)