@prunellejs/mcp 0.1.1 → 0.7.3
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 +21 -0
- package/llms.txt +3 -2
- package/package.json +2 -2
- package/src/index.ts +108 -39
- package/src/rpc.ts +101 -42
- package/src/schema.ts +2 -1
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
|
|
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
|
|
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.
|
|
3
|
+
"version": "0.7.3",
|
|
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.
|
|
24
|
+
"prunelle": "^0.7.3"
|
|
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 {
|
|
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,46 @@ 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_MAX = 10
|
|
437
|
+
const FAILED_AUTH_WINDOW_MS = 60_000
|
|
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
|
+
|
|
446
|
+
function createAuthorizer(
|
|
447
|
+
tokenSource: McpTokenSource | undefined,
|
|
448
|
+
readTokenFile: (filePath: string) => Promise<string | undefined>,
|
|
449
|
+
failedAuthLimit: RateLimit<RequestContext>,
|
|
450
|
+
failures: RateLimiter,
|
|
451
|
+
): (ctx: RequestContext) => Promise<Response | undefined> {
|
|
452
|
+
return async (ctx) => {
|
|
453
|
+
const configured = await resolveToken(tokenSource, readTokenFile)
|
|
454
|
+
if (configured === undefined || Buffer.byteLength(configured) < MIN_TOKEN_BYTES)
|
|
455
|
+
return new Response('Not Found', { status: 404 })
|
|
456
|
+
|
|
457
|
+
const key = rateLimitKey(failedAuthLimit, ctx)
|
|
458
|
+
const retryAfter = failures.peek(key)
|
|
459
|
+
if (retryAfter > 0)
|
|
460
|
+
return mcpTooManyRequests(retryAfter)
|
|
461
|
+
const provided = extractBearerToken(ctx.request)
|
|
462
|
+
if (provided === undefined || !safeEqual(provided, configured)) {
|
|
463
|
+
failures.hit(key)
|
|
464
|
+
return Response.json(
|
|
465
|
+
{ error: 'Unauthorized' },
|
|
466
|
+
{ status: 401, headers: { 'www-authenticate': 'Bearer' } },
|
|
467
|
+
)
|
|
468
|
+
}
|
|
469
|
+
return undefined
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
432
473
|
export function mcp<T extends Record<string, unknown>>(
|
|
433
474
|
options: Omit<McpOptions, 'tools'> & { tools: McpToolsRecord<T> },
|
|
434
475
|
): PrunellePlugin
|
|
@@ -453,39 +494,15 @@ export function mcp(options: McpOptions): PrunellePlugin {
|
|
|
453
494
|
const warnSink = customWarn ?? ((msg: string) => console.warn(msg))
|
|
454
495
|
const readTokenFile = createTokenFileReader()
|
|
455
496
|
|
|
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
497
|
return definePlugin({
|
|
484
498
|
name: '@prunellejs/mcp',
|
|
485
499
|
|
|
486
500
|
async requires() {
|
|
487
|
-
|
|
488
|
-
|
|
501
|
+
const configured = await resolveToken(options.token, readTokenFile)
|
|
502
|
+
if (configured === undefined)
|
|
503
|
+
return ['no `token`, so the endpoint answers 404 to every call: pass `token: { env: \'MCP_TOKEN\' }` and set `MCP_TOKEN`, or `token: { file }`.']
|
|
504
|
+
return Buffer.byteLength(configured) < MIN_TOKEN_BYTES
|
|
505
|
+
? [`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
506
|
: []
|
|
490
507
|
},
|
|
491
508
|
|
|
@@ -495,26 +512,78 @@ export function mcp(options: McpOptions): PrunellePlugin {
|
|
|
495
512
|
warnSink(msg)
|
|
496
513
|
}
|
|
497
514
|
|
|
515
|
+
const trustedOrigins = api.trustedOrigins.length > 0 ? new Set(api.trustedOrigins) : undefined
|
|
516
|
+
const checkOrigin = (ctx: RequestContext): Response | undefined => {
|
|
517
|
+
const origin = ctx.request.headers.get('origin')
|
|
518
|
+
if (origin === null)
|
|
519
|
+
return undefined
|
|
520
|
+
if (isTrustedOrigin(origin, ctx.request, trustedOrigins, api.trustProxy, ctx.url))
|
|
521
|
+
return undefined
|
|
522
|
+
return Response.json({ error: `Forbidden: untrusted origin ${origin}` }, { status: 403 })
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const failedAuthLimit: RateLimit<RequestContext> = { max: FAILED_AUTH_MAX, windowMs: FAILED_AUTH_WINDOW_MS }
|
|
526
|
+
const failures = api.rateLimiter(failedAuthLimit)
|
|
527
|
+
const authorize = createAuthorizer(options.token, readTokenFile, failedAuthLimit, failures)
|
|
528
|
+
const rpc = createRpcDispatcher({
|
|
529
|
+
serverName,
|
|
530
|
+
serverVersion,
|
|
531
|
+
instructions: options.instructions,
|
|
532
|
+
listedTools,
|
|
533
|
+
toolMap,
|
|
534
|
+
resourceMap,
|
|
535
|
+
listedResources,
|
|
536
|
+
formatResult: options.formatResult,
|
|
537
|
+
mapError: options.mapError,
|
|
538
|
+
limiterFor: limit => api.rateLimiter(limit),
|
|
539
|
+
})
|
|
540
|
+
|
|
541
|
+
const serverRateLimit = rateLimit !== undefined ? { ...rateLimit } : undefined
|
|
542
|
+
const postLimiter = serverRateLimit !== undefined ? api.rateLimiter(serverRateLimit) : undefined
|
|
543
|
+
const consumePostTokens = postLimiter !== undefined && serverRateLimit !== undefined
|
|
544
|
+
? (ctx: RequestContext, count: number): Response | undefined => {
|
|
545
|
+
const key = rateLimitKey(serverRateLimit, ctx)
|
|
546
|
+
for (let i = 0; i < count; i++) {
|
|
547
|
+
const retryAfter = postLimiter.hit(key)
|
|
548
|
+
if (retryAfter > 0)
|
|
549
|
+
return mcpTooManyRequests(retryAfter)
|
|
550
|
+
}
|
|
551
|
+
return undefined
|
|
552
|
+
}
|
|
553
|
+
: undefined
|
|
554
|
+
|
|
498
555
|
api.route('POST', endpoint, async (ctx) => {
|
|
499
|
-
const
|
|
556
|
+
const limited = consumePostTokens?.(ctx, 1)
|
|
557
|
+
if (limited !== undefined)
|
|
558
|
+
return limited
|
|
559
|
+
const originDenied = checkOrigin(ctx)
|
|
560
|
+
if (originDenied !== undefined)
|
|
561
|
+
return originDenied
|
|
562
|
+
const denied = await authorize(ctx)
|
|
500
563
|
if (denied !== undefined)
|
|
501
564
|
return denied
|
|
502
|
-
return rpc.handlePost(ctx, api.dev)
|
|
503
|
-
}, { csrf: false
|
|
565
|
+
return rpc.handlePost(ctx, api.dev, consumePostTokens)
|
|
566
|
+
}, { csrf: false })
|
|
504
567
|
|
|
505
568
|
api.route('GET', endpoint, async (ctx) => {
|
|
506
|
-
const
|
|
569
|
+
const originDenied = checkOrigin(ctx)
|
|
570
|
+
if (originDenied !== undefined)
|
|
571
|
+
return originDenied
|
|
572
|
+
const denied = await authorize(ctx)
|
|
507
573
|
if (denied !== undefined)
|
|
508
574
|
return denied
|
|
509
575
|
return new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST, DELETE' } })
|
|
510
|
-
}, { rateLimit })
|
|
576
|
+
}, { rateLimit: serverRateLimit })
|
|
511
577
|
|
|
512
578
|
api.route('DELETE', endpoint, async (ctx) => {
|
|
513
|
-
const
|
|
579
|
+
const originDenied = checkOrigin(ctx)
|
|
580
|
+
if (originDenied !== undefined)
|
|
581
|
+
return originDenied
|
|
582
|
+
const denied = await authorize(ctx)
|
|
514
583
|
if (denied !== undefined)
|
|
515
584
|
return denied
|
|
516
585
|
return new Response(null, { status: 204 })
|
|
517
|
-
}, { csrf: false, rateLimit })
|
|
586
|
+
}, { csrf: false, rateLimit: serverRateLimit })
|
|
518
587
|
},
|
|
519
588
|
|
|
520
589
|
check(ctx) {
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
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
|
|
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)
|