@prunellejs/mcp 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,52 @@
1
+ # @prunellejs/mcp Reference
2
+
3
+ > Zero-dependency MCP Streamable HTTP (`2025-03-26`) plugin exposing typed Prunelle `action()` handlers and standalone handlers as bearer-authenticated AI agent tools and resources.
4
+
5
+ ## Imports
6
+
7
+ - `@prunellejs/mcp`: `mcp`, `mcpTool`, `inspectMcpFootprint`, `formatMcpFootprint`, `formatLines`, `formatTable`, `pruneEmpty`, `truncateOutput`, `compactSchema`, `schemaToJsonSchema`, `MCP_PROTOCOL_VERSION`, `MAX_BATCH_SIZE`; types `McpOptions`, `McpTool`, `McpActionTool`, `McpHandlerTool`, `McpToolsRecord`, `McpResource`, `McpTokenSource`, `McpToolAnnotations`, `McpBudgetOptions`, `McpFootprint`, `McpToolFootprint`, `McpContentBlock`, `McpToolResult`, `McpPruneMode`, `PruneEmptyOptions`, `CompactListOptions`, `CompactSchemaOptions`, `JsonSchemaObject`.
8
+
9
+ ## Plugin Setup (`mcp(options)`)
10
+
11
+ - `name` (`'prunelle-mcp'`), `version` (`'1.0.0'`), `instructions` (returned in `initialize`).
12
+ - `path`: HTTP endpoint (default `'/mcp/tools'`).
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 token returns `404`, and a production start refuses until it is set; missing/invalid `Authorization: Bearer <token>` returns `401`.
15
+ - `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
+ - 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
+ - `schemas`: shared schemas exposed on demand via auto-added `describe_schema` tool and `prunelle://schemas/<name>` resources.
18
+ - `resources`: `Record<uri, { name?, description?, mimeType?, read: string | ((ctx) => string | Promise<string>) }>`.
19
+ - 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
+
21
+ ## Mounted Routes & CLI
22
+
23
+ - `POST /mcp/tools` (`csrf: false`, JSON-RPC 2.0: `initialize`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `ping`), `GET /mcp/tools` (`405`), `DELETE /mcp/tools` (`204`, `csrf: false`).
24
+ - `prunelle mcp-footprint` prints per-tool byte/token table; `prunelle check` and dev startup report `budget` violations.
25
+ - Output helpers: `formatLines(items, render, { total?, nextCursor?, empty? })`, `formatTable(rows, columns?, opts?)`, `pruneEmpty(val, opts?)`, `truncateOutput(text, maxChars)`.
26
+
27
+ ## Snippet
28
+
29
+ ```ts
30
+ // prunelle.config.ts
31
+ import { defineConfig } from 'prunelle/config'
32
+ import { formatTable, mcp, mcpTool } from '@prunellejs/mcp'
33
+ import { createTodo, listTodos } from './src/actions/todos'
34
+
35
+ export default defineConfig({
36
+ plugins: [
37
+ mcp({
38
+ name: 'todos',
39
+ token: { env: 'MCP_TOKEN' },
40
+ tools: {
41
+ list_todos: mcpTool({
42
+ action: listTodos,
43
+ description: 'List open todos',
44
+ annotations: { readOnlyHint: true },
45
+ format: rows => formatTable(rows, ['id', 'title', 'done']),
46
+ }),
47
+ create_todo: mcpTool({ action: createTodo, description: 'Create a todo' }),
48
+ },
49
+ }),
50
+ ],
51
+ })
52
+ ```
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@prunellejs/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Zero-dependency MCP Streamable HTTP (2025-03-26) plugin exposing Prunelle server actions as AI agent tools",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "src",
10
+ "llms.txt"
11
+ ],
12
+ "exports": {
13
+ ".": "./src/index.ts"
14
+ },
15
+ "engines": {
16
+ "bun": ">=1.4.0"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/Kayno0o/prunelle",
21
+ "directory": "packages/plugin-mcp"
22
+ },
23
+ "peerDependencies": {
24
+ "prunelle": "^0.1.1"
25
+ }
26
+ }
@@ -0,0 +1,129 @@
1
+ // Up-front tools/list byte & token footprint measurement, budget enforcement, and CLI table formatting.
2
+
3
+ import type { JsonSchemaObject } from './schema'
4
+
5
+ export const DEFAULT_MAX_TOOL_BYTES = 2048
6
+
7
+ export interface McpBudgetOptions {
8
+ /** Per-tool byte budget in `tools/list` (default: 2048). */
9
+ maxToolBytes?: number | undefined
10
+ /** Total `instructions` + `tools/list` byte budget (optional). */
11
+ maxTotalBytes?: number | undefined
12
+ /** When true, `prunelle check` fails with `ctx.error()` on budget overruns instead of warning (default: false). */
13
+ strict?: boolean | undefined
14
+ /** Custom warning sink for dev startup (and alongside `ctx.warn()` in non-strict `prunelle check`). */
15
+ onWarn?: ((message: string) => void) | undefined
16
+ }
17
+
18
+ export interface McpToolFootprint {
19
+ name: string
20
+ chars: number
21
+ bytes: number
22
+ descriptionBytes: number
23
+ schemaBytes: number
24
+ estimatedTokens: number
25
+ }
26
+
27
+ export interface McpFootprint {
28
+ instructionsChars: number
29
+ instructionsBytes: number
30
+ toolsChars: number
31
+ toolsBytes: number
32
+ totalChars: number
33
+ totalBytes: number
34
+ estimatedTokens: number
35
+ tools: McpToolFootprint[]
36
+ }
37
+
38
+ export interface ListedToolShape {
39
+ name: string
40
+ description: string
41
+ inputSchema: JsonSchemaObject
42
+ }
43
+
44
+ function utf8Bytes(str: string): number {
45
+ return Buffer.byteLength(str, 'utf8')
46
+ }
47
+
48
+ export function computeFootprint(instructions: string | undefined, listedTools: readonly ListedToolShape[]): McpFootprint {
49
+ const instructionsText = instructions ?? ''
50
+ const instructionsChars = instructionsText.length
51
+ const instructionsBytes = utf8Bytes(instructionsText)
52
+ const tools: McpToolFootprint[] = []
53
+ let toolsChars = 0
54
+ let toolsBytes = 0
55
+
56
+ for (const listed of listedTools) {
57
+ const json = JSON.stringify(listed)
58
+ const chars = json.length
59
+ const bytes = utf8Bytes(json)
60
+ const descriptionBytes = utf8Bytes(listed.description)
61
+ const schemaBytes = utf8Bytes(JSON.stringify(listed.inputSchema))
62
+ toolsChars += chars
63
+ toolsBytes += bytes
64
+ tools.push({
65
+ name: listed.name,
66
+ chars,
67
+ bytes,
68
+ descriptionBytes,
69
+ schemaBytes,
70
+ estimatedTokens: Math.ceil(bytes / 4),
71
+ })
72
+ }
73
+
74
+ tools.sort((a, b) => b.bytes - a.bytes)
75
+ const totalChars = instructionsChars + toolsChars
76
+ const totalBytes = instructionsBytes + toolsBytes
77
+ return {
78
+ instructionsChars,
79
+ instructionsBytes,
80
+ toolsChars,
81
+ toolsBytes,
82
+ totalChars,
83
+ totalBytes,
84
+ estimatedTokens: Math.ceil(totalBytes / 4),
85
+ tools,
86
+ }
87
+ }
88
+
89
+ export function collectBudgetViolations(footprint: McpFootprint, budget: McpBudgetOptions | false | undefined): string[] {
90
+ if (budget === false)
91
+ return []
92
+ const maxToolBytes = budget?.maxToolBytes ?? DEFAULT_MAX_TOOL_BYTES
93
+ const maxTotalBytes = budget?.maxTotalBytes
94
+ const violations: string[] = []
95
+
96
+ if (maxToolBytes > 0) {
97
+ for (const tool of footprint.tools) {
98
+ if (tool.bytes > maxToolBytes) {
99
+ violations.push(
100
+ `[@prunellejs/mcp] tool "${tool.name}" is ${tool.bytes} B (~${tool.estimatedTokens} tok; desc ${tool.descriptionBytes} B, schema ${tool.schemaBytes} B), exceeding ${maxToolBytes} B budget`,
101
+ )
102
+ }
103
+ }
104
+ }
105
+ if (maxTotalBytes !== undefined && maxTotalBytes > 0 && footprint.totalBytes > maxTotalBytes) {
106
+ violations.push(
107
+ `[@prunellejs/mcp] total MCP surface is ${footprint.totalBytes} B (~${footprint.estimatedTokens} tok), exceeding ${maxTotalBytes} B budget`,
108
+ )
109
+ }
110
+ return violations
111
+ }
112
+
113
+ /** Formats an `McpFootprint` report as a compact table for CLI / CI output. */
114
+ export function formatMcpFootprint(footprint: McpFootprint, budget?: McpBudgetOptions | false): string {
115
+ const maxToolBytes = budget === false ? undefined : (budget?.maxToolBytes ?? DEFAULT_MAX_TOOL_BYTES)
116
+ const lines = [
117
+ `@prunellejs/mcp footprint: ${footprint.totalBytes} B (~${footprint.estimatedTokens} tok) — instructions: ${footprint.instructionsBytes} B, tools: ${footprint.toolsBytes} B (${footprint.tools.length} tools)`,
118
+ ]
119
+ const nameWidth = footprint.tools.reduce((max, t) => Math.max(max, t.name.length), 0)
120
+ for (const t of footprint.tools) {
121
+ const flag = maxToolBytes !== undefined && maxToolBytes > 0 && t.bytes > maxToolBytes
122
+ ? ` [OVER ${maxToolBytes} B]`
123
+ : ''
124
+ lines.push(
125
+ ` ${t.name.padEnd(nameWidth)} ${String(t.bytes).padStart(6)} B (~${t.estimatedTokens} tok) desc: ${t.descriptionBytes} B schema: ${t.schemaBytes} B${flag}`,
126
+ )
127
+ }
128
+ return lines.join('\n')
129
+ }
package/src/format.ts ADDED
@@ -0,0 +1,259 @@
1
+ // Output pruning, compact text/TSV formatting, truncation, and Response normalization for @prunellejs/mcp.
2
+
3
+ export interface McpContentBlock {
4
+ type: 'text'
5
+ text: string
6
+ }
7
+
8
+ export interface McpToolResult {
9
+ content: McpContentBlock[]
10
+ isError?: boolean | undefined
11
+ }
12
+
13
+ export type McpPruneMode = false | 'nullish' | true
14
+
15
+ export interface PruneEmptyOptions {
16
+ /** Also drop empty arrays `[]` and empty objects `{}` (default: true). */
17
+ emptyCollections?: boolean | undefined
18
+ /** Also drop empty strings `""` (default: false). */
19
+ emptyStrings?: boolean | undefined
20
+ }
21
+
22
+ export interface CompactListOptions {
23
+ /** Total available items when the returned slice is paginated. */
24
+ total?: number | undefined
25
+ /** Next cursor/offset hint shown in the footer when more items exist. */
26
+ nextCursor?: string | number | null | undefined
27
+ /** Fallback text when the list is empty (default: '(none)'). */
28
+ empty?: string | undefined
29
+ }
30
+
31
+ /** Recursively removes `null`/`undefined` (and by default empty `[]`/`{}`) to shrink JSON payloads. */
32
+ export function pruneEmpty(value: unknown, options?: PruneEmptyOptions): unknown {
33
+ const dropCollections = options?.emptyCollections ?? true
34
+ const dropStrings = options?.emptyStrings ?? false
35
+ const ancestors = new Set<object>()
36
+
37
+ function walk(node: unknown, isRoot: boolean): unknown {
38
+ if (node === null || node === undefined)
39
+ return isRoot ? node : undefined
40
+ if (typeof node === 'string')
41
+ return !isRoot && dropStrings && node.length === 0 ? undefined : node
42
+ if (Array.isArray(node)) {
43
+ if (ancestors.has(node))
44
+ return undefined
45
+ ancestors.add(node)
46
+ try {
47
+ const out: unknown[] = []
48
+ for (const item of node) {
49
+ const cleaned = walk(item, false)
50
+ if (cleaned !== undefined)
51
+ out.push(cleaned)
52
+ }
53
+ if (!isRoot && dropCollections && out.length === 0)
54
+ return undefined
55
+ return out
56
+ }
57
+ finally {
58
+ ancestors.delete(node)
59
+ }
60
+ }
61
+ if (typeof node === 'object') {
62
+ const proto = Object.getPrototypeOf(node)
63
+ if (proto !== Object.prototype && proto !== null)
64
+ return node
65
+ if (ancestors.has(node))
66
+ return undefined
67
+ ancestors.add(node)
68
+ try {
69
+ const out: Record<string, unknown> = {}
70
+ let count = 0
71
+ for (const [k, v] of Object.entries(node as Record<string, unknown>)) {
72
+ const cleaned = walk(v, false)
73
+ if (cleaned !== undefined) {
74
+ out[k] = cleaned
75
+ count++
76
+ }
77
+ }
78
+ if (!isRoot && dropCollections && count === 0)
79
+ return undefined
80
+ return out
81
+ }
82
+ finally {
83
+ ancestors.delete(node)
84
+ }
85
+ }
86
+ return node
87
+ }
88
+
89
+ return walk(value, true)
90
+ }
91
+
92
+ function formatListFooter(count: number, options?: CompactListOptions): string {
93
+ const parts: string[] = []
94
+ if (options?.total !== undefined && options.total > count)
95
+ parts.push(`${count}/${options.total}`)
96
+ if (options?.nextCursor !== undefined && options.nextCursor !== null && String(options.nextCursor).length > 0)
97
+ parts.push(`next=${options.nextCursor}`)
98
+ return parts.length > 0 ? `\n--- ${parts.join(', ')}` : ''
99
+ }
100
+
101
+ /** Renders items as compact one-line-per-entry text with an optional pagination footer. */
102
+ export function formatLines<T>(
103
+ items: readonly T[],
104
+ render: (item: T, index: number) => string,
105
+ options?: CompactListOptions,
106
+ ): string {
107
+ if (items.length === 0)
108
+ return options?.empty ?? '(none)'
109
+ return items.map(render).join('\n') + formatListFooter(items.length, options)
110
+ }
111
+
112
+ function escapeTsvCell(value: unknown): string {
113
+ if (value === null || value === undefined)
114
+ return ''
115
+ const raw = typeof value === 'string'
116
+ ? value
117
+ : (typeof value === 'object' ? JSON.stringify(value) : String(value))
118
+ return raw.replace(/[\t\r\n]+/g, ' ')
119
+ }
120
+
121
+ /** Renders tabular records as compact TSV (typically 50–65% fewer tokens than JSON object arrays). */
122
+ export function formatTable<T extends Record<string, unknown>>(
123
+ rows: readonly T[],
124
+ columns?: readonly (keyof T & string)[],
125
+ options?: CompactListOptions,
126
+ ): string {
127
+ if (rows.length === 0)
128
+ return options?.empty ?? '(none)'
129
+ const cols: readonly string[] = columns && columns.length > 0
130
+ ? columns
131
+ : Object.keys(rows[0] ?? {})
132
+ if (cols.length === 0)
133
+ return options?.empty ?? '(none)'
134
+
135
+ const lines: string[] = [cols.join('\t')]
136
+ for (const row of rows)
137
+ lines.push(cols.map(col => escapeTsvCell(row[col])).join('\t'))
138
+ return lines.join('\n') + formatListFooter(rows.length, options)
139
+ }
140
+
141
+ /** Truncates oversized text outputs cleanly while leaving an actionable recovery hint. */
142
+ export function truncateOutput(text: string, maxChars: number): string {
143
+ if (maxChars <= 0 || text.length <= maxChars)
144
+ return text
145
+ const reserve = 64
146
+ if (maxChars <= reserve)
147
+ return text.slice(0, maxChars)
148
+ let keep = maxChars - reserve
149
+ let omitted = text.length - keep
150
+ let suffix = `\n…[truncated ${omitted} chars — narrow query or paginate]`
151
+ if (keep + suffix.length > maxChars) {
152
+ keep = Math.max(0, maxChars - suffix.length)
153
+ omitted = text.length - keep
154
+ suffix = `\n…[truncated ${omitted} chars — narrow query or paginate]`
155
+ }
156
+ return text.slice(0, keep) + suffix
157
+ }
158
+
159
+ export function applyPrune(value: unknown, mode: McpPruneMode): unknown {
160
+ if (mode === false)
161
+ return value
162
+ if (mode === 'nullish')
163
+ return pruneEmpty(value, { emptyCollections: false })
164
+ return pruneEmpty(value, { emptyCollections: true })
165
+ }
166
+
167
+ export function isMcpToolResult(value: unknown): value is McpToolResult {
168
+ if (typeof value !== 'object' || value === null || !('content' in value))
169
+ return false
170
+ const content = (value as { content: unknown }).content
171
+ return Array.isArray(content) && content.every(
172
+ item => typeof item === 'object' && item !== null && (item as { type?: unknown }).type === 'text' && typeof (item as { text?: unknown }).text === 'string',
173
+ )
174
+ }
175
+
176
+ export function formatFieldErrors(fieldErrors: unknown): string {
177
+ if (fieldErrors === null || typeof fieldErrors !== 'object' || Array.isArray(fieldErrors))
178
+ return ''
179
+ return Object.entries(fieldErrors as Record<string, unknown>)
180
+ .filter(([, v]) => v !== undefined && v !== null && String(v).length > 0)
181
+ .map(([k, v]) => `${k}: ${String(v)}`)
182
+ .join('; ')
183
+ }
184
+
185
+ export async function formatResponseResult(res: Response, pruneMode: McpPruneMode): Promise<McpToolResult> {
186
+ // 3xx redirects from reused Prunelle form actions indicate a completed mutation, not a failure.
187
+ if (res.status >= 300 && res.status < 400) {
188
+ const location = res.headers.get('location')
189
+ return { content: [{ type: 'text', text: location ? `ok -> ${location}` : 'ok' }] }
190
+ }
191
+
192
+ const rawText = await res.text()
193
+ if (!res.ok) {
194
+ let errorMsg = rawText || `${res.status} ${res.statusText}`.trim()
195
+ if (rawText.trimStart().startsWith('{')) {
196
+ try {
197
+ const parsed = JSON.parse(rawText) as { error?: unknown, message?: unknown, fieldErrors?: unknown }
198
+ const base = typeof parsed.error === 'string' && parsed.error.length > 0
199
+ ? parsed.error
200
+ : (typeof parsed.message === 'string' && parsed.message.length > 0 ? parsed.message : '')
201
+ const fields = formatFieldErrors(parsed.fieldErrors)
202
+ if (base && fields)
203
+ errorMsg = `${base} (${fields})`
204
+ else if (base)
205
+ errorMsg = base
206
+ else if (fields)
207
+ errorMsg = fields
208
+ }
209
+ catch {
210
+ // Keep rawText
211
+ }
212
+ }
213
+ return { content: [{ type: 'text', text: errorMsg }], isError: true }
214
+ }
215
+
216
+ if (rawText.length === 0 && res.status === 204)
217
+ return { content: [{ type: 'text', text: 'ok' }] }
218
+
219
+ const contentType = res.headers.get('content-type') ?? ''
220
+ if (contentType.includes('json')) {
221
+ try {
222
+ const parsed = JSON.parse(rawText) as unknown
223
+ 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
+ return { content: [{ type: 'text', text: rawText }] }
230
+ }
231
+
232
+ export function applyOutputBudget(result: McpToolResult, maxChars: number | undefined): McpToolResult {
233
+ if (maxChars === undefined || maxChars <= 0)
234
+ return result
235
+ let remaining = maxChars
236
+ const nextContent: McpContentBlock[] = []
237
+ for (const block of result.content) {
238
+ if (remaining <= 0)
239
+ break
240
+ const text = truncateOutput(block.text, remaining)
241
+ remaining -= text.length
242
+ nextContent.push({ type: 'text', text })
243
+ }
244
+ return result.isError !== undefined
245
+ ? { content: nextContent, isError: result.isError }
246
+ : { content: nextContent }
247
+ }
248
+
249
+ export async function finalizeToolValue(value: unknown, pruneMode: McpPruneMode): Promise<McpToolResult> {
250
+ if (value instanceof Response)
251
+ return await formatResponseResult(value, pruneMode)
252
+ if (isMcpToolResult(value))
253
+ return value
254
+ if (typeof value === 'string')
255
+ return { content: [{ type: 'text', text: value }] }
256
+ if (value === undefined)
257
+ return { content: [{ type: 'text', text: 'ok' }] }
258
+ return { content: [{ type: 'text', text: JSON.stringify(applyPrune(value, pruneMode)) }] }
259
+ }