@prunellejs/mcp 0.7.7 → 0.9.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/llms.txt +4 -4
- package/package.json +3 -3
- package/src/auth.ts +240 -0
- package/src/format.ts +26 -25
- package/src/index.ts +23 -147
- package/src/rpc.ts +101 -79
- package/src/schema.ts +102 -87
package/llms.txt
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
# @prunellejs/mcp Reference
|
|
2
2
|
|
|
3
|
-
> Zero-dependency MCP Streamable HTTP (`2025-03-26`)
|
|
3
|
+
> Zero-dependency MCP plugin over the JSON-only subset of Streamable HTTP (`2025-03-26`: `POST` answers `application/json`, `GET` answers `405`, no SSE stream) exposing typed Prunelle `action()` handlers and standalone handlers as bearer-authenticated AI agent tools and resources.
|
|
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` (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`.
|
|
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`, `McpAuthenticator`, `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>)
|
|
14
|
+
- `token`: `string | { env: string } | { file: string } | (() => string | undefined | Promise<string | undefined>)` (relative `{ file }` paths resolve against the app root). `authenticate`: `(token, ctx) => boolean | object | string | number | null | undefined | Promise<...>` validates dynamic bearer tokens and populates `ctx.locals` (e.g. `ctx.locals.user`) for actions, guards, handlers, and resources; falsy return or thrown error answers `401` and counts against the failed-auth lockout. When both `token` and `authenticate` are set, both must pass. With neither configured (or a `token` shorter than 32 bytes), the endpoint returns `404` and a production start refuses (`openssl rand -hex 32` makes a static token); 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 a valid token.
|
|
15
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.
|
|
16
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.
|
|
17
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`.
|
|
18
18
|
- `schemas`: shared schemas exposed on demand via auto-added `describe_schema` tool and `prunelle://schemas/<name>` resources.
|
|
19
19
|
- `resources`: `Record<uri, { name?, description?, mimeType?, read: string | ((ctx) => string | Promise<string>) }>`.
|
|
20
|
-
- Compact output & footprint options: `compactSchemas` (default `true`), `pruneEmpty` (`false | 'nullish' | true`), `maxOutputChars`, `formatResult(output, toolName, input)`, `mapError(err)`, `budget` (default `{ maxToolBytes: 2048 }`; `strict: true` fails `prunelle check`; `false` disables).
|
|
20
|
+
- Compact output & footprint options: `compactSchemas` (default `true`; pass `{ foldHomogeneousObjects: true }` to opt into folding homogeneous optional objects into `additionalProperties`), `pruneEmpty` (`false | 'nullish' | true`), `maxOutputChars`, `formatResult(output, toolName, input)`, `mapError(err)`, `budget` (default `{ maxToolBytes: 2048 }`; `strict: true` fails `prunelle check`; `false` disables).
|
|
21
21
|
|
|
22
22
|
## Mounted Routes & CLI
|
|
23
23
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Zero-dependency MCP Streamable HTTP
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"description": "Zero-dependency MCP plugin (JSON-only subset of Streamable HTTP, 2025-03-26) exposing Prunelle server actions as AI agent tools",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"sideEffects": false,
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
"directory": "packages/plugin-mcp"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
|
-
"prunelle": "^0.
|
|
24
|
+
"prunelle": "^0.9.0"
|
|
25
25
|
}
|
|
26
26
|
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Bearer-token resolution, request authorization (static token and custom `authenticate` hook),
|
|
2
|
+
// and batch-aware POST rate limiting for @prunellejs/mcp.
|
|
3
|
+
|
|
4
|
+
import type { RateLimit, RateLimiter, RequestContext, SharedStore } from 'prunelle/server'
|
|
5
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
6
|
+
import { resolve } from 'node:path'
|
|
7
|
+
import { rateLimitKey } from 'prunelle/internal/server'
|
|
8
|
+
import { safeEqual } from 'prunelle/server'
|
|
9
|
+
|
|
10
|
+
export type McpTokenSource =
|
|
11
|
+
| string
|
|
12
|
+
| { env: string }
|
|
13
|
+
| { file: string }
|
|
14
|
+
| (() => string | undefined | Promise<string | undefined>)
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Custom bearer-token authenticator: receives the extracted bearer token and request context.
|
|
18
|
+
* Populate `ctx.locals` (for example `ctx.locals.user`) when authenticated, and return `true`
|
|
19
|
+
* (or any truthy value) to allow the request, or `false` / `null` / `undefined` to reject with `401`.
|
|
20
|
+
*/
|
|
21
|
+
export type McpAuthenticator = (
|
|
22
|
+
token: string,
|
|
23
|
+
ctx: RequestContext,
|
|
24
|
+
) => boolean | object | string | number | null | undefined | Promise<boolean | object | string | number | null | undefined>
|
|
25
|
+
|
|
26
|
+
/** The shortest bearer token the endpoint accepts: 32 bytes, the size of a random key. */
|
|
27
|
+
export const MIN_TOKEN_BYTES = 32
|
|
28
|
+
/** Wrong or missing bearer tokens one client may send per window before the endpoint answers 429. */
|
|
29
|
+
export const FAILED_AUTH_MAX = 10
|
|
30
|
+
export const FAILED_AUTH_WINDOW_MS = 60_000
|
|
31
|
+
|
|
32
|
+
const MCP_POST_SCOPE = '@prunellejs/mcp:post'
|
|
33
|
+
|
|
34
|
+
interface CachedTokenFile {
|
|
35
|
+
mtimeNs: bigint
|
|
36
|
+
ctimeNs: bigint
|
|
37
|
+
size: bigint
|
|
38
|
+
ino: bigint
|
|
39
|
+
token: string | undefined
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function createTokenFileReader(): (filePath: string) => Promise<string | undefined> {
|
|
43
|
+
const cache = new Map<string, CachedTokenFile>()
|
|
44
|
+
|
|
45
|
+
return async (filePath: string): Promise<string | undefined> => {
|
|
46
|
+
try {
|
|
47
|
+
const info = await stat(filePath, { bigint: true })
|
|
48
|
+
const prev = cache.get(filePath)
|
|
49
|
+
if (
|
|
50
|
+
prev !== undefined
|
|
51
|
+
&& prev.mtimeNs === info.mtimeNs
|
|
52
|
+
&& prev.ctimeNs === info.ctimeNs
|
|
53
|
+
&& prev.size === info.size
|
|
54
|
+
&& prev.ino === info.ino
|
|
55
|
+
) {
|
|
56
|
+
return prev.token
|
|
57
|
+
}
|
|
58
|
+
const raw = (await readFile(filePath, 'utf8')).trim()
|
|
59
|
+
const token = raw.length > 0 ? raw : undefined
|
|
60
|
+
cache.set(filePath, {
|
|
61
|
+
mtimeNs: info.mtimeNs,
|
|
62
|
+
ctimeNs: info.ctimeNs,
|
|
63
|
+
size: info.size,
|
|
64
|
+
ino: info.ino,
|
|
65
|
+
token,
|
|
66
|
+
})
|
|
67
|
+
return token
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
cache.delete(filePath)
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function resolveToken(
|
|
77
|
+
src: McpTokenSource | undefined,
|
|
78
|
+
readTokenFile: (filePath: string) => Promise<string | undefined>,
|
|
79
|
+
root: string,
|
|
80
|
+
): Promise<string | undefined> {
|
|
81
|
+
if (src === undefined)
|
|
82
|
+
return undefined
|
|
83
|
+
if (typeof src === 'function') {
|
|
84
|
+
const val = (await src())?.trim()
|
|
85
|
+
return val && val.length > 0 ? val : undefined
|
|
86
|
+
}
|
|
87
|
+
if (typeof src === 'string') {
|
|
88
|
+
const val = src.trim()
|
|
89
|
+
return val.length > 0 ? val : undefined
|
|
90
|
+
}
|
|
91
|
+
if ('env' in src) {
|
|
92
|
+
const val = process.env[src.env]?.trim()
|
|
93
|
+
return val && val.length > 0 ? val : undefined
|
|
94
|
+
}
|
|
95
|
+
if ('file' in src)
|
|
96
|
+
return readTokenFile(resolve(root, src.file))
|
|
97
|
+
return undefined
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function extractBearerToken(request: Request): string | undefined {
|
|
101
|
+
const header = request.headers.get('authorization')
|
|
102
|
+
if (header === null)
|
|
103
|
+
return undefined
|
|
104
|
+
const match = /^Bearer\s+(.+)$/i.exec(header.trim())
|
|
105
|
+
if (!match)
|
|
106
|
+
return undefined
|
|
107
|
+
const token = match[1]?.trim()
|
|
108
|
+
return token && token.length > 0 ? token : undefined
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function mcpTooManyRequests(retryAfter: number): Response {
|
|
112
|
+
return Response.json(
|
|
113
|
+
{ ok: false, status: 429, error: 'Too many requests' },
|
|
114
|
+
{ status: 429, headers: { 'retry-after': String(retryAfter) } },
|
|
115
|
+
)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function unauthorized(): Response {
|
|
119
|
+
return Response.json(
|
|
120
|
+
{ error: 'Unauthorized' },
|
|
121
|
+
{ status: 401, headers: { 'www-authenticate': 'Bearer' } },
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function createAuthorizer(
|
|
126
|
+
tokenSource: McpTokenSource | undefined,
|
|
127
|
+
authenticate: McpAuthenticator | undefined,
|
|
128
|
+
readTokenFile: (filePath: string) => Promise<string | undefined>,
|
|
129
|
+
root: string,
|
|
130
|
+
failedAuthLimit: RateLimit<RequestContext>,
|
|
131
|
+
failures: RateLimiter,
|
|
132
|
+
): (ctx: RequestContext) => Promise<Response | undefined> {
|
|
133
|
+
return async (ctx) => {
|
|
134
|
+
let configured: string | undefined
|
|
135
|
+
if (tokenSource !== undefined) {
|
|
136
|
+
configured = await resolveToken(tokenSource, readTokenFile, root)
|
|
137
|
+
if (configured === undefined || Buffer.byteLength(configured) < MIN_TOKEN_BYTES)
|
|
138
|
+
return new Response('Not Found', { status: 404 })
|
|
139
|
+
}
|
|
140
|
+
else if (authenticate === undefined) {
|
|
141
|
+
return new Response('Not Found', { status: 404 })
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const key = rateLimitKey(failedAuthLimit, ctx)
|
|
145
|
+
const retryAfter = await failures.peek(key)
|
|
146
|
+
if (retryAfter > 0)
|
|
147
|
+
return mcpTooManyRequests(retryAfter)
|
|
148
|
+
|
|
149
|
+
const provided = extractBearerToken(ctx.request)
|
|
150
|
+
if (provided === undefined) {
|
|
151
|
+
await failures.hit(key)
|
|
152
|
+
return unauthorized()
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (configured !== undefined && !safeEqual(provided, configured)) {
|
|
156
|
+
await failures.hit(key)
|
|
157
|
+
return unauthorized()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (authenticate !== undefined) {
|
|
161
|
+
let allowed: unknown
|
|
162
|
+
try {
|
|
163
|
+
allowed = await authenticate(provided, ctx)
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
await failures.hit(key)
|
|
167
|
+
return unauthorized()
|
|
168
|
+
}
|
|
169
|
+
if (!allowed) {
|
|
170
|
+
await failures.hit(key)
|
|
171
|
+
return unauthorized()
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return undefined
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// Consumes `count` hits in one SQL statement (SQLite) or one locked transaction (Postgres), avoiding N sequential round-trips per JSON-RPC batch.
|
|
180
|
+
async function hitSharedBatch(
|
|
181
|
+
shared: SharedStore,
|
|
182
|
+
scope: string,
|
|
183
|
+
key: string,
|
|
184
|
+
count: number,
|
|
185
|
+
max: number,
|
|
186
|
+
windowMs: number,
|
|
187
|
+
): Promise<number> {
|
|
188
|
+
if (count > max)
|
|
189
|
+
return Math.max(1, Math.ceil(windowMs / 1000))
|
|
190
|
+
const now = Date.now()
|
|
191
|
+
const expires = now + windowMs
|
|
192
|
+
const cutoff = now - windowMs
|
|
193
|
+
const insertBatch = async (tx: SharedStore['sql']): Promise<number> => {
|
|
194
|
+
const inserted = await tx`with recursive seq(n) as (select 1 union all select n + 1 from seq where n < ${count}) insert into prunelle_rate_hits (scope, key, at, expires) select ${scope}, ${key}, ${now}, ${expires} from seq where (select count(*) from prunelle_rate_hits where scope = ${scope} and key = ${key} and at > ${cutoff}) + ${count} <= ${max}`
|
|
195
|
+
return inserted.count
|
|
196
|
+
}
|
|
197
|
+
const insertedCount = shared.kind === 'sqlite'
|
|
198
|
+
? await insertBatch(shared.sql)
|
|
199
|
+
: await shared.sql.begin(async (tx) => {
|
|
200
|
+
await tx`select pg_advisory_xact_lock(hashtext(${`${scope}\n${key}`}))`
|
|
201
|
+
return insertBatch(tx)
|
|
202
|
+
})
|
|
203
|
+
if (insertedCount > 0)
|
|
204
|
+
return 0
|
|
205
|
+
const keep = max - count
|
|
206
|
+
const rows: { at: number | string }[] = await shared.sql`select at from prunelle_rate_hits where scope = ${scope} and key = ${key} and at > ${cutoff} order by at desc limit ${keep + 1}`
|
|
207
|
+
if (rows.length <= keep)
|
|
208
|
+
return 1
|
|
209
|
+
return Math.max(1, Math.ceil((Number(rows[keep]!.at) + windowMs - now) / 1000))
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function createPostTokenConsumer(
|
|
213
|
+
serverRateLimit: RateLimit<RequestContext> | undefined,
|
|
214
|
+
postLimiter: RateLimiter | undefined,
|
|
215
|
+
sharedStore: SharedStore | undefined,
|
|
216
|
+
): ((ctx: RequestContext, count: number) => Promise<Response | undefined>) | undefined {
|
|
217
|
+
if (postLimiter === undefined || serverRateLimit === undefined)
|
|
218
|
+
return undefined
|
|
219
|
+
return async (ctx: RequestContext, count: number): Promise<Response | undefined> => {
|
|
220
|
+
if (count <= 0)
|
|
221
|
+
return undefined
|
|
222
|
+
const key = rateLimitKey(serverRateLimit, ctx)
|
|
223
|
+
if (count === 1) {
|
|
224
|
+
const retryAfter = await postLimiter.hit(key)
|
|
225
|
+
return retryAfter > 0 ? mcpTooManyRequests(retryAfter) : undefined
|
|
226
|
+
}
|
|
227
|
+
if (sharedStore !== undefined) {
|
|
228
|
+
const retryAfter = await hitSharedBatch(sharedStore, MCP_POST_SCOPE, key, count, serverRateLimit.max, serverRateLimit.windowMs)
|
|
229
|
+
return retryAfter > 0 ? mcpTooManyRequests(retryAfter) : undefined
|
|
230
|
+
}
|
|
231
|
+
if (count > serverRateLimit.max)
|
|
232
|
+
return mcpTooManyRequests(Math.max(1, Math.ceil(serverRateLimit.windowMs / 1000)))
|
|
233
|
+
for (let i = 0; i < count; i++) {
|
|
234
|
+
const retryAfter = await postLimiter.hit(key)
|
|
235
|
+
if (retryAfter > 0)
|
|
236
|
+
return mcpTooManyRequests(retryAfter)
|
|
237
|
+
}
|
|
238
|
+
return undefined
|
|
239
|
+
}
|
|
240
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -119,7 +119,7 @@ function escapeTsvCell(value: unknown): string {
|
|
|
119
119
|
}
|
|
120
120
|
|
|
121
121
|
/** Renders tabular records as compact TSV (typically 50–65% fewer tokens than JSON object arrays). */
|
|
122
|
-
export function formatTable<T extends
|
|
122
|
+
export function formatTable<T extends object>(
|
|
123
123
|
rows: readonly T[],
|
|
124
124
|
columns?: readonly (keyof T & string)[],
|
|
125
125
|
options?: CompactListOptions,
|
|
@@ -134,7 +134,7 @@ export function formatTable<T extends Record<string, unknown>>(
|
|
|
134
134
|
|
|
135
135
|
const lines: string[] = [cols.join('\t')]
|
|
136
136
|
for (const row of rows)
|
|
137
|
-
lines.push(cols.map(col => escapeTsvCell(row[col])).join('\t'))
|
|
137
|
+
lines.push(cols.map(col => escapeTsvCell((row as Record<string, unknown>)[col])).join('\t'))
|
|
138
138
|
return lines.join('\n') + formatListFooter(rows.length, options)
|
|
139
139
|
}
|
|
140
140
|
|
|
@@ -182,6 +182,16 @@ export function formatFieldErrors(fieldErrors: unknown): string {
|
|
|
182
182
|
.join('; ')
|
|
183
183
|
}
|
|
184
184
|
|
|
185
|
+
// A body that is not valid JSON is passed on as the text it is; JSON has no `undefined`, so that value can only mean the parse failed.
|
|
186
|
+
function parseJsonOrUndefined(text: string): unknown {
|
|
187
|
+
try {
|
|
188
|
+
return JSON.parse(text) as unknown
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
return undefined
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
185
195
|
export async function formatResponseResult(res: Response, pruneMode: McpPruneMode): Promise<McpToolResult> {
|
|
186
196
|
// 3xx redirects from reused Prunelle form actions indicate a completed mutation, not a failure.
|
|
187
197
|
if (res.status >= 300 && res.status < 400) {
|
|
@@ -192,23 +202,18 @@ export async function formatResponseResult(res: Response, pruneMode: McpPruneMod
|
|
|
192
202
|
const rawText = await res.text()
|
|
193
203
|
if (!res.ok) {
|
|
194
204
|
let errorMsg = rawText || `${res.status} ${res.statusText}`.trim()
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
errorMsg = fields
|
|
208
|
-
}
|
|
209
|
-
catch {
|
|
210
|
-
// Keep rawText
|
|
211
|
-
}
|
|
205
|
+
const parsed = rawText.trimStart().startsWith('{') ? parseJsonOrUndefined(rawText) as { error?: unknown, message?: unknown, fieldErrors?: unknown } | undefined : undefined
|
|
206
|
+
if (parsed !== undefined) {
|
|
207
|
+
const base = typeof parsed.error === 'string' && parsed.error.length > 0
|
|
208
|
+
? parsed.error
|
|
209
|
+
: (typeof parsed.message === 'string' && parsed.message.length > 0 ? parsed.message : '')
|
|
210
|
+
const fields = formatFieldErrors(parsed.fieldErrors)
|
|
211
|
+
if (base && fields)
|
|
212
|
+
errorMsg = `${base} (${fields})`
|
|
213
|
+
else if (base)
|
|
214
|
+
errorMsg = base
|
|
215
|
+
else if (fields)
|
|
216
|
+
errorMsg = fields
|
|
212
217
|
}
|
|
213
218
|
return { content: [{ type: 'text', text: errorMsg }], isError: true }
|
|
214
219
|
}
|
|
@@ -218,13 +223,9 @@ export async function formatResponseResult(res: Response, pruneMode: McpPruneMod
|
|
|
218
223
|
|
|
219
224
|
const contentType = res.headers.get('content-type') ?? ''
|
|
220
225
|
if (contentType.includes('json')) {
|
|
221
|
-
|
|
222
|
-
|
|
226
|
+
const parsed = parseJsonOrUndefined(rawText)
|
|
227
|
+
if (parsed !== undefined)
|
|
223
228
|
return { content: [{ type: 'text', text: JSON.stringify(applyPrune(parsed, pruneMode)) }] }
|
|
224
|
-
}
|
|
225
|
-
catch {
|
|
226
|
-
// Keep rawText when body is not valid JSON
|
|
227
|
-
}
|
|
228
229
|
}
|
|
229
230
|
return { content: [{ type: 'text', text: rawText }] }
|
|
230
231
|
}
|
package/src/index.ts
CHANGED
|
@@ -3,20 +3,22 @@
|
|
|
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,
|
|
6
|
+
import type { ActionContext, InferOutput, RateLimit, RequestContext, ServerAction, StandardSchemaV1 } from 'prunelle/server'
|
|
7
|
+
import type { McpAuthenticator, McpTokenSource } from './auth'
|
|
7
8
|
import type { McpBudgetOptions, McpFootprint } from './footprint'
|
|
8
9
|
import type { McpPruneMode, McpToolResult } from './format'
|
|
9
10
|
import type { ListedTool, McpToolAnnotations, ResolvedResource, ResolvedToolEntry } from './rpc'
|
|
10
11
|
import type { CompactSchemaOptions, JsonSchemaObject } from './schema'
|
|
11
12
|
|
|
12
|
-
import { readFile, stat } from 'node:fs/promises'
|
|
13
13
|
import { definePlugin } from 'prunelle/config'
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
14
|
+
import { isTrustedOrigin, nodeEnv, SHARED_STORE } from 'prunelle/server'
|
|
15
|
+
import { createAuthorizer, createPostTokenConsumer, createTokenFileReader, FAILED_AUTH_MAX, FAILED_AUTH_WINDOW_MS, MIN_TOKEN_BYTES, resolveToken } from './auth'
|
|
16
16
|
import { collectBudgetViolations, computeFootprint, formatMcpFootprint } from './footprint'
|
|
17
17
|
import { createRpcDispatcher } from './rpc'
|
|
18
18
|
import { isPlainRecord, isStandardSchema, normalizeObjectSchema, schemaToJsonSchema } from './schema'
|
|
19
19
|
|
|
20
|
+
export type { McpAuthenticator, McpTokenSource } from './auth'
|
|
21
|
+
|
|
20
22
|
export { formatMcpFootprint } from './footprint'
|
|
21
23
|
export type { McpBudgetOptions, McpFootprint, McpToolFootprint } from './footprint'
|
|
22
24
|
export { formatLines, formatTable, pruneEmpty, truncateOutput } from './format'
|
|
@@ -144,12 +146,6 @@ export function mcpTool(tool: McpTool): McpTool {
|
|
|
144
146
|
return tool
|
|
145
147
|
}
|
|
146
148
|
|
|
147
|
-
export type McpTokenSource =
|
|
148
|
-
| string
|
|
149
|
-
| { env: string }
|
|
150
|
-
| { file: string }
|
|
151
|
-
| (() => string | undefined | Promise<string | undefined>)
|
|
152
|
-
|
|
153
149
|
export interface McpOptions {
|
|
154
150
|
/** Server name reported in `initialize` `serverInfo.name` (default: 'prunelle-mcp'). */
|
|
155
151
|
name?: string | undefined
|
|
@@ -159,8 +155,10 @@ export interface McpOptions {
|
|
|
159
155
|
instructions?: string | undefined
|
|
160
156
|
/** HTTP endpoint path (default: '/mcp/tools'). */
|
|
161
157
|
path?: string | undefined
|
|
162
|
-
/** Bearer token source: inline string, `{ env }`, `{ file }
|
|
158
|
+
/** Bearer token source: inline string, `{ env }`, `{ file }` (relative paths resolve against the app root), or resolver function. */
|
|
163
159
|
token?: McpTokenSource | undefined
|
|
160
|
+
/** Custom bearer-token authenticator: validates the bearer token, populates `ctx.locals` (e.g. `ctx.locals.user`), and returns a truthy value to allow or falsy (`false`/`null`/`undefined`) to reject with `401`. When set alongside `token`, both must pass. */
|
|
161
|
+
authenticate?: McpAuthenticator | undefined
|
|
164
162
|
/** Map of MCP tool names to Prunelle `action()` or handler definitions. */
|
|
165
163
|
tools: Record<string, McpTool>
|
|
166
164
|
/** Optional on-demand MCP resources exposed via `resources/list` and `resources/read`. */
|
|
@@ -169,7 +167,7 @@ export interface McpOptions {
|
|
|
169
167
|
schemas?: Record<string, StandardSchemaV1 | JsonSchemaObject> | undefined
|
|
170
168
|
/** Optional domain-error formatter for thrown errors (defaults to `err.message`). */
|
|
171
169
|
mapError?: ((error: unknown) => string | { message: string } | undefined) | undefined
|
|
172
|
-
/** Strip JSON Schema boilerplate, form-coercion unions, `x-*` keys
|
|
170
|
+
/** Strip JSON Schema boilerplate, form-coercion unions, and `x-*` keys in `tools/list` (default: true; pass `{ foldHomogeneousObjects: true }` to also fold homogeneous records). */
|
|
173
171
|
compactSchemas?: boolean | CompactSchemaOptions | undefined
|
|
174
172
|
/** Strip `null`/`undefined` (`'nullish'`) or also empty `[]`/`{}` (`true`) from JSON tool outputs (default: false). */
|
|
175
173
|
pruneEmpty?: McpPruneMode | undefined
|
|
@@ -353,123 +351,6 @@ export function inspectMcpFootprint(
|
|
|
353
351
|
return computeFootprint(options.instructions, listedTools)
|
|
354
352
|
}
|
|
355
353
|
|
|
356
|
-
interface CachedTokenFile {
|
|
357
|
-
mtimeNs: bigint
|
|
358
|
-
ctimeNs: bigint
|
|
359
|
-
size: bigint
|
|
360
|
-
ino: bigint
|
|
361
|
-
token: string | undefined
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
function createTokenFileReader(): (filePath: string) => Promise<string | undefined> {
|
|
365
|
-
const cache = new Map<string, CachedTokenFile>()
|
|
366
|
-
|
|
367
|
-
return async (filePath: string): Promise<string | undefined> => {
|
|
368
|
-
try {
|
|
369
|
-
const info = await stat(filePath, { bigint: true })
|
|
370
|
-
const prev = cache.get(filePath)
|
|
371
|
-
if (
|
|
372
|
-
prev !== undefined
|
|
373
|
-
&& prev.mtimeNs === info.mtimeNs
|
|
374
|
-
&& prev.ctimeNs === info.ctimeNs
|
|
375
|
-
&& prev.size === info.size
|
|
376
|
-
&& prev.ino === info.ino
|
|
377
|
-
) {
|
|
378
|
-
return prev.token
|
|
379
|
-
}
|
|
380
|
-
const raw = (await readFile(filePath, 'utf8')).trim()
|
|
381
|
-
const token = raw.length > 0 ? raw : undefined
|
|
382
|
-
cache.set(filePath, {
|
|
383
|
-
mtimeNs: info.mtimeNs,
|
|
384
|
-
ctimeNs: info.ctimeNs,
|
|
385
|
-
size: info.size,
|
|
386
|
-
ino: info.ino,
|
|
387
|
-
token,
|
|
388
|
-
})
|
|
389
|
-
return token
|
|
390
|
-
}
|
|
391
|
-
catch {
|
|
392
|
-
cache.delete(filePath)
|
|
393
|
-
return undefined
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
async function resolveToken(
|
|
399
|
-
src: McpTokenSource | undefined,
|
|
400
|
-
readTokenFile: (filePath: string) => Promise<string | undefined>,
|
|
401
|
-
): Promise<string | undefined> {
|
|
402
|
-
if (src === undefined)
|
|
403
|
-
return undefined
|
|
404
|
-
if (typeof src === 'function') {
|
|
405
|
-
const val = (await src())?.trim()
|
|
406
|
-
return val && val.length > 0 ? val : undefined
|
|
407
|
-
}
|
|
408
|
-
if (typeof src === 'string') {
|
|
409
|
-
const val = src.trim()
|
|
410
|
-
return val.length > 0 ? val : undefined
|
|
411
|
-
}
|
|
412
|
-
if ('env' in src) {
|
|
413
|
-
const val = process.env[src.env]?.trim()
|
|
414
|
-
return val && val.length > 0 ? val : undefined
|
|
415
|
-
}
|
|
416
|
-
if ('file' in src)
|
|
417
|
-
return readTokenFile(src.file)
|
|
418
|
-
return undefined
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
function extractBearerToken(request: Request): string | undefined {
|
|
423
|
-
const header = request.headers.get('authorization')
|
|
424
|
-
if (header === null)
|
|
425
|
-
return undefined
|
|
426
|
-
const match = /^Bearer\s+(.+)$/i.exec(header.trim())
|
|
427
|
-
if (!match)
|
|
428
|
-
return undefined
|
|
429
|
-
const token = match[1]?.trim()
|
|
430
|
-
return token && token.length > 0 ? token : undefined
|
|
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
|
-
|
|
473
354
|
export function mcp<T extends Record<string, unknown>>(
|
|
474
355
|
options: Omit<McpOptions, 'tools'> & { tools: McpToolsRecord<T> },
|
|
475
356
|
): PrunellePlugin
|
|
@@ -497,8 +378,13 @@ export function mcp(options: McpOptions): PrunellePlugin {
|
|
|
497
378
|
return definePlugin({
|
|
498
379
|
name: '@prunellejs/mcp',
|
|
499
380
|
|
|
500
|
-
async requires() {
|
|
501
|
-
|
|
381
|
+
async requires(ctx) {
|
|
382
|
+
if (options.token === undefined) {
|
|
383
|
+
return options.authenticate !== undefined
|
|
384
|
+
? []
|
|
385
|
+
: ['no `token`, so the endpoint answers 404 to every call: pass `token: { env: \'MCP_TOKEN\' }` and set `MCP_TOKEN`, or `token: { file }`.']
|
|
386
|
+
}
|
|
387
|
+
const configured = await resolveToken(options.token, readTokenFile, ctx.root)
|
|
502
388
|
if (configured === undefined)
|
|
503
389
|
return ['no `token`, so the endpoint answers 404 to every call: pass `token: { env: \'MCP_TOKEN\' }` and set `MCP_TOKEN`, or `token: { file }`.']
|
|
504
390
|
return Buffer.byteLength(configured) < MIN_TOKEN_BYTES
|
|
@@ -523,8 +409,8 @@ export function mcp(options: McpOptions): PrunellePlugin {
|
|
|
523
409
|
}
|
|
524
410
|
|
|
525
411
|
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)
|
|
412
|
+
const failures = api.rateLimiter(failedAuthLimit, 'failed-auth')
|
|
413
|
+
const authorize = createAuthorizer(options.token, options.authenticate, readTokenFile, api.root, failedAuthLimit, failures)
|
|
528
414
|
const rpc = createRpcDispatcher({
|
|
529
415
|
serverName,
|
|
530
416
|
serverVersion,
|
|
@@ -535,25 +421,15 @@ export function mcp(options: McpOptions): PrunellePlugin {
|
|
|
535
421
|
listedResources,
|
|
536
422
|
formatResult: options.formatResult,
|
|
537
423
|
mapError: options.mapError,
|
|
538
|
-
limiterFor: limit => api.rateLimiter(limit),
|
|
424
|
+
limiterFor: (limit, name) => api.rateLimiter(limit, name),
|
|
539
425
|
})
|
|
540
426
|
|
|
541
427
|
const serverRateLimit = rateLimit !== undefined ? { ...rateLimit } : undefined
|
|
542
|
-
const postLimiter = serverRateLimit !== undefined ? api.rateLimiter(serverRateLimit) : undefined
|
|
543
|
-
const consumePostTokens =
|
|
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
|
|
428
|
+
const postLimiter = serverRateLimit !== undefined ? api.rateLimiter(serverRateLimit, 'post') : undefined
|
|
429
|
+
const consumePostTokens = createPostTokenConsumer(serverRateLimit, postLimiter, api.inject(SHARED_STORE))
|
|
554
430
|
|
|
555
431
|
api.route('POST', endpoint, async (ctx) => {
|
|
556
|
-
const limited = consumePostTokens?.(ctx, 1)
|
|
432
|
+
const limited = await consumePostTokens?.(ctx, 1)
|
|
557
433
|
if (limited !== undefined)
|
|
558
434
|
return limited
|
|
559
435
|
const originDenied = checkOrigin(ctx)
|
package/src/rpc.ts
CHANGED
|
@@ -70,7 +70,7 @@ export interface RpcDispatcherConfig {
|
|
|
70
70
|
formatResult?: ((output: unknown, toolName: string, input: unknown) => unknown) | undefined
|
|
71
71
|
mapError?: ((error: unknown) => string | { message: string } | undefined) | undefined
|
|
72
72
|
/** A limiter counting under `limit`, or undefined before the server runs; one per action is kept. */
|
|
73
|
-
limiterFor?: ((limit: RateLimit<ActionContext
|
|
73
|
+
limiterFor?: ((limit: RateLimit<ActionContext>, name: string) => RateLimiter | undefined) | undefined
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
function shouldExposeErrors(dev: boolean): boolean {
|
|
@@ -133,7 +133,7 @@ async function handleResourceRead(
|
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
135
|
|
|
136
|
-
export type BatchRateLimitCheck = (ctx: RequestContext, extraCalls: number) => Response | undefined
|
|
136
|
+
export type BatchRateLimitCheck = (ctx: RequestContext, extraCalls: number) => Promise<Response | undefined>
|
|
137
137
|
|
|
138
138
|
function budgetSpent(item: unknown): JsonRpcResponse | null {
|
|
139
139
|
const id = typeof item === 'object' && item !== null ? (item as Partial<JsonRpcRequest>).id : undefined
|
|
@@ -154,14 +154,14 @@ async function runBatch(payload: readonly unknown[], handle: (item: unknown) =>
|
|
|
154
154
|
}
|
|
155
155
|
|
|
156
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 {
|
|
157
|
+
function createActionGuard(limiterFor: RpcDispatcherConfig['limiterFor']): (act: ServerAction<unknown, unknown>, ctx: RequestContext) => Promise<number> {
|
|
158
158
|
const limiters = new WeakMap<object, RateLimiter>()
|
|
159
|
-
return (act, ctx) => {
|
|
159
|
+
return async (act, ctx) => {
|
|
160
160
|
if (act.rateLimit === undefined)
|
|
161
161
|
return 0
|
|
162
162
|
let limiter = limiters.get(act)
|
|
163
163
|
if (limiter === undefined) {
|
|
164
|
-
limiter = limiterFor?.(act.rateLimit)
|
|
164
|
+
limiter = limiterFor?.(act.rateLimit, `action:${act.url}`)
|
|
165
165
|
if (limiter === undefined)
|
|
166
166
|
return 0
|
|
167
167
|
limiters.set(act, limiter)
|
|
@@ -179,6 +179,94 @@ async function shapeResult(cfg: RpcDispatcherConfig, tool: ResolvedToolEntry, na
|
|
|
179
179
|
return finalizeToolValue(formatted, tool.pruneEmpty)
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
+
type ActionRetryAfter = ReturnType<typeof createActionGuard>
|
|
183
|
+
|
|
184
|
+
// Runs one tool, through its action (rate limit, validation, `ok: false` as a tool error) or its handler; a throw becomes an `isError` result, and `mapError` or the dev flag decide how much of it shows.
|
|
185
|
+
async function runTool(cfg: RpcDispatcherConfig, actionRetryAfter: ActionRetryAfter, tool: ResolvedToolEntry, name: string, input: unknown, ctx: RequestContext, dev: boolean): Promise<McpToolResult> {
|
|
186
|
+
try {
|
|
187
|
+
let rawResult: unknown
|
|
188
|
+
if (tool.action !== undefined) {
|
|
189
|
+
const retryAfter = await actionRetryAfter(tool.action, ctx)
|
|
190
|
+
if (retryAfter > 0) {
|
|
191
|
+
return {
|
|
192
|
+
content: [{ type: 'text', text: `Too many requests to ${name}: retry after ${retryAfter} s` }],
|
|
193
|
+
isError: true,
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const invoked = await tool.action(input)
|
|
197
|
+
if (!invoked.ok) {
|
|
198
|
+
return applyOutputBudget({
|
|
199
|
+
content: [{ type: 'text', text: formatActionFailure(invoked) }],
|
|
200
|
+
isError: true,
|
|
201
|
+
}, tool.maxOutputChars)
|
|
202
|
+
}
|
|
203
|
+
rawResult = invoked.data
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
rawResult = await tool.handler(input, ctx)
|
|
207
|
+
}
|
|
208
|
+
return applyOutputBudget(await shapeResult(cfg, tool, name, rawResult, input), tool.maxOutputChars)
|
|
209
|
+
}
|
|
210
|
+
catch (err) {
|
|
211
|
+
const message = formatCaughtError(err, cfg.mapError, shouldExposeErrors(dev))
|
|
212
|
+
return applyOutputBudget({
|
|
213
|
+
content: [{ type: 'text', text: message }],
|
|
214
|
+
isError: true,
|
|
215
|
+
}, tool.maxOutputChars)
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function initializeResult(cfg: RpcDispatcherConfig): Record<string, unknown> {
|
|
220
|
+
return {
|
|
221
|
+
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
222
|
+
capabilities: {
|
|
223
|
+
tools: { listChanged: false },
|
|
224
|
+
...(cfg.resourceMap.size > 0 ? { resources: { subscribe: false, listChanged: false } } : {}),
|
|
225
|
+
},
|
|
226
|
+
serverInfo: { name: cfg.serverName, version: cfg.serverVersion },
|
|
227
|
+
...(cfg.instructions !== undefined ? { instructions: cfg.instructions } : {}),
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function handleToolsCall(
|
|
232
|
+
callTool: (name: string, args: unknown, ctx: RequestContext, dev: boolean) => Promise<McpToolResult>,
|
|
233
|
+
id: string | number | null,
|
|
234
|
+
params: Record<string, unknown> | undefined,
|
|
235
|
+
ctx: RequestContext,
|
|
236
|
+
dev: boolean,
|
|
237
|
+
): Promise<JsonRpcResponse> {
|
|
238
|
+
const toolName = typeof params?.name === 'string' ? params.name : undefined
|
|
239
|
+
if (toolName === undefined)
|
|
240
|
+
return { jsonrpc: '2.0', id, error: { code: -32602, message: 'Missing tool name' } }
|
|
241
|
+
try {
|
|
242
|
+
const toolResult = await callTool(toolName, params?.arguments, ctx, dev)
|
|
243
|
+
return { jsonrpc: '2.0', id, result: toolResult }
|
|
244
|
+
}
|
|
245
|
+
catch (err) {
|
|
246
|
+
const rpcCode = (err as { rpcCode?: number }).rpcCode ?? -32603
|
|
247
|
+
const expose = rpcCode !== -32603 || shouldExposeErrors(dev)
|
|
248
|
+
const message = expose ? (err instanceof Error ? err.message : String(err)) : 'Internal error'
|
|
249
|
+
return { jsonrpc: '2.0', id, error: { code: rpcCode, message } }
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// The 400 answer for an empty batch or one past `MAX_BATCH_SIZE`, `undefined` for a batch that may run.
|
|
254
|
+
function refuseBatch(payload: readonly unknown[]): Response | undefined {
|
|
255
|
+
if (payload.length > 0 && payload.length <= MAX_BATCH_SIZE)
|
|
256
|
+
return undefined
|
|
257
|
+
return Response.json(
|
|
258
|
+
{
|
|
259
|
+
jsonrpc: '2.0',
|
|
260
|
+
id: null,
|
|
261
|
+
error: {
|
|
262
|
+
code: -32600,
|
|
263
|
+
message: payload.length === 0 ? 'Invalid Request' : `Batch size exceeds limit (${MAX_BATCH_SIZE})`,
|
|
264
|
+
},
|
|
265
|
+
},
|
|
266
|
+
{ status: 400 },
|
|
267
|
+
)
|
|
268
|
+
}
|
|
269
|
+
|
|
182
270
|
export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
|
|
183
271
|
const hasResources = cfg.resourceMap.size > 0
|
|
184
272
|
const availableNamesHint = cfg.toolMap.size > 0 && cfg.toolMap.size <= 12
|
|
@@ -207,37 +295,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
|
|
|
207
295
|
input = checked.value
|
|
208
296
|
}
|
|
209
297
|
|
|
210
|
-
|
|
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
|
-
}
|
|
298
|
+
return runTool(cfg, actionRetryAfter, tool, name, input, ctx, dev)
|
|
241
299
|
}
|
|
242
300
|
|
|
243
301
|
async function handleMessage(msg: unknown, ctx: RequestContext, dev = false): Promise<JsonRpcResponse | null> {
|
|
@@ -257,19 +315,7 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
|
|
|
257
315
|
|
|
258
316
|
switch (req.method) {
|
|
259
317
|
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
|
-
}
|
|
318
|
+
return { jsonrpc: '2.0', id, result: initializeResult(cfg) }
|
|
273
319
|
|
|
274
320
|
case 'ping':
|
|
275
321
|
return { jsonrpc: '2.0', id, result: {} }
|
|
@@ -283,22 +329,8 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
|
|
|
283
329
|
},
|
|
284
330
|
}
|
|
285
331
|
|
|
286
|
-
case 'tools/call':
|
|
287
|
-
|
|
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
|
-
}
|
|
332
|
+
case 'tools/call':
|
|
333
|
+
return handleToolsCall(callTool, id, req.params, ctx, dev)
|
|
302
334
|
|
|
303
335
|
case 'resources/list': {
|
|
304
336
|
if (!hasResources)
|
|
@@ -335,21 +367,11 @@ export function createRpcDispatcher(cfg: RpcDispatcherConfig) {
|
|
|
335
367
|
}
|
|
336
368
|
|
|
337
369
|
if (Array.isArray(payload)) {
|
|
338
|
-
|
|
339
|
-
|
|
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
|
-
}
|
|
370
|
+
const refused = refuseBatch(payload)
|
|
371
|
+
if (refused !== undefined)
|
|
372
|
+
return refused
|
|
351
373
|
if (checkBatchRateLimit !== undefined && payload.length > 1) {
|
|
352
|
-
const limited = checkBatchRateLimit(ctx, payload.length - 1)
|
|
374
|
+
const limited = await checkBatchRateLimit(ctx, payload.length - 1)
|
|
353
375
|
if (limited !== undefined)
|
|
354
376
|
return limited
|
|
355
377
|
}
|
package/src/schema.ts
CHANGED
|
@@ -22,8 +22,8 @@ export interface CompactSchemaOptions {
|
|
|
22
22
|
stripExtensions?: boolean | undefined
|
|
23
23
|
/** Strip no-op bounds (`minLength: 0`, `minItems: 0`, `minProperties: 0`, `±MAX_SAFE_INTEGER`) and optional app-wide default caps (default: true). */
|
|
24
24
|
stripDefaultBounds?: boolean | { maxLength?: number | undefined, maxItems?: number | undefined } | undefined
|
|
25
|
-
/**
|
|
26
|
-
foldHomogeneousObjects?:
|
|
25
|
+
/** Opt-in: fold optional-only objects with >= N identical-schema properties into `additionalProperties` + a compact `Keys: ...` description (default: false; `true` uses 4). */
|
|
26
|
+
foldHomogeneousObjects?: boolean | number | undefined
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
interface StandardJsonSchemaCapable {
|
|
@@ -67,6 +67,10 @@ function resolveCompactConfig(opt: boolean | CompactSchemaOptions | undefined):
|
|
|
67
67
|
}
|
|
68
68
|
const cfg = opt === true || opt === undefined ? {} : opt
|
|
69
69
|
const bounds = cfg.stripDefaultBounds
|
|
70
|
+
const foldOpt = cfg.foldHomogeneousObjects
|
|
71
|
+
const foldHomogeneousMin: number | false = foldOpt === true
|
|
72
|
+
? DEFAULT_FOLD_HOMOGENEOUS_MIN
|
|
73
|
+
: (typeof foldOpt === 'number' ? foldOpt : false)
|
|
70
74
|
return {
|
|
71
75
|
enabled: true,
|
|
72
76
|
stripFormCoercion: cfg.stripFormCoercion ?? true,
|
|
@@ -74,7 +78,7 @@ function resolveCompactConfig(opt: boolean | CompactSchemaOptions | undefined):
|
|
|
74
78
|
stripDefaultBounds: bounds !== false,
|
|
75
79
|
defaultMaxLength: typeof bounds === 'object' ? bounds.maxLength : undefined,
|
|
76
80
|
defaultMaxItems: typeof bounds === 'object' ? bounds.maxItems : undefined,
|
|
77
|
-
foldHomogeneousMin
|
|
81
|
+
foldHomogeneousMin,
|
|
78
82
|
}
|
|
79
83
|
}
|
|
80
84
|
|
|
@@ -254,92 +258,102 @@ function pruneUnusedDefs(root: JsonSchemaObject): void {
|
|
|
254
258
|
}
|
|
255
259
|
}
|
|
256
260
|
|
|
261
|
+
// A key a compacted schema drops: boilerplate, vendor extensions, empty values and no-op bounds.
|
|
262
|
+
function isNoOpBound(key: string, value: unknown, cfg: ResolvedCompactConfig): boolean {
|
|
263
|
+
if (key === 'minLength' || key === 'minItems' || key === 'minProperties')
|
|
264
|
+
return value === 0
|
|
265
|
+
if (key === 'minimum')
|
|
266
|
+
return value === SAFE_INT_MIN
|
|
267
|
+
if (key === 'maximum')
|
|
268
|
+
return value === SAFE_INT_MAX
|
|
269
|
+
if (key === 'maxLength')
|
|
270
|
+
return cfg.defaultMaxLength !== undefined && value === cfg.defaultMaxLength
|
|
271
|
+
if (key === 'maxItems')
|
|
272
|
+
return cfg.defaultMaxItems !== undefined && value === cfg.defaultMaxItems
|
|
273
|
+
return false
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function isRedundantTitle(value: string, propName: string | undefined): boolean {
|
|
277
|
+
const trimmed = value.trim()
|
|
278
|
+
return trimmed.length === 0 || (propName !== undefined && trimmed.toLowerCase() === propName.toLowerCase())
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function isDroppedKey(key: string, value: unknown, cfg: ResolvedCompactConfig, propName: string | undefined): boolean {
|
|
282
|
+
if (value === undefined || STRIPPED_SCHEMA_KEYS.has(key))
|
|
283
|
+
return true
|
|
284
|
+
if (cfg.stripExtensions && key.startsWith('x-'))
|
|
285
|
+
return true
|
|
286
|
+
if (key === 'additionalProperties')
|
|
287
|
+
return value === true
|
|
288
|
+
if (key === 'required')
|
|
289
|
+
return Array.isArray(value) && value.length === 0
|
|
290
|
+
if (key === 'description')
|
|
291
|
+
return typeof value === 'string' && value.trim().length === 0
|
|
292
|
+
if (key === 'title' && typeof value === 'string')
|
|
293
|
+
return isRedundantTitle(value, propName)
|
|
294
|
+
return cfg.stripDefaultBounds && isNoOpBound(key, value, cfg)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function compactProperties(props: Record<string, unknown>, cfg: ResolvedCompactConfig): Record<string, unknown> {
|
|
298
|
+
const propsOut: Record<string, unknown> = {}
|
|
299
|
+
for (const [pKey, pVal] of Object.entries(props))
|
|
300
|
+
propsOut[pKey] = compactSchemaNode(pVal, cfg, pKey, false)
|
|
301
|
+
return propsOut
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// `anyOf` / `oneOf` lose their form-coercion string branches; a lone survivor is merged into the node, and what the dropped branches carried (default, description) is lifted onto it.
|
|
305
|
+
function collapseUnion(out: Record<string, unknown>, unionKey: 'anyOf' | 'oneOf'): void {
|
|
306
|
+
const rawVariants = out[unionKey]
|
|
307
|
+
if (!Array.isArray(rawVariants) || rawVariants.length < 2)
|
|
308
|
+
return
|
|
309
|
+
const { variants, liftedDefault, liftedDescription } = collapseCoercionVariants(rawVariants)
|
|
310
|
+
if (variants.length === rawVariants.length)
|
|
311
|
+
return
|
|
312
|
+
const single = variants.length === 1 && isPlainRecord(variants[0]) ? variants[0] : undefined
|
|
313
|
+
if (single === undefined && variants.length === 0)
|
|
314
|
+
return
|
|
315
|
+
if (single !== undefined) {
|
|
316
|
+
delete out[unionKey]
|
|
317
|
+
for (const [k, v] of Object.entries(single)) {
|
|
318
|
+
if (out[k] === undefined)
|
|
319
|
+
out[k] = v
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
else {
|
|
323
|
+
out[unionKey] = variants
|
|
324
|
+
}
|
|
325
|
+
if (liftedDefault !== undefined && out.default === undefined)
|
|
326
|
+
out.default = liftedDefault
|
|
327
|
+
if (liftedDescription !== undefined && out.description === undefined)
|
|
328
|
+
out.description = liftedDescription
|
|
329
|
+
}
|
|
330
|
+
|
|
257
331
|
function compactSchemaNode(node: unknown, cfg: ResolvedCompactConfig, propName?: string, isRoot = false): unknown {
|
|
258
332
|
if (Array.isArray(node))
|
|
259
333
|
return node.map(item => compactSchemaNode(item, cfg))
|
|
260
334
|
if (node === null || typeof node !== 'object')
|
|
261
335
|
return node
|
|
262
336
|
|
|
263
|
-
const src = node as Record<string, unknown>
|
|
264
337
|
const out: Record<string, unknown> = {}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
if (value === undefined || STRIPPED_SCHEMA_KEYS.has(key))
|
|
268
|
-
continue
|
|
269
|
-
if (cfg.stripExtensions && key.startsWith('x-'))
|
|
270
|
-
continue
|
|
271
|
-
if (key === 'additionalProperties' && value === true)
|
|
272
|
-
continue
|
|
273
|
-
if (key === 'required' && Array.isArray(value) && value.length === 0)
|
|
338
|
+
for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
|
|
339
|
+
if (isDroppedKey(key, value, cfg, propName))
|
|
274
340
|
continue
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const trimmed = value.trim()
|
|
279
|
-
if (trimmed.length === 0 || (propName !== undefined && trimmed.toLowerCase() === propName.toLowerCase()))
|
|
280
|
-
continue
|
|
281
|
-
}
|
|
282
|
-
if (cfg.stripDefaultBounds) {
|
|
283
|
-
if ((key === 'minLength' || key === 'minItems' || key === 'minProperties') && value === 0)
|
|
284
|
-
continue
|
|
285
|
-
if (key === 'minimum' && value === SAFE_INT_MIN)
|
|
286
|
-
continue
|
|
287
|
-
if (key === 'maximum' && value === SAFE_INT_MAX)
|
|
288
|
-
continue
|
|
289
|
-
if (key === 'maxLength' && cfg.defaultMaxLength !== undefined && value === cfg.defaultMaxLength)
|
|
290
|
-
continue
|
|
291
|
-
if (key === 'maxItems' && cfg.defaultMaxItems !== undefined && value === cfg.defaultMaxItems)
|
|
292
|
-
continue
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
if (key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
296
|
-
const propsOut: Record<string, unknown> = {}
|
|
297
|
-
for (const [pKey, pVal] of Object.entries(value as Record<string, unknown>))
|
|
298
|
-
propsOut[pKey] = compactSchemaNode(pVal, cfg, pKey, false)
|
|
299
|
-
out[key] = propsOut
|
|
300
|
-
continue
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
out[key] = compactSchemaNode(value, cfg)
|
|
341
|
+
out[key] = key === 'properties' && value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
342
|
+
? compactProperties(value as Record<string, unknown>, cfg)
|
|
343
|
+
: compactSchemaNode(value, cfg)
|
|
304
344
|
}
|
|
305
345
|
|
|
306
346
|
if (cfg.stripFormCoercion) {
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
if (!Array.isArray(rawVariants) || rawVariants.length < 2)
|
|
310
|
-
continue
|
|
311
|
-
const { variants, liftedDefault, liftedDescription } = collapseCoercionVariants(rawVariants)
|
|
312
|
-
if (variants.length === rawVariants.length)
|
|
313
|
-
continue
|
|
314
|
-
if (variants.length === 1 && isPlainRecord(variants[0])) {
|
|
315
|
-
delete out[unionKey]
|
|
316
|
-
const single = variants[0]
|
|
317
|
-
for (const [k, v] of Object.entries(single)) {
|
|
318
|
-
if (out[k] === undefined)
|
|
319
|
-
out[k] = v
|
|
320
|
-
}
|
|
321
|
-
if (liftedDefault !== undefined && out.default === undefined)
|
|
322
|
-
out.default = liftedDefault
|
|
323
|
-
if (liftedDescription !== undefined && out.description === undefined)
|
|
324
|
-
out.description = liftedDescription
|
|
325
|
-
}
|
|
326
|
-
else if (variants.length > 0) {
|
|
327
|
-
out[unionKey] = variants
|
|
328
|
-
if (liftedDefault !== undefined && out.default === undefined)
|
|
329
|
-
out.default = liftedDefault
|
|
330
|
-
if (liftedDescription !== undefined && out.description === undefined)
|
|
331
|
-
out.description = liftedDescription
|
|
332
|
-
}
|
|
333
|
-
}
|
|
347
|
+
collapseUnion(out, 'anyOf')
|
|
348
|
+
collapseUnion(out, 'oneOf')
|
|
334
349
|
}
|
|
335
|
-
|
|
336
350
|
if (!isRoot && cfg.foldHomogeneousMin !== false && cfg.foldHomogeneousMin > 0)
|
|
337
351
|
tryFoldHomogeneousObject(out, cfg.foldHomogeneousMin)
|
|
338
352
|
|
|
339
353
|
return out
|
|
340
354
|
}
|
|
341
355
|
|
|
342
|
-
/** Strips JSON Schema boilerplate, form-coercion unions, `x-*` extensions, no-op bounds
|
|
356
|
+
/** Strips JSON Schema boilerplate, form-coercion unions, `x-*` extensions, and no-op bounds (plus opt-in folding of homogeneous records). */
|
|
343
357
|
export function compactSchema(raw: Record<string, unknown>, options?: CompactSchemaOptions): JsonSchemaObject {
|
|
344
358
|
const cfg = resolveCompactConfig(options ?? true)
|
|
345
359
|
const compacted = compactSchemaNode(raw, cfg, undefined, true) as JsonSchemaObject
|
|
@@ -364,6 +378,17 @@ export function normalizeObjectSchema(raw: Record<string, unknown> | undefined,
|
|
|
364
378
|
return copy
|
|
365
379
|
}
|
|
366
380
|
|
|
381
|
+
// A library that cannot emit the schema (an unsupported draft target, a type with no JSON form) throws; the caller tries the next source.
|
|
382
|
+
function extractJsonSchema(produce: () => Record<string, unknown> | undefined): Record<string, unknown> | undefined {
|
|
383
|
+
try {
|
|
384
|
+
const out = produce()
|
|
385
|
+
return out && typeof out === 'object' ? out : undefined
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return undefined
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
367
392
|
/** Extracts an MCP-compatible JSON Schema object from a Standard Schema (Zod 4, Valibot, ArkType, etc.). */
|
|
368
393
|
export function schemaToJsonSchema(
|
|
369
394
|
schema: StandardSchemaV1 | undefined,
|
|
@@ -377,26 +402,16 @@ export function schemaToJsonSchema(
|
|
|
377
402
|
const stdJson = candidate['~standard']?.jsonSchema
|
|
378
403
|
if (stdJson && typeof stdJson.input === 'function') {
|
|
379
404
|
for (const target of ['draft-2020-12', 'draft-07']) {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
return normalizeObjectSchema(out, compact)
|
|
384
|
-
}
|
|
385
|
-
catch {
|
|
386
|
-
// Try next JSON Schema draft target
|
|
387
|
-
}
|
|
405
|
+
const out = extractJsonSchema(() => stdJson.input?.({ target }))
|
|
406
|
+
if (out !== undefined)
|
|
407
|
+
return normalizeObjectSchema(out, compact)
|
|
388
408
|
}
|
|
389
409
|
}
|
|
390
410
|
|
|
391
411
|
if (typeof candidate.toJSONSchema === 'function') {
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
return normalizeObjectSchema(out, compact)
|
|
396
|
-
}
|
|
397
|
-
catch {
|
|
398
|
-
// Fall through to default object schema
|
|
399
|
-
}
|
|
412
|
+
const out = extractJsonSchema(() => candidate.toJSONSchema?.())
|
|
413
|
+
if (out !== undefined)
|
|
414
|
+
return normalizeObjectSchema(out, compact)
|
|
400
415
|
}
|
|
401
416
|
|
|
402
417
|
if (candidate.jsonSchema && typeof candidate.jsonSchema === 'object')
|