@prunellejs/mcp 0.0.0-stage → 0.1.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,311 @@
1
+ // JSON-RPC 2.0 & MCP Streamable HTTP (2025-03-26) dispatcher with bounded batch execution.
2
+
3
+ import type { ActionContext, ActionResult, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
4
+ import type { McpPruneMode, McpToolResult } from './format'
5
+ import type { JsonSchemaObject } from './schema'
6
+ import { formatSchemaIssues, nodeEnv, validateSchema } from 'prunelle/server'
7
+ import { applyOutputBudget, finalizeToolValue, formatFieldErrors, formatResponseResult } from './format'
8
+
9
+ export const MCP_PROTOCOL_VERSION = '2025-03-26'
10
+ export const MAX_BATCH_SIZE = 50
11
+
12
+ export interface McpToolAnnotations {
13
+ title?: string | undefined
14
+ readOnlyHint?: boolean | undefined
15
+ destructiveHint?: boolean | undefined
16
+ idempotentHint?: boolean | undefined
17
+ openWorldHint?: boolean | undefined
18
+ }
19
+
20
+ export interface JsonRpcRequest {
21
+ jsonrpc: '2.0'
22
+ id?: string | number | null | undefined
23
+ method: string
24
+ params?: Record<string, unknown> | undefined
25
+ }
26
+
27
+ export interface JsonRpcResponse {
28
+ jsonrpc: '2.0'
29
+ id: string | number | null
30
+ result?: unknown
31
+ error?: { code: number, message: string, data?: unknown }
32
+ }
33
+
34
+ export interface ListedTool {
35
+ name: string
36
+ description: string
37
+ inputSchema: JsonSchemaObject
38
+ annotations?: McpToolAnnotations
39
+ }
40
+
41
+ export interface ResolvedResource {
42
+ uri: string
43
+ name: string
44
+ description?: string
45
+ mimeType: string
46
+ read: (ctx: RequestContext) => string | Promise<string>
47
+ }
48
+
49
+ export interface ResolvedToolEntry {
50
+ name: string
51
+ action?: ServerAction<unknown, unknown> | undefined
52
+ schema: StandardSchemaV1 | undefined
53
+ handler: (input: unknown, ctx: ActionContext) => unknown | Promise<unknown>
54
+ format: ((output: unknown, input: unknown) => unknown) | undefined
55
+ maxOutputChars: number | undefined
56
+ pruneEmpty: McpPruneMode
57
+ }
58
+
59
+ export interface RpcDispatcherConfig {
60
+ serverName: string
61
+ serverVersion: string
62
+ instructions?: string | undefined
63
+ listedTools: readonly ListedTool[]
64
+ toolMap: ReadonlyMap<string, ResolvedToolEntry>
65
+ resourceMap: ReadonlyMap<string, ResolvedResource>
66
+ listedResources: readonly { uri: string, name: string, description?: string, mimeType: string }[]
67
+ formatResult?: ((output: unknown, toolName: string, input: unknown) => unknown) | undefined
68
+ mapError?: ((error: unknown) => string | { message: string } | undefined) | undefined
69
+ }
70
+
71
+ function shouldExposeErrors(dev: boolean): boolean {
72
+ const env = nodeEnv()
73
+ if (env === 'production')
74
+ return false
75
+ return dev || env === 'development' || env === 'test'
76
+ }
77
+
78
+ function formatCaughtError(
79
+ err: unknown,
80
+ mapError: RpcDispatcherConfig['mapError'],
81
+ exposeInternal: boolean,
82
+ ): string {
83
+ const mapped = mapError?.(err)
84
+ if (typeof mapped === 'string')
85
+ return mapped
86
+ if (mapped && typeof mapped.message === 'string')
87
+ return mapped.message
88
+ if (!exposeInternal)
89
+ return 'Internal error'
90
+ return err instanceof Error ? err.message : String(err)
91
+ }
92
+
93
+ function formatActionFailure(invoked: Extract<ActionResult<unknown>, { ok: false }>): string {
94
+ if (invoked.issues !== undefined && invoked.issues.length > 0)
95
+ return `Invalid arguments: ${formatSchemaIssues(invoked.issues)}`
96
+ const fields = formatFieldErrors(invoked.fieldErrors)
97
+ return fields ? `${invoked.error} (${fields})` : invoked.error
98
+ }
99
+
100
+ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
101
+ const hasResources = cfg.resourceMap.size > 0
102
+ const availableNamesHint = cfg.toolMap.size > 0 && cfg.toolMap.size <= 12
103
+ ? ` (available: ${[...cfg.toolMap.keys()].join(', ')})`
104
+ : ''
105
+
106
+ async function callTool(name: string, args: unknown, ctx: RequestContext, dev: boolean): Promise<McpToolResult> {
107
+ const tool = cfg.toolMap.get(name)
108
+ if (tool === undefined)
109
+ throw Object.assign(new Error(`Unknown tool: ${name}${availableNamesHint}`), { rpcCode: -32602 })
110
+
111
+ let input: unknown = args ?? {}
112
+ // When backed by an action that already declares a schema, `tool.action(input)` runs
113
+ // `validateSchema` once inside `invokeActionCore`; re-validating here would double-run transforms/codecs.
114
+ const actionValidates = tool.action !== undefined && tool.action.schema !== undefined
115
+ if (tool.schema !== undefined && !actionValidates) {
116
+ const checked = await validateSchema(tool.schema, input)
117
+ if (!checked.ok) {
118
+ return {
119
+ content: [{ type: 'text', text: `Invalid arguments: ${formatSchemaIssues(checked.issues)}` }],
120
+ isError: true,
121
+ }
122
+ }
123
+ input = checked.value
124
+ }
125
+
126
+ try {
127
+ let rawResult: unknown
128
+ if (tool.action !== undefined) {
129
+ const invoked = await tool.action(input)
130
+ if (!invoked.ok) {
131
+ return applyOutputBudget({
132
+ content: [{ type: 'text', text: formatActionFailure(invoked) }],
133
+ isError: true,
134
+ }, tool.maxOutputChars)
135
+ }
136
+ rawResult = invoked.data
137
+ }
138
+ else {
139
+ rawResult = await tool.handler(input, ctx)
140
+ }
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)
152
+ }
153
+ catch (err) {
154
+ const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
155
+ return applyOutputBudget({
156
+ content: [{ type: 'text', text: message }],
157
+ isError: true,
158
+ }, tool.maxOutputChars)
159
+ }
160
+ }
161
+
162
+ async function handleMessage(msg: unknown, ctx: RequestContext, dev = false): Promise<JsonRpcResponse | null> {
163
+ if (typeof msg !== 'object' || msg === null)
164
+ return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } }
165
+
166
+ const req = msg as Partial<JsonRpcRequest>
167
+ const hasId = 'id' in req && req.id !== undefined
168
+ const id = hasId ? (req.id ?? null) : null
169
+
170
+ if (req.jsonrpc !== '2.0' || typeof req.method !== 'string')
171
+ return { jsonrpc: '2.0', id, error: { code: -32600, message: 'Invalid Request' } }
172
+
173
+ // JSON-RPC notifications (no `id`) receive no response payload (HTTP 202)
174
+ if (!hasId)
175
+ return null
176
+
177
+ switch (req.method) {
178
+ case 'initialize':
179
+ return {
180
+ jsonrpc: '2.0',
181
+ id,
182
+ result: {
183
+ protocolVersion: MCP_PROTOCOL_VERSION,
184
+ capabilities: {
185
+ tools: { listChanged: false },
186
+ ...(hasResources ? { resources: { subscribe: false, listChanged: false } } : {}),
187
+ },
188
+ serverInfo: { name: cfg.serverName, version: cfg.serverVersion },
189
+ ...(cfg.instructions !== undefined ? { instructions: cfg.instructions } : {}),
190
+ },
191
+ }
192
+
193
+ case 'ping':
194
+ return { jsonrpc: '2.0', id, result: {} }
195
+
196
+ case 'tools/list':
197
+ return {
198
+ jsonrpc: '2.0',
199
+ id,
200
+ result: {
201
+ tools: cfg.listedTools,
202
+ },
203
+ }
204
+
205
+ case 'tools/call': {
206
+ const params = req.params
207
+ const toolName = typeof params?.name === 'string' ? params.name : undefined
208
+ if (toolName === undefined)
209
+ return { jsonrpc: '2.0', id, error: { code: -32602, message: 'Missing tool name' } }
210
+ try {
211
+ const toolResult = await callTool(toolName, params?.arguments, ctx, dev)
212
+ return { jsonrpc: '2.0', id, result: toolResult }
213
+ }
214
+ catch (err) {
215
+ const rpcCode = (err as { rpcCode?: number }).rpcCode ?? -32603
216
+ const expose = rpcCode !== -32603 || shouldExposeErrors(dev)
217
+ const message = expose ? (err instanceof Error ? err.message : String(err)) : 'Internal error'
218
+ return { jsonrpc: '2.0', id, error: { code: rpcCode, message } }
219
+ }
220
+ }
221
+
222
+ case 'resources/list': {
223
+ if (!hasResources)
224
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${req.method}` } }
225
+ return {
226
+ jsonrpc: '2.0',
227
+ id,
228
+ result: { resources: cfg.listedResources },
229
+ }
230
+ }
231
+
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
+ }
256
+
257
+ default:
258
+ return {
259
+ jsonrpc: '2.0',
260
+ id,
261
+ error: { code: -32601, message: `Method not found: ${req.method}` },
262
+ }
263
+ }
264
+ }
265
+
266
+ async function handlePost(ctx: RequestContext, dev = false): Promise<Response> {
267
+ let payload: unknown
268
+ try {
269
+ payload = await ctx.request.json()
270
+ }
271
+ catch {
272
+ return Response.json(
273
+ { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } },
274
+ { status: 400 },
275
+ )
276
+ }
277
+
278
+ if (Array.isArray(payload)) {
279
+ if (payload.length === 0 || payload.length > MAX_BATCH_SIZE) {
280
+ return Response.json(
281
+ {
282
+ jsonrpc: '2.0',
283
+ id: null,
284
+ error: {
285
+ code: -32600,
286
+ message: payload.length === 0 ? 'Invalid Request' : `Batch size exceeds limit (${MAX_BATCH_SIZE})`,
287
+ },
288
+ },
289
+ { status: 400 },
290
+ )
291
+ }
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)
297
+ }
298
+ if (responses.length === 0)
299
+ return new Response(null, { status: 202 })
300
+ return Response.json(responses, { status: 200 })
301
+ }
302
+
303
+ const single = await handleMessage(payload, ctx, dev)
304
+ if (single === null)
305
+ return new Response(null, { status: 202 })
306
+ const status = single.error?.code === -32600 ? 400 : 200
307
+ return Response.json(single, { status })
308
+ }
309
+
310
+ return { handleMessage, handlePost }
311
+ }