@prunellejs/mcp 0.0.0-stage → 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/src/rpc.ts ADDED
@@ -0,0 +1,370 @@
1
+ // JSON-RPC 2.0 & MCP Streamable HTTP (2025-03-26) dispatcher with bounded batch execution.
2
+
3
+ import type { ActionContext, ActionResult, RateLimit, RateLimiter, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
4
+ import type { McpPruneMode, McpToolResult } from './format'
5
+ import type { JsonSchemaObject } from './schema'
6
+ import { rateLimitKey } from 'prunelle/internal/server'
7
+ import { formatSchemaIssues, nodeEnv, validateSchema } from 'prunelle/server'
8
+ import { applyOutputBudget, finalizeToolValue, formatFieldErrors, formatResponseResult } from './format'
9
+
10
+ export const MCP_PROTOCOL_VERSION = '2025-03-26'
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
14
+
15
+ export interface McpToolAnnotations {
16
+ title?: string | undefined
17
+ readOnlyHint?: boolean | undefined
18
+ destructiveHint?: boolean | undefined
19
+ idempotentHint?: boolean | undefined
20
+ openWorldHint?: boolean | undefined
21
+ }
22
+
23
+ export interface JsonRpcRequest {
24
+ jsonrpc: '2.0'
25
+ id?: string | number | null | undefined
26
+ method: string
27
+ params?: Record<string, unknown> | undefined
28
+ }
29
+
30
+ export interface JsonRpcResponse {
31
+ jsonrpc: '2.0'
32
+ id: string | number | null
33
+ result?: unknown
34
+ error?: { code: number, message: string, data?: unknown }
35
+ }
36
+
37
+ export interface ListedTool {
38
+ name: string
39
+ description: string
40
+ inputSchema: JsonSchemaObject
41
+ annotations?: McpToolAnnotations
42
+ }
43
+
44
+ export interface ResolvedResource {
45
+ uri: string
46
+ name: string
47
+ description?: string
48
+ mimeType: string
49
+ read: (ctx: RequestContext) => string | Promise<string>
50
+ }
51
+
52
+ export interface ResolvedToolEntry {
53
+ name: string
54
+ action?: ServerAction<unknown, unknown> | undefined
55
+ schema: StandardSchemaV1 | undefined
56
+ handler: (input: unknown, ctx: ActionContext) => unknown | Promise<unknown>
57
+ format: ((output: unknown, input: unknown) => unknown) | undefined
58
+ maxOutputChars: number | undefined
59
+ pruneEmpty: McpPruneMode
60
+ }
61
+
62
+ export interface RpcDispatcherConfig {
63
+ serverName: string
64
+ serverVersion: string
65
+ instructions?: string | undefined
66
+ listedTools: readonly ListedTool[]
67
+ toolMap: ReadonlyMap<string, ResolvedToolEntry>
68
+ resourceMap: ReadonlyMap<string, ResolvedResource>
69
+ listedResources: readonly { uri: string, name: string, description?: string, mimeType: string }[]
70
+ formatResult?: ((output: unknown, toolName: string, input: unknown) => unknown) | undefined
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
74
+ }
75
+
76
+ function shouldExposeErrors(dev: boolean): boolean {
77
+ const env = nodeEnv()
78
+ if (env === 'production')
79
+ return false
80
+ return dev || env === 'development' || env === 'test'
81
+ }
82
+
83
+ function formatCaughtError(
84
+ err: unknown,
85
+ mapError: RpcDispatcherConfig['mapError'],
86
+ exposeInternal: boolean,
87
+ ): string {
88
+ const mapped = mapError?.(err)
89
+ if (typeof mapped === 'string')
90
+ return mapped
91
+ if (mapped && typeof mapped.message === 'string')
92
+ return mapped.message
93
+ if (!exposeInternal)
94
+ return 'Internal error'
95
+ return err instanceof Error ? err.message : String(err)
96
+ }
97
+
98
+ function formatActionFailure(invoked: Extract<ActionResult<unknown>, { ok: false }>): string {
99
+ if (invoked.issues !== undefined && invoked.issues.length > 0)
100
+ return `Invalid arguments: ${formatSchemaIssues(invoked.issues)}`
101
+ const fields = formatFieldErrors(invoked.fieldErrors)
102
+ return fields ? `${invoked.error} (${fields})` : invoked.error
103
+ }
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
+
182
+ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
183
+ const hasResources = cfg.resourceMap.size > 0
184
+ const availableNamesHint = cfg.toolMap.size > 0 && cfg.toolMap.size <= 12
185
+ ? ` (available: ${[...cfg.toolMap.keys()].join(', ')})`
186
+ : ''
187
+
188
+ const actionRetryAfter = createActionGuard(cfg.limiterFor)
189
+
190
+ async function callTool(name: string, args: unknown, ctx: RequestContext, dev: boolean): Promise<McpToolResult> {
191
+ const tool = cfg.toolMap.get(name)
192
+ if (tool === undefined)
193
+ throw Object.assign(new Error(`Unknown tool: ${name}${availableNamesHint}`), { rpcCode: -32602 })
194
+
195
+ let input: unknown = args ?? {}
196
+ // When backed by an action that already declares a schema, `tool.action(input)` runs
197
+ // `validateSchema` once inside `invokeActionCore`; re-validating here would double-run transforms/codecs.
198
+ const actionValidates = tool.action !== undefined && tool.action.schema !== undefined
199
+ if (tool.schema !== undefined && !actionValidates) {
200
+ const checked = await validateSchema(tool.schema, input)
201
+ if (!checked.ok) {
202
+ return {
203
+ content: [{ type: 'text', text: `Invalid arguments: ${formatSchemaIssues(checked.issues)}` }],
204
+ isError: true,
205
+ }
206
+ }
207
+ input = checked.value
208
+ }
209
+
210
+ try {
211
+ let rawResult: unknown
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
+ }
220
+ const invoked = await tool.action(input)
221
+ if (!invoked.ok) {
222
+ return applyOutputBudget({
223
+ content: [{ type: 'text', text: formatActionFailure(invoked) }],
224
+ isError: true,
225
+ }, tool.maxOutputChars)
226
+ }
227
+ rawResult = invoked.data
228
+ }
229
+ else {
230
+ rawResult = await tool.handler(input, ctx)
231
+ }
232
+ return applyOutputBudget(await shapeResult(cfg, tool, name, rawResult, input), tool.maxOutputChars)
233
+ }
234
+ catch (err) {
235
+ const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
236
+ return applyOutputBudget({
237
+ content: [{ type: 'text', text: message }],
238
+ isError: true,
239
+ }, tool.maxOutputChars)
240
+ }
241
+ }
242
+
243
+ async function handleMessage(msg: unknown, ctx: RequestContext, dev = false): Promise<JsonRpcResponse | null> {
244
+ if (typeof msg !== 'object' || msg === null)
245
+ return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } }
246
+
247
+ const req = msg as Partial<JsonRpcRequest>
248
+ const hasId = 'id' in req && req.id !== undefined
249
+ const id = hasId ? (req.id ?? null) : null
250
+
251
+ if (req.jsonrpc !== '2.0' || typeof req.method !== 'string')
252
+ return { jsonrpc: '2.0', id, error: { code: -32600, message: 'Invalid Request' } }
253
+
254
+ // JSON-RPC notifications (no `id`) receive no response payload (HTTP 202)
255
+ if (!hasId)
256
+ return null
257
+
258
+ switch (req.method) {
259
+ case 'initialize':
260
+ return {
261
+ jsonrpc: '2.0',
262
+ id,
263
+ result: {
264
+ protocolVersion: MCP_PROTOCOL_VERSION,
265
+ capabilities: {
266
+ tools: { listChanged: false },
267
+ ...(hasResources ? { resources: { subscribe: false, listChanged: false } } : {}),
268
+ },
269
+ serverInfo: { name: cfg.serverName, version: cfg.serverVersion },
270
+ ...(cfg.instructions !== undefined ? { instructions: cfg.instructions } : {}),
271
+ },
272
+ }
273
+
274
+ case 'ping':
275
+ return { jsonrpc: '2.0', id, result: {} }
276
+
277
+ case 'tools/list':
278
+ return {
279
+ jsonrpc: '2.0',
280
+ id,
281
+ result: {
282
+ tools: cfg.listedTools,
283
+ },
284
+ }
285
+
286
+ case 'tools/call': {
287
+ const params = req.params
288
+ const toolName = typeof params?.name === 'string' ? params.name : undefined
289
+ if (toolName === undefined)
290
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: 'Missing tool name' } }
291
+ try {
292
+ const toolResult = await callTool(toolName, params?.arguments, ctx, dev)
293
+ return { jsonrpc: '2.0', id, result: toolResult }
294
+ }
295
+ catch (err) {
296
+ const rpcCode = (err as { rpcCode?: number }).rpcCode ?? -32603
297
+ const expose = rpcCode !== -32603 || shouldExposeErrors(dev)
298
+ const message = expose ? (err instanceof Error ? err.message : String(err)) : 'Internal error'
299
+ return { jsonrpc: '2.0', id, error: { code: rpcCode, message } }
300
+ }
301
+ }
302
+
303
+ case 'resources/list': {
304
+ if (!hasResources)
305
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${req.method}` } }
306
+ return {
307
+ jsonrpc: '2.0',
308
+ id,
309
+ result: { resources: cfg.listedResources },
310
+ }
311
+ }
312
+
313
+ case 'resources/read':
314
+ return handleResourceRead(cfg, id, req.params, ctx, dev)
315
+
316
+ default:
317
+ return {
318
+ jsonrpc: '2.0',
319
+ id,
320
+ error: { code: -32601, message: `Method not found: ${req.method}` },
321
+ }
322
+ }
323
+ }
324
+
325
+ async function handlePost(ctx: RequestContext, dev = false, checkBatchRateLimit?: BatchRateLimitCheck): Promise<Response> {
326
+ let payload: unknown
327
+ try {
328
+ payload = await ctx.request.json()
329
+ }
330
+ catch {
331
+ return Response.json(
332
+ { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } },
333
+ { status: 400 },
334
+ )
335
+ }
336
+
337
+ if (Array.isArray(payload)) {
338
+ if (payload.length === 0 || payload.length > MAX_BATCH_SIZE) {
339
+ return Response.json(
340
+ {
341
+ jsonrpc: '2.0',
342
+ id: null,
343
+ error: {
344
+ code: -32600,
345
+ message: payload.length === 0 ? 'Invalid Request' : `Batch size exceeds limit (${MAX_BATCH_SIZE})`,
346
+ },
347
+ },
348
+ { status: 400 },
349
+ )
350
+ }
351
+ if (checkBatchRateLimit !== undefined && payload.length > 1) {
352
+ const limited = checkBatchRateLimit(ctx, payload.length - 1)
353
+ if (limited !== undefined)
354
+ return limited
355
+ }
356
+ const responses = await runBatch(payload, item => handleMessage(item, ctx, dev))
357
+ if (responses.length === 0)
358
+ return new Response(null, { status: 202 })
359
+ return Response.json(responses, { status: 200 })
360
+ }
361
+
362
+ const single = await handleMessage(payload, ctx, dev)
363
+ if (single === null)
364
+ return new Response(null, { status: 202 })
365
+ const status = single.error?.code === -32600 ? 400 : 200
366
+ return Response.json(single, { status })
367
+ }
368
+
369
+ return { handleMessage, handlePost }
370
+ }