mcponce 0.1.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.
Files changed (186) hide show
  1. package/README.md +1013 -0
  2. package/dist/cli/analytics.d.ts +5 -0
  3. package/dist/cli/analytics.d.ts.map +1 -0
  4. package/dist/cli/analytics.js +93 -0
  5. package/dist/cli/analytics.js.map +1 -0
  6. package/dist/cli/bin.d.ts +20 -0
  7. package/dist/cli/bin.d.ts.map +1 -0
  8. package/dist/cli/bin.js +510 -0
  9. package/dist/cli/bin.js.map +1 -0
  10. package/dist/cli/index.d.ts +9 -0
  11. package/dist/cli/index.d.ts.map +1 -0
  12. package/dist/cli/index.js +196 -0
  13. package/dist/cli/index.js.map +1 -0
  14. package/dist/cli/info.d.ts +3 -0
  15. package/dist/cli/info.d.ts.map +1 -0
  16. package/dist/cli/info.js +42 -0
  17. package/dist/cli/info.js.map +1 -0
  18. package/dist/cli/installer.d.ts +64 -0
  19. package/dist/cli/installer.d.ts.map +1 -0
  20. package/dist/cli/installer.js +183 -0
  21. package/dist/cli/installer.js.map +1 -0
  22. package/dist/cli/logs.d.ts +3 -0
  23. package/dist/cli/logs.d.ts.map +1 -0
  24. package/dist/cli/logs.js +19 -0
  25. package/dist/cli/logs.js.map +1 -0
  26. package/dist/cli/tool-caller.d.ts +70 -0
  27. package/dist/cli/tool-caller.d.ts.map +1 -0
  28. package/dist/cli/tool-caller.js +404 -0
  29. package/dist/cli/tool-caller.js.map +1 -0
  30. package/dist/index.d.ts +31 -0
  31. package/dist/index.d.ts.map +1 -0
  32. package/dist/index.js +27 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/logging/file-logger.d.ts +21 -0
  35. package/dist/logging/file-logger.d.ts.map +1 -0
  36. package/dist/logging/file-logger.js +96 -0
  37. package/dist/logging/file-logger.js.map +1 -0
  38. package/dist/logging/logger.d.ts +22 -0
  39. package/dist/logging/logger.d.ts.map +1 -0
  40. package/dist/logging/logger.js +57 -0
  41. package/dist/logging/logger.js.map +1 -0
  42. package/dist/logging/rotation.d.ts +6 -0
  43. package/dist/logging/rotation.d.ts.map +1 -0
  44. package/dist/logging/rotation.js +32 -0
  45. package/dist/logging/rotation.js.map +1 -0
  46. package/dist/registry/central.d.ts +54 -0
  47. package/dist/registry/central.d.ts.map +1 -0
  48. package/dist/registry/central.js +205 -0
  49. package/dist/registry/central.js.map +1 -0
  50. package/dist/registry/prompts.d.ts +9 -0
  51. package/dist/registry/prompts.d.ts.map +1 -0
  52. package/dist/registry/prompts.js +18 -0
  53. package/dist/registry/prompts.js.map +1 -0
  54. package/dist/registry/resources.d.ts +52 -0
  55. package/dist/registry/resources.d.ts.map +1 -0
  56. package/dist/registry/resources.js +102 -0
  57. package/dist/registry/resources.js.map +1 -0
  58. package/dist/registry/subscriptions.d.ts +44 -0
  59. package/dist/registry/subscriptions.d.ts.map +1 -0
  60. package/dist/registry/subscriptions.js +96 -0
  61. package/dist/registry/subscriptions.js.map +1 -0
  62. package/dist/registry/tools.d.ts +24 -0
  63. package/dist/registry/tools.d.ts.map +1 -0
  64. package/dist/registry/tools.js +120 -0
  65. package/dist/registry/tools.js.map +1 -0
  66. package/dist/runtime/config.d.ts +30 -0
  67. package/dist/runtime/config.d.ts.map +1 -0
  68. package/dist/runtime/config.js +79 -0
  69. package/dist/runtime/config.js.map +1 -0
  70. package/dist/runtime/health.d.ts +15 -0
  71. package/dist/runtime/health.d.ts.map +1 -0
  72. package/dist/runtime/health.js +63 -0
  73. package/dist/runtime/health.js.map +1 -0
  74. package/dist/runtime/instance.d.ts +33 -0
  75. package/dist/runtime/instance.d.ts.map +1 -0
  76. package/dist/runtime/instance.js +148 -0
  77. package/dist/runtime/instance.js.map +1 -0
  78. package/dist/runtime/lock.d.ts +33 -0
  79. package/dist/runtime/lock.d.ts.map +1 -0
  80. package/dist/runtime/lock.js +105 -0
  81. package/dist/runtime/lock.js.map +1 -0
  82. package/dist/runtime/paths.d.ts +16 -0
  83. package/dist/runtime/paths.d.ts.map +1 -0
  84. package/dist/runtime/paths.js +54 -0
  85. package/dist/runtime/paths.js.map +1 -0
  86. package/dist/runtime/state.d.ts +24 -0
  87. package/dist/runtime/state.d.ts.map +1 -0
  88. package/dist/runtime/state.js +71 -0
  89. package/dist/runtime/state.js.map +1 -0
  90. package/dist/runtime/unitup.d.ts +44 -0
  91. package/dist/runtime/unitup.d.ts.map +1 -0
  92. package/dist/runtime/unitup.js +134 -0
  93. package/dist/runtime/unitup.js.map +1 -0
  94. package/dist/server/analytics.d.ts +47 -0
  95. package/dist/server/analytics.d.ts.map +1 -0
  96. package/dist/server/analytics.js +327 -0
  97. package/dist/server/analytics.js.map +1 -0
  98. package/dist/server/app.d.ts +249 -0
  99. package/dist/server/app.d.ts.map +1 -0
  100. package/dist/server/app.js +1332 -0
  101. package/dist/server/app.js.map +1 -0
  102. package/dist/server/context.d.ts +12 -0
  103. package/dist/server/context.d.ts.map +1 -0
  104. package/dist/server/context.js +52 -0
  105. package/dist/server/context.js.map +1 -0
  106. package/dist/server/hono.d.ts +54 -0
  107. package/dist/server/hono.d.ts.map +1 -0
  108. package/dist/server/hono.js +423 -0
  109. package/dist/server/hono.js.map +1 -0
  110. package/dist/server/inspector.d.ts +21 -0
  111. package/dist/server/inspector.d.ts.map +1 -0
  112. package/dist/server/inspector.js +834 -0
  113. package/dist/server/inspector.js.map +1 -0
  114. package/dist/server/mcp.d.ts +41 -0
  115. package/dist/server/mcp.d.ts.map +1 -0
  116. package/dist/server/mcp.js +425 -0
  117. package/dist/server/mcp.js.map +1 -0
  118. package/dist/transport/http.d.ts +14 -0
  119. package/dist/transport/http.d.ts.map +1 -0
  120. package/dist/transport/http.js +48 -0
  121. package/dist/transport/http.js.map +1 -0
  122. package/dist/transport/proxy.d.ts +12 -0
  123. package/dist/transport/proxy.d.ts.map +1 -0
  124. package/dist/transport/proxy.js +115 -0
  125. package/dist/transport/proxy.js.map +1 -0
  126. package/dist/types.d.ts +602 -0
  127. package/dist/types.d.ts.map +1 -0
  128. package/dist/types.js +2 -0
  129. package/dist/types.js.map +1 -0
  130. package/dist/utils/browser.d.ts +6 -0
  131. package/dist/utils/browser.d.ts.map +1 -0
  132. package/dist/utils/browser.js +39 -0
  133. package/dist/utils/browser.js.map +1 -0
  134. package/dist/utils/cache.d.ts +43 -0
  135. package/dist/utils/cache.d.ts.map +1 -0
  136. package/dist/utils/cache.js +126 -0
  137. package/dist/utils/cache.js.map +1 -0
  138. package/dist/utils/coercion.d.ts +38 -0
  139. package/dist/utils/coercion.d.ts.map +1 -0
  140. package/dist/utils/coercion.js +175 -0
  141. package/dist/utils/coercion.js.map +1 -0
  142. package/dist/utils/completion.d.ts +30 -0
  143. package/dist/utils/completion.d.ts.map +1 -0
  144. package/dist/utils/completion.js +79 -0
  145. package/dist/utils/completion.js.map +1 -0
  146. package/dist/utils/media.d.ts +65 -0
  147. package/dist/utils/media.d.ts.map +1 -0
  148. package/dist/utils/media.js +305 -0
  149. package/dist/utils/media.js.map +1 -0
  150. package/dist/utils/middleware.d.ts +48 -0
  151. package/dist/utils/middleware.d.ts.map +1 -0
  152. package/dist/utils/middleware.js +133 -0
  153. package/dist/utils/middleware.js.map +1 -0
  154. package/dist/utils/openapi.d.ts +102 -0
  155. package/dist/utils/openapi.d.ts.map +1 -0
  156. package/dist/utils/openapi.js +368 -0
  157. package/dist/utils/openapi.js.map +1 -0
  158. package/dist/utils/progress.d.ts +26 -0
  159. package/dist/utils/progress.d.ts.map +1 -0
  160. package/dist/utils/progress.js +91 -0
  161. package/dist/utils/progress.js.map +1 -0
  162. package/dist/utils/queue.d.ts +51 -0
  163. package/dist/utils/queue.d.ts.map +1 -0
  164. package/dist/utils/queue.js +136 -0
  165. package/dist/utils/queue.js.map +1 -0
  166. package/dist/utils/retry.d.ts +26 -0
  167. package/dist/utils/retry.d.ts.map +1 -0
  168. package/dist/utils/retry.js +125 -0
  169. package/dist/utils/retry.js.map +1 -0
  170. package/dist/utils/roots.d.ts +21 -0
  171. package/dist/utils/roots.d.ts.map +1 -0
  172. package/dist/utils/roots.js +74 -0
  173. package/dist/utils/roots.js.map +1 -0
  174. package/dist/utils/sampling.d.ts +129 -0
  175. package/dist/utils/sampling.d.ts.map +1 -0
  176. package/dist/utils/sampling.js +177 -0
  177. package/dist/utils/sampling.js.map +1 -0
  178. package/dist/utils/security.d.ts +35 -0
  179. package/dist/utils/security.d.ts.map +1 -0
  180. package/dist/utils/security.js +113 -0
  181. package/dist/utils/security.js.map +1 -0
  182. package/dist/utils/validation.d.ts +52 -0
  183. package/dist/utils/validation.d.ts.map +1 -0
  184. package/dist/utils/validation.js +176 -0
  185. package/dist/utils/validation.js.map +1 -0
  186. package/package.json +61 -0
package/README.md ADDED
@@ -0,0 +1,1013 @@
1
+ # mcponce
2
+
3
+ > **Cross-platform MCP server from a single executable file** powered by **Hono** and the official **Model Context Protocol SDK**.
4
+
5
+ Add the MCP server once in your client settings, point it to one executable file, and let that file automatically start or reuse the local server.
6
+
7
+ ```text
8
+ Claude / Cursor / Antigravity / VS Code
9
+ │
10
+ │ stdio
11
+ ▼
12
+ Single executable file
13
+ │
14
+ ├── starts server if needed
15
+ ├── discovers existing server
16
+ ├── proxies MCP messages
17
+ └── writes logs/runtime state
18
+ │
19
+ ▼
20
+ Local Hono + MCP server
21
+ │
22
+ └── shared tools/resources/context
23
+ ```
24
+
25
+ ## Features
26
+
27
+ - **Single Executable UX**: No manual daemons to start, stop, or manage. One executable handles both server ownership and stdio bridging.
28
+ - **Cross-Platform**: Works out of the box on macOS, Linux, and Windows using native OS application state paths.
29
+ - **Dynamic Port Allocation**: Defaults to `port: 0` so the operating system assigns an available port. No port conflicts.
30
+ - **Robust Single-Instance**: Atomic lock files with `O_CREAT | O_EXCL`, HTTP `/health` verification, race handling with retry backoff, and automatic stale lock/crash recovery.
31
+ - **Shared Application Context**: Initialize database, caches, or connections once for the server, shared across all simultaneous client sessions.
32
+ - **Smart Input Coercion & Schema Defaults**: Shields handlers from LLM stringification errors (`"42"` -> `42`, `"false"` -> `false`, JSON strings to objects) with `coerceInputs: true` and schema defaults.
33
+ - **Automatic Retries with Exponential Backoff**: Declarative `retry: 3` with configurable exponential delays, cancellation aborts, selective predicates, and telemetry tracking.
34
+ - **In-Memory Response Caching**: LRU response caching (`cache: true` or custom TTL) with deterministic argument sorting and fine-grained invalidation.
35
+ - **Sequential Queuing & Mutexes**: Prevent race conditions with `sequential: true` or named mutex locks.
36
+ - **Images & Binary Media**: Return raw `Buffer`s or use `image(buffer)` helpers with automatic magic byte MIME detection (PNG, JPEG, GIF, WEBP, BMP, SVG) and base64 encoding.
37
+ - **Dynamic Resource URI Templates (RFC 6570)**: Expose parametric resources (`users://{userId}/profile`) with parameter extraction, client autocompletion callbacks, and automatic return normalization.
38
+ - **Resource Subscriptions & Live Push**: Client subscriptions (`resources/subscribe`, `resources/unsubscribe`) with live push updates (`app.notifyResourceUpdated`, `app.notifyResourceListChanged`).
39
+ - **Enterprise Security & Rate Limiting**: Multi-key Bearer/API Key auth, custom identity validators (`auth.validate`), tool-level RBAC scopes, sliding-window rate limiting (429 Retry-After), and OWASP security headers.
40
+ - **MCP Sampling & Workspace Roots**: Enable autonomous sub-agents by requesting LLM completions back from the client (`context.sample`) and querying open IDE workspace directories (`context.listRoots`).
41
+ - **OpenAPI / Swagger Auto-Generation**: Transform any REST API into type-safe MCP tools in 1 line with `app.fromOpenApi()`.
42
+ - **Interactive Web Inspector & Playground**: Zero-dependency browser developer UI at `/inspect` (`mcponce inspect` / `server.js inspect`) with dynamic form generation, execution diagnostics, and live metrics.
43
+ - **MCP Autocomplete Protocol**: Full `completion/complete` support for prompt arguments, resource template variables, and tool parameters.
44
+ - **Client Auto-Installer**: Automatically configure servers into Claude Desktop or Cursor in 1 command: `node server.js install` or `mcponce install <target>`.
45
+ - **Clean Protocol Communication**: `stdout` is reserved strictly for MCP JSON-RPC protocol messages. Diagnostic and error logs are written safely to log files and `stderr`.
46
+ - **Hono & Official MCP SDK**: Native Web Standards Streamable HTTP transport integration.
47
+
48
+ ## Comparison & Alternatives
49
+
50
+ Different tools in the MCP ecosystem serve different architectural needs:
51
+
52
+ | Feature / Capability | Official SDK (`@modelcontextprotocol/sdk`) | FastMCP (TypeScript) | Standalone Proxies (e.g., Supergateway) | **mcponce** |
53
+ | :--- | :---: | :---: | :---: | :---: |
54
+ | **Primary Focus** | Core protocol reference & wire primitives | Ergonomic syntax for quick scripts | Wrapping existing stdio servers without code changes | Enterprise-grade production runtime & lifecycle |
55
+ | **HTTP Web Standards** | ⚠️ Low-level transport primitives | ⚠️ Custom adapter | ✔ Built-in HTTP proxy | ✔ Native [Hono](https://hono.dev/) Streamable HTTP & stdio |
56
+ | **Background Daemon** | ❌ Spawns new process per window | ❌ Spawns new process per window | ❌ Spawns per connection | ✔ Single shared daemon via Unitup (<5ms warm connect) |
57
+ | **Concurrency & Mutex** | ❌ Manual | ❌ Manual | ❌ Manual | ✔ FIFO queues & named mutexes (`sequential: "browser"`) |
58
+ | **Input Coercion** | ❌ Fails on stringified numbers/bools | ❌ Strict Zod parse | ❌ Raw pass-through | ✔ Smart coercion (`"42"` ➔ `42`, JSON strings to objects) |
59
+ | **Response Caching** | ❌ Manual | ❌ Manual | ❌ Manual | ✔ Built-in LRU cache with TTL & fine-grained invalidation |
60
+ | **Inter-Tool Calling** | ❌ Manual | ❌ Manual | ❌ Not applicable | ✔ `context.callTool` with cycle detection & 20-depth guard |
61
+ | **Automatic Retries** | ❌ Manual | ❌ Manual | ❌ Manual | ✔ Exponential backoff & jitter (`retry: 3`) |
62
+ | **Observability & Metrics** | ❌ Console logs only | ❌ Console logs only | ❌ Basic access logs | ✔ Native Prometheus (`/metrics`) & JSON Telemetry (`/analytics`) |
63
+ | **CLI Tool Testing** | ❌ Needs full LLM client | ❌ Needs custom scripts | ⚠️ curl only | ✔ Built-in `mcponce call` with terminal progress bars |
64
+ | **Client Auto-Installer** | ❌ Manual config editing | ❌ Manual config editing | ❌ Manual config editing | ✔ `mcponce install` (Claude Desktop & Cursor 1-click) |
65
+ | **Subscriptions & Push** | ⚠️ Low-level subscribe primitives | ❌ Not supported | ⚠️ Basic SSE forwarding | ✔ Full `resources/subscribe` & `app.notifyResourceUpdated` |
66
+ | **Security & Rate Limiting** | ❌ Manual | ⚠️ Basic Bearer token | ⚠️ Basic proxy headers | ✔ Built-in Bearer & `X-API-Key`, custom `auth.validate`, RBAC scopes, rate limiting & OWASP headers |
67
+ | **Sampling & Roots** | ⚠️ Low-level server methods | ⚠️ Basic sampling helper | ❌ Not supported | ✔ Turnkey `context.sample`, `context.listRoots` & offline fallbacks |
68
+ | **OpenAPI Auto-Gen** | ❌ Manual tool definition | ❌ Separate package/script | ❌ Not supported | ✔ Turnkey `app.fromOpenApi()` & CLI `mcponce openapi` |
69
+ | **Web Inspector & UI** | ⚠️ Separate npm package | ✔ Built-in `fastmcp dev` | ❌ Not supported | ✔ Built-in `/inspect` playground & `mcponce inspect` |
70
+ | **Autocomplete Protocol** | ⚠️ Low-level completable | ✔ Basic completers | ❌ Not supported | ✔ Built-in `completion/complete` for prompts & templates |
71
+
72
+ ### When to choose what?
73
+
74
+ - **Choose the Official SDK** if you want minimal abstractions, zero extra dependencies beyond Anthropic packages, or are embedding MCP inside an existing custom enterprise framework (NestJS, Express, Fastify) that already has its own lifecycle, caching, and queueing infrastructure.
75
+ - **Choose FastMCP** if you are writing quick utility scripts, prefer decorating simple functions, and do not need background process multiplexing, named mutex queues, or Prometheus metrics.
76
+ - **Choose Standalone Proxies (Supergateway / mcp-proxy)** if you have an existing third-party MCP server binary (e.g. from GitHub) that only supports stdio and you need to expose it over SSE/HTTP without touching its source code.
77
+ - **Choose `mcponce`** if you are building production or team-shared MCP servers where multiple client windows should share a single warm background process, your tools touch rate-limited/exclusive resources needing mutex serialization, you want protection against LLM hallucinated argument types, or you require out-of-the-box Prometheus metrics and terminal CLI debugging.
78
+
79
+ ## Installation
80
+
81
+ ```bash
82
+ npm install mcponce
83
+ ```
84
+
85
+ ## Quick Start
86
+
87
+ ```ts
88
+ import { createMcpServer } from "mcponce";
89
+
90
+ // 1-parameter shorthand or config object:
91
+ const app = createMcpServer("my-mcp");
92
+
93
+ app.tool({
94
+ name: "hello",
95
+ description: "Say hello",
96
+ inputSchema: {
97
+ name: "string"
98
+ },
99
+ async handler({ name }) {
100
+ return {
101
+ content: [{ type: "text", text: `Hello ${name}!` }]
102
+ };
103
+ }
104
+ });
105
+
106
+ app.run();
107
+ ```
108
+
109
+ ### Calling Tools Within One Another (Inter-Tool Invocations)
110
+
111
+ Tools can invoke other registered tools internally with full argument validation, automatic cycle detection, and unwrapped data access:
112
+
113
+ ```ts
114
+ app.tool({
115
+ name: "add",
116
+ inputSchema: { a: "number", b: "number" },
117
+ handler: ({ a, b }) => a + b
118
+ });
119
+
120
+ app.tool({
121
+ name: "add_and_double",
122
+ inputSchema: { a: "number", b: "number" },
123
+ // 1. Access callTool directly from the context parameter:
124
+ async handler({ a, b }, { callTool }) {
125
+ const sumResult = await callTool("add", { a, b });
126
+ return sumResult.data * 2;
127
+ }
128
+ });
129
+ ```
130
+
131
+ You can also invoke tools programmatically directly on the server instance (great for testing):
132
+
133
+ ```ts
134
+ const result = await app.callTool("add", { a: 10, b: 20 });
135
+ console.log(result.data); // 30
136
+ console.log(result.text); // "30"
137
+ ```
138
+
139
+ ### Images & Binary Media Support (Screenshots, Charts & Buffers)
140
+
141
+ Many tools produce visual output (e.g. Playwright browser screenshots, canvas charts, PDF previews). In `mcponce`, returning a raw `Buffer` or using `image(buffer)` automatically normalizes into the standard MCP `ImageContent` block with magic-byte MIME type detection (PNG, JPEG, GIF, WEBP, BMP, SVG):
142
+
143
+ ```ts
144
+ import { image } from "mcponce";
145
+ import fs from "node:fs/promises";
146
+
147
+ // 1. Direct Buffer return (MIME type is auto-detected from magic bytes!)
148
+ app.tool({
149
+ name: "capture_screen",
150
+ handler: async () => {
151
+ return await fs.readFile("./screenshot.png");
152
+ }
153
+ });
154
+
155
+ // 2. Mixed multi-part content (Text + Image)
156
+ app.tool({
157
+ name: "render_dashboard",
158
+ handler: async () => {
159
+ const chartBuffer = await generateChart();
160
+ return [
161
+ "Here is the Q3 performance report:",
162
+ image(chartBuffer),
163
+ "Summary: Growth exceeded forecasts by 18%."
164
+ ];
165
+ }
166
+ });
167
+ ```
168
+
169
+ ### Dynamic Resource URI Templates (RFC 6570)
170
+
171
+ Expose parametric, dynamic resources to AI clients and developers. `mcponce` supports RFC 6570 URI templates with automated variable extraction, client autocompletions, and return normalization:
172
+
173
+ ```ts
174
+ app.resourceTemplate({
175
+ uriTemplate: "users://{userId}/profile",
176
+ name: "user_profile",
177
+ description: "User profile details",
178
+ mimeType: "application/json",
179
+ complete: {
180
+ // Autocompletions surfaced in Claude Desktop & Cursor
181
+ userId: async (prefix) => ["alice", "bob", "charlie"].filter((u) => u.startsWith(prefix))
182
+ },
183
+ handler: async (uri, { userId }) => {
184
+ // Return objects, strings, or Buffers—mcponce normalizes them automatically!
185
+ return {
186
+ userId,
187
+ role: "developer",
188
+ url: uri.href
189
+ };
190
+ }
191
+ });
192
+
193
+ // Programmatic reading (great for tests and inter-service reads)
194
+ const profile = await app.readResource("users://alice/profile");
195
+ ```
196
+
197
+ ### Resource Subscriptions & Live Push Notifications
198
+
199
+ Clients like Claude Desktop or Cursor can subscribe to dynamic resources via `resources/subscribe`. When application state changes, notify all subscribed clients in real time using `app.notifyResourceUpdated(uri)` or notify that the resource list changed using `app.notifyResourceListChanged()`.
200
+
201
+ ```ts
202
+ app.resource({
203
+ uri: "status://system",
204
+ name: "system_status",
205
+ mimeType: "application/json",
206
+ handler: async () => ({ status: getSystemStatus(), timestamp: Date.now() })
207
+ });
208
+
209
+ // Broadcast live push notification to all subscribed clients:
210
+ app.notifyResourceUpdated("status://system");
211
+
212
+ // Broadcast when new resources are added or removed:
213
+ app.notifyResourceListChanged();
214
+
215
+ // Hook into subscription events:
216
+ app.onResourceUpdated((uri, sessionIds) => {
217
+ console.log(`Resource ${uri} was updated for ${sessionIds.length} subscribers`);
218
+ });
219
+ ```
220
+
221
+ ### Enterprise Security, Authentication & Rate Limiting
222
+
223
+ Secure your MCP HTTP/SSE endpoints with multi-key authentication, custom identity validators (`auth.validate`), tool-level RBAC scopes, sliding-window rate limiting, and OWASP security headers. The public `/health` endpoint remains open for container orchestration and uptime monitoring.
224
+
225
+ ```ts
226
+ const app = createMcpServer({
227
+ name: "enterprise-mcp-server",
228
+ // 1. Static API keys (Bearer token or X-API-Key header)
229
+ apiKey: ["secret-token-12345", "backup-key-67890"],
230
+
231
+ // 2. Or custom identity validator with RBAC scopes
232
+ auth: {
233
+ validate: async (token, context) => {
234
+ const user = await verifyJwt(token);
235
+ return user ? { id: user.id, user: user.email, scopes: user.scopes } : false;
236
+ }
237
+ },
238
+
239
+ // 3. Sliding-window rate limiting (returns 429 & Retry-After)
240
+ rateLimit: {
241
+ max: 100,
242
+ windowMs: 60 * 1000
243
+ },
244
+
245
+ // 4. Configurable CORS & security headers
246
+ cors: {
247
+ origin: "https://app.example.com",
248
+ credentials: true
249
+ }
250
+ });
251
+
252
+ // 5. Tool-level permission scopes
253
+ app.tool({
254
+ name: "admin_delete_user",
255
+ inputSchema: { userId: "string" },
256
+ requireAuth: true,
257
+ scopes: ["admin:users", "write"],
258
+ handler: async ({ userId }, ctx, extra) => {
259
+ console.log(`Executed by: ${extra.auth?.user}`);
260
+ return `User ${userId} deleted`;
261
+ }
262
+ });
263
+ ```
264
+
265
+ Clients authenticate using standard headers or CLI flags:
266
+ - **Authorization Header**: `Authorization: Bearer secret-token-12345`
267
+ - **Custom Header**: `X-API-Key: secret-token-12345`
268
+ - **CLI Caller**: `mcponce call my-server admin_delete_user --userId 42 --token secret-token-12345`
269
+
270
+ ### MCP Sampling & Workspace Roots (Sub-Agents)
271
+
272
+ Turn your tools into autonomous sub-agents by requesting LLM completions (`sampling/createMessage`) back from the connected client (Claude Desktop, Cursor, AI agents). Tools can also discover open project folders via the MCP Roots protocol (`roots/list`).
273
+
274
+ ```ts
275
+ app.tool({
276
+ name: "code_reviewer",
277
+ inputSchema: { patch: "string" },
278
+ async handler({ patch }, { sample, listRoots }) {
279
+ // 1. Discover user's project directories in their IDE
280
+ const roots = await listRoots();
281
+
282
+ // 2. Request an LLM completion from the connected client
283
+ const reply = await sample({
284
+ prompt: `Review this diff and suggest performance improvements:\n\n${patch}`,
285
+ systemPrompt: "You are a senior code reviewer. Output a concise markdown report.",
286
+ maxTokens: 500,
287
+ temperature: 0.2
288
+ });
289
+
290
+ return {
291
+ review: reply.text,
292
+ modelUsed: reply.model,
293
+ workspace: roots[0]?.name
294
+ };
295
+ }
296
+ });
297
+
298
+ // Configure offline mock fallback during testing or standalone runs:
299
+ app.onSample(async (params) => {
300
+ return "Mock review for test environment";
301
+ });
302
+ ```
303
+
304
+ ### OpenAPI & Swagger Tool Auto-Generation (`app.fromOpenApi`)
305
+
306
+ Transform entire REST APIs into type-safe MCP tools in a single line. Supports OpenAPI v3.0, v3.1, and Swagger 2.0 specs via remote URLs, local file paths, JSON/YAML strings, or JS objects:
307
+
308
+ ```ts
309
+ // 1. From remote URL or local file path
310
+ await app.fromOpenApi("https://petstore.swagger.io/v2/swagger.json", {
311
+ prefix: "petstore", // e.g. "petstore_get_pet_by_id"
312
+ headers: {
313
+ Authorization: `Bearer ${process.env.API_KEY}`
314
+ }
315
+ });
316
+
317
+ // 2. Or from an inline specification with tag filtering
318
+ await app.fromOpenApi(specObject, {
319
+ baseUrl: "https://api.example.com",
320
+ tags: ["users", "billing"], // only generate tools for these tags
321
+ exclude: ["internal_*"],
322
+ transformResponse: (res) => res.data // extract inner payload
323
+ });
324
+ ```
325
+
326
+ All query, path, and header parameters as well as JSON request bodies are automatically mapped to pre-compiled Zod schemas with complete parameter type coercion.
327
+
328
+ ### Workspace Roots Security & Path Traversal Guards
329
+
330
+ When LLM agents operate across user files, `mcponce` provides path traversal defense helpers to ensure all file operations stay safely confined inside open IDE workspace roots:
331
+
332
+ ```ts
333
+ import { isPathInWorkspace, resolveWorkspacePath } from "mcponce";
334
+
335
+ app.tool({
336
+ name: "read_workspace_file",
337
+ inputSchema: { relativePath: "string" },
338
+ async handler({ relativePath }, { listRoots }) {
339
+ const roots = await listRoots();
340
+
341
+ // Resolves path and throws an error if "../" attempts to escape roots
342
+ const safePath = resolveWorkspacePath(relativePath, roots);
343
+ return await fs.readFile(safePath, "utf-8");
344
+ }
345
+ });
346
+ ```
347
+
348
+ ### Interactive Web Inspector & Playground (`/inspect`)
349
+
350
+ Every `mcponce` server includes a zero-dependency, dark-mode developer playground accessible directly at `http://localhost:<port>/inspect`.
351
+
352
+ Launch it directly during development:
353
+
354
+ ```bash
355
+ # Start your server and auto-open the Web Inspector
356
+ node server.js inspect
357
+
358
+ # Or open inspector for an active background server
359
+ mcponce inspect my-server
360
+ ```
361
+
362
+ - **Dynamic Form Generation**: Form controls automatically generated from tool `inputSchema` with type validation and sample value population.
363
+ - **Live Output Console**: Syntax-highlighted JSON trees, execution duration timers in milliseconds, and LRU cache HIT/MISS indicators.
364
+ - **Binary Media Renderer**: Renders image outputs directly in the browser.
365
+ - **Live Telemetry**: Real-time request counts, error counts, active sessions, and direct links to `/metrics` (Prometheus) and `/analytics` (JSON).
366
+
367
+ ### MCP Autocomplete Protocol (`completion/complete`)
368
+
369
+ Enable instant autocompletion in AI clients (Cursor, Claude Desktop, Antigravity) as users or agents type arguments:
370
+
371
+ ```ts
372
+ // 1. Prompt Argument Autocompletion
373
+ app.prompt({
374
+ name: "conventional_commit",
375
+ argsSchema: { type: "string" },
376
+ complete: {
377
+ type: (query) => ["feat", "fix", "docs", "style", "refactor", "test"].filter((t) => t.startsWith(query))
378
+ },
379
+ handler: ({ type }) => ({ messages: [...] })
380
+ });
381
+
382
+ // 2. Resource Template Autocompletion
383
+ app.resourceTemplate({
384
+ uriTemplate: "repos://{owner}/{repo}",
385
+ complete: {
386
+ owner: (query) => ["litepacks", "facebook", "microsoft"].filter((o) => o.startsWith(query)),
387
+ repo: (query, context) => context?.arguments?.owner === "litepacks" ? ["mcponce", "unitup"] : []
388
+ },
389
+ handler: async (uri, params) => ...
390
+ });
391
+ ```
392
+
393
+
394
+
395
+ ### Strict Naming Validation (AI Provider & Cross-Platform Compatibility)
396
+
397
+ Many AI providers (OpenAI, Anthropic Claude, Google Gemini) and MCP clients (Cursor, Claude Desktop, Antigravity) enforce strict naming requirements on tools and functions. For instance, OpenAI strictly rejects tool names with spaces, dots, or symbols (`^[a-zA-Z0-9_-]{1,64}$`), causing runtime API errors if violated.
398
+
399
+ `mcponce` automatically validates names upon registration and provides clear, actionable error messages with suggested alternatives:
400
+
401
+ - **Tool Names (`tool.name`)**: Must be 1–64 characters matching `/^[a-zA-Z0-9_-]{1,64}$/`. No spaces, dots, slashes, or unicode symbols.
402
+ - **Parameter Names (`inputSchema` keys)**: Must be 1–64 characters matching `/^[a-zA-Z0-9_-]{1,64}$/` to ensure schema compatibility with all LLM tool calling providers.
403
+ - **Server Names (`config.name`)**: Must be 1–128 characters matching `/^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*$/`. Disallows path traversal (`..`, `/`, `\`), Windows reserved names (`CON`, `PRN`, `NUL`, etc.), and whitespace, guaranteeing cross-platform filesystem and daemon compatibility.
404
+ - **Prompt Names (`prompt.name`)**: Must match `/^[a-zA-Z0-9_-]{1,64}$/`.
405
+
406
+ ```ts
407
+ import { isValidToolName, sanitizeToolName, sanitizeServerName } from "mcponce";
408
+
409
+ console.log(isValidToolName("get_user")); // true
410
+ console.log(isValidToolName("get user")); // false (spaces rejected by LLM providers)
411
+ console.log(sanitizeToolName("my tool: calculate!")); // "my_tool_calculate"
412
+ ```
413
+
414
+ ### Timeouts, Cancellation, and Error Resilience
415
+
416
+ `mcponce` provides enterprise-grade timeout, cancellation, and error handling out of the box:
417
+
418
+ - **Per-Tool & Global Timeouts**: Set `timeoutMs` per tool or `toolTimeoutMs` globally on the server (defaults to 60s, configurable via `MCP_TOOL_TIMEOUT_MS`). Set `timeoutMs: 0` to disable timeouts for long-running batch jobs.
419
+ - **Client Cancellation (`notifications/cancelled`)**: When a user clicks "Stop" in Claude, Cursor, or Antigravity, the client sends `notifications/cancelled`. `mcponce` automatically aborts the tool's `signal` (`AbortSignal`).
420
+ - **Resilient Handler Racing**: Even if a tool handler ignores the signal and hangs in a promise, `mcponce` races execution against the timeout/cancellation signal and aborts promptly without hanging the server.
421
+ - **MCP Spec Compliant Errors**: Tool exceptions and timeouts never crash the server or tear down HTTP/SSE sessions. They return structured `{ isError: true, content: [...] }` so LLMs can observe the failure and self-correct.
422
+
423
+ ```ts
424
+ app.tool({
425
+ name: "fetch_webpage",
426
+ description: "Fetches webpage content with cancellation & timeout",
427
+ inputSchema: { url: "string" },
428
+ timeoutMs: 5000, // Tool-specific 5-second timeout
429
+ async handler({ url }, { signal }) {
430
+ // Pass signal to fetch() or your async operations.
431
+ // If the client cancels or timeout expires, fetch aborts immediately!
432
+ const res = await fetch(url, { signal });
433
+ return await res.text();
434
+ }
435
+ });
436
+
437
+ // Programmatic tool calls with custom timeout or AbortController:
438
+ const controller = new AbortController();
439
+ const res = await app.callTool("fetch_webpage", { url: "https://example.com" }, {
440
+ signal: controller.signal,
441
+ timeoutMs: 3000,
442
+ throwOnError: false // returns { isError: true, ... } instead of throwing
443
+ });
444
+ ```
445
+
446
+ ### Sequential Execution & Concurrency Control (Queuing & Mutexes)
447
+
448
+ When tools interact with stateful or rate-limited resources (e.g. browser automation via Playwright/Puppeteer, hardware devices, database transactions, or single-session APIs), concurrent invocations can cause race conditions or state corruption.
449
+
450
+ `mcponce` provides built-in concurrency control and deterministic FIFO queuing:
451
+
452
+ - **Server-Level Sequential (`sequential: true`)**: All tool calls across the entire server are queued and executed one-by-one in strict FIFO order. Can also be enabled via environment variable `MCP_SEQUENTIAL=true`.
453
+ - **Server-Level Max Concurrency (`maxConcurrency: N`)**: Limits the number of simultaneous tool executions across the entire server to `N` (configurable via `MCP_MAX_CONCURRENCY`).
454
+ - **Tool-Level Sequential (`sequential: true`)**: Invocations of this specific tool run one at a time. Other independent tools continue running concurrently.
455
+ - **Tool-Level Max Concurrency (`maxConcurrency: N`)**: Limits simultaneous invocations of this specific tool to `N`.
456
+ - **Named Mutex Groups (`sequential: "group_name"`)**: Multiple distinct tools can share a single mutex queue. For example, `browser_click`, `browser_type`, and `browser_navigate` can all specify `sequential: "browser"` so they never run concurrently with each other while allowing other tools (like calculations or file reads) to run freely.
457
+ - **Safe Re-Entrancy**: Inter-tool calls (tools calling other tools via `context.callTool`) automatically detect that the parent caller already holds the queue lock, preventing deadlocks.
458
+ - **Queue Introspection**: Call `app.getQueueStats()` to inspect active tasks and waiting queue lengths at runtime.
459
+
460
+ #### Server-Level Sequential Mode
461
+
462
+ ```ts
463
+ const app = createMcpServer({
464
+ name: "single-threaded-app",
465
+ sequential: true // All tools execute serially one at a time
466
+ // or: maxConcurrency: 2
467
+ });
468
+ ```
469
+
470
+ #### Tool-Level Sequential & Named Mutexes
471
+
472
+ ```ts
473
+ // 1. Tool-level serial execution
474
+ app.tool({
475
+ name: "write_ledger",
476
+ description: "Appends to an accounting ledger without race conditions",
477
+ sequential: true, // Only one ledger write at a time
478
+ async handler({ entry }) {
479
+ await appendToLedger(entry);
480
+ }
481
+ });
482
+
483
+ // 2. Shared named mutex across multiple browser tools
484
+ app.tool({
485
+ name: "browser_navigate",
486
+ sequential: "browser_session", // Shares queue with browser_click
487
+ async handler({ url }) {
488
+ await page.goto(url);
489
+ }
490
+ });
491
+
492
+ app.tool({
493
+ name: "browser_click",
494
+ sequential: "browser_session", // Shares queue with browser_navigate
495
+ async handler({ selector }) {
496
+ await page.click(selector);
497
+ }
498
+ });
499
+
500
+ // 3. Rate-limited tool with maxConcurrency
501
+ app.tool({
502
+ name: "scrape_page",
503
+ maxConcurrency: 3, // At most 3 simultaneous scrape jobs
504
+ async handler({ url }) {
505
+ return await scrape(url);
506
+ }
507
+ });
508
+ ```
509
+
510
+ ### In-Memory Tool Response Caching
511
+
512
+ LLM workflows frequently re-query read-only tools with identical arguments across turns (e.g. `get_weather`, `search_docs`, `fetch_schema`, `get_stock_quote`), incurring redundant latency, API costs, and database load.
513
+
514
+ `mcponce` provides built-in, zero-dependency in-memory response caching with automatic LRU eviction and deterministic argument hashing:
515
+
516
+ - **Quick Caching (`cache: true`)**: Caches tool responses with a default 60-second TTL and 100-entry LRU limit.
517
+ - **Custom TTL & Limits (`cache: { ttlMs: 30_000, maxSize: 250 }`)**: Set custom expiration and capacity per tool.
518
+ - **Deterministic Argument Hashing**: `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` hit the exact same cache entry via key-sorted recursive serialization.
519
+ - **Cache Invalidation**:
520
+ - Inside mutating tools: `context.clearCache("other_tool")`.
521
+ - Programmatically: `app.clearCache("tool_name")` (or `app.clearCache()` to evict all).
522
+ - **Cache Bypass**: Call with `{ noCache: true }` in code or `--no-cache` via CLI.
523
+ - **Protocol Transparency**: Seamlessly caches both programmatic calls and remote MCP client calls over HTTP / SSE.
524
+ - **Error Non-Caching**: Only successful responses are cached. Errors and timeouts are never cached.
525
+
526
+ ```ts
527
+ // 1. Tool with 30-second response caching
528
+ app.tool({
529
+ name: "fetch_stock_quote",
530
+ description: "Fetches latest stock price with 30s cache",
531
+ inputSchema: { symbol: "string" },
532
+ cache: { ttlMs: 30_000 },
533
+ async handler({ symbol }) {
534
+ return await api.getQuote(symbol);
535
+ }
536
+ });
537
+
538
+ // 2. Invalidate cache from a mutating tool
539
+ app.tool({
540
+ name: "update_stock_symbol",
541
+ inputSchema: { symbol: "string", price: "number" },
542
+ async handler({ symbol, price }, { clearCache }) {
543
+ await db.updatePrice(symbol, price);
544
+ clearCache("fetch_stock_quote"); // Evicts cached quotes
545
+ }
546
+ });
547
+
548
+ // 3. Programmatic cache bypass and cache stats
549
+ await app.callTool("fetch_stock_quote", { symbol: "AAPL" }, { noCache: true });
550
+ console.log(app.getCacheStats()); // { size: 1, hits: 14, misses: 2, evictions: 0 }
551
+ ```
552
+
553
+ ### Automatic Tool Retries with Exponential Backoff
554
+
555
+ Tools frequently encounter transient network hiccups, brief database reconnects, or upstream API rate limits (e.g. 503 Service Unavailable, 429 Too Many Requests). Without automated recovery, transient errors fail the entire LLM workflow.
556
+
557
+ `mcponce` provides built-in, zero-dependency declarative retries with exponential backoff:
558
+
559
+ - **Shorthand (`retry: 3`)**: Automatically retries up to 3 times with exponential backoff (100ms, 200ms, 400ms).
560
+ - **Detailed Configuration (`retry: { attempts, backoffMs, factor, maxBackoffMs, retryIf }`)**: Customize initial delay, multiplier factor, maximum backoff cap, and selective error filtering.
561
+ - **Selective Retry Predicates (`retryIf`)**: Only retry transient errors (e.g. `(err) => err.status === 429 || err.code === 'ECONNRESET'`) while immediately failing on permanent errors like bad credentials.
562
+ - **Cancellation & Timeout Safe**: If a client cancels or the tool timeout expires while the server is sleeping between retries, the delay timer is aborted immediately without hanging the process.
563
+ - **Per-Call Overrides**: Override or disable retries for individual calls via `app.callTool(name, args, { retry: false })` or `{ retry: 5 }`.
564
+ - **Telemetry Integration**: Retries are automatically tracked in `analytics.getSnapshot().summary.totalRetries` and per-tool `metric.retries`, and logged at warning level (`tool:retry`).
565
+
566
+ ```ts
567
+ // 1. Declarative shorthand: retry up to 3 times on failure
568
+ app.tool({
569
+ name: "fetch_external_weather",
570
+ inputSchema: { city: "string" },
571
+ retry: 3,
572
+ async handler({ city }) {
573
+ return await weatherApi.getForecast(city);
574
+ }
575
+ });
576
+
577
+ // 2. Fine-grained configuration with error filter
578
+ app.tool({
579
+ name: "query_upstream_database",
580
+ retry: {
581
+ attempts: 4,
582
+ backoffMs: 200, // First retry after 200ms
583
+ factor: 2, // 200ms -> 400ms -> 800ms -> 1600ms
584
+ maxBackoffMs: 5000, // Cap backoff at 5 seconds
585
+ retryIf: (err) => err.isTransient === true // Don't retry validation or auth errors
586
+ },
587
+ async handler(args) {
588
+ return await db.query(args);
589
+ }
590
+ });
591
+
592
+ // 3. Programmatic override (bypass retries)
593
+ await app.callTool("fetch_external_weather", { city: "London" }, { retry: false });
594
+ ```
595
+
596
+ ### Smart Input Coercion & Schema Defaults
597
+
598
+ Smaller, open-source, or cost-efficient LLMs (e.g. Llama 3, Mistral, Gemma, GPT-4o-mini, Claude Haiku) often pass stringified numbers (`"42"` instead of `42`), stringified booleans (`"false"` instead of boolean `false`), stringified JSON objects/arrays, or omit optional fields.
599
+
600
+ `mcponce` provides zero-dependency **Smart Input Coercion & Schema Defaults**:
601
+
602
+ - **Boolean String Safety**: In JavaScript, `Boolean("false")` evaluates to `true`. `mcponce`'s coercion correctly maps `"false"`, `"0"`, `"no"`, and `"off"` to boolean `false`, and `"true"`, `"1"`, `"yes"`, `"on"` to `true`.
603
+ - **Numeric Coercion**: Automatically coerces numeric strings (`"42"`, `"3.14"`, `"-10"`) into JavaScript numbers.
604
+ - **JSON Object & Array Parsing**: Coerces stringified JSON (`'{"key": "val"}'` or `'["a", "b"]'`) into parsed objects and arrays, and wraps single values into `[val]` when an array is expected.
605
+ - **Extended Schema Properties**: Define defaults, descriptions, and coercion directly in `inputSchema`:
606
+ ```ts
607
+ inputSchema: {
608
+ page: { type: "number", default: 1, description: "Page number" },
609
+ limit: { type: "number", default: 25, description: "Items per page" },
610
+ activeOnly: { type: "boolean", default: true }
611
+ }
612
+ ```
613
+ - **Flexible Activation**:
614
+ - **Tool-Level**: `app.tool({ name: "...", coerceInputs: true, ... })`.
615
+ - **Server-Level**: `createMcpServer({ coerceInputs: true })` or via env `MCP_COERCE_INPUTS=true`.
616
+ - **Property-Level**: `page: { type: "number", coerce: true }`.
617
+ - **Per-Call Override**: `app.callTool(name, args, { coerceInputs: false })` (bypass) or `{ coerceInputs: true }` (enable).
618
+ - **Clean JSON Schema Advertising**: The underlying base type (`"type": "number"`, `"type": "boolean"`) and descriptions/defaults are preserved in JSON Schema advertised to clients over `tools/list`.
619
+
620
+ ```ts
621
+ // 1. Tool with automatic input coercion and defaults
622
+ app.tool({
623
+ name: "search_users",
624
+ description: "Searches users with smart type coercion",
625
+ coerceInputs: true,
626
+ inputSchema: {
627
+ page: { type: "number", default: 1, description: "Page number" },
628
+ limit: { type: "number", default: 20, description: "Items per page" },
629
+ activeOnly: { type: "boolean", default: true },
630
+ tags: { type: "array", default: [] }
631
+ },
632
+ async handler({ page, limit, activeOnly, tags }) {
633
+ // Guarantees: page is number (1), limit is number (20), activeOnly is boolean (true), tags is Array
634
+ return await db.findUsers({ page, limit, activeOnly, tags });
635
+ }
636
+ });
637
+
638
+ // Calling with stringified LLM inputs works seamlessly:
639
+ await app.callTool("search_users", {
640
+ page: "2",
641
+ limit: "50",
642
+ activeOnly: "false",
643
+ tags: '["admin", "developer"]'
644
+ });
645
+ ```
646
+
647
+ ### Real-Time Progress Reporting (`reportProgress`)
648
+
649
+ Long-running tools (e.g. file downloads, batch data migrations, AI embeddings, scraping, database indexing) need to communicate ongoing progress to clients before final completion so users and LLMs aren't left waiting blindly.
650
+
651
+ `mcponce` provides built-in, zero-dependency **Real-Time Progress Reporting**:
652
+
653
+ - **Official MCP Protocol Compliance**: When an MCP client (Claude Desktop, Cursor, Antigravity) requests progress via `_meta: { progressToken: "..." }`, `mcponce` automatically dispatches standard `notifications/progress` JSON-RPC messages over the active SSE/HTTP or stdio stream.
654
+ - **Unified Dual-Signature API**: Both `context.reportProgress(...)` and `extra.reportProgress(...)` support positional and object formats:
655
+ - `await context.reportProgress(current, total, message)`
656
+ - `await context.reportProgress({ progress: current, total, message })`
657
+ - **Programmatic Live Callbacks**: Pass `onProgress` to `app.callTool(name, args, { onProgress: (p) => ... })` to stream live updates in Node.js scripts or unit tests.
658
+ - **Inter-Tool Progress Forwarding**: When a parent tool calls a sub-tool, it can listen to the sub-tool's progress events via `context.callTool(..., { onProgress })` and aggregate or re-broadcast them.
659
+ - **Interactive CLI Terminal Display**: Running `mcponce call <tool-name>` renders live progress indicators and percentages on `stderr` (e.g. `[Progress sync_data] 45/100 (45%) - Syncing user records`), keeping `stdout` completely clean for piped JSON or output data. Supports `--no-progress` to suppress rendering.
660
+ - **Safe & Non-Blocking**: Progress reporting never throws or disrupts execution even if a client disconnects or an `onProgress` callback fails.
661
+
662
+ ```ts
663
+ // 1. Tool reporting progress during execution
664
+ app.tool({
665
+ name: "batch_process_records",
666
+ description: "Processes records in chunks with live progress updates",
667
+ inputSchema: { totalRecords: "number" },
668
+ async handler({ totalRecords }, context) {
669
+ for (let i = 1; i <= totalRecords; i++) {
670
+ // Positional syntax: (progress, total, statusMessage)
671
+ await context.reportProgress?.(i, totalRecords, `Processing record #${i}`);
672
+
673
+ // Or object syntax:
674
+ // await context.reportProgress?.({ progress: i, total: totalRecords, message: `Record #${i}` });
675
+ }
676
+
677
+ return { processed: totalRecords, success: true };
678
+ }
679
+ });
680
+
681
+ // 2. Programmatic invocation with live onProgress listener
682
+ const result = await app.callTool("batch_process_records", { totalRecords: 100 }, {
683
+ onProgress: (report) => {
684
+ console.log(`[Live Progress] ${report.tool}: ${report.progress}/${report.total} - ${report.message}`);
685
+ }
686
+ });
687
+
688
+ // 3. Running from CLI with live terminal progress indicator:
689
+ // $ mcponce call batch_process_records --totalRecords 50
690
+ // [Progress batch_process_records] 50/50 (100%) - Processing record #50
691
+ ```
692
+
693
+ ### Lightweight Middleware & Interceptors (`app.use`)
694
+
695
+ `mcponce` features a zero-dependency, Koa/Hono-style **Onion Middleware Subsystem** that intercepts tool executions. Use middleware for authentication, authorization guards, global request logging, argument mutation, context enrichment, custom rate-limiting, error fallbacks, and response masking:
696
+
697
+ - **Onion Model Execution**: Middlewares follow the standard `async (ctx, next) => { ... }` signature. Calling `await next()` passes control to downstream middleware and the final tool handler, then unwinds back up the stack.
698
+ - **Multi-Level Scope**:
699
+ - **Global**: `app.use(handler)` intercepts every tool call on the server.
700
+ - **Pattern / Filtered**: `app.use('admin_*', handler)`, `app.use(['read', 'write'], handler)`, or `app.use(/^query_/, handler)`.
701
+ - **Tool-Level**: `app.tool({ name: 'x', middleware: [auth, rateLimiter], ... })` attaches middleware exclusively to a specific tool.
702
+ - **Server Config**: `createMcpServer({ middleware: [...] })` registers initial middleware at server initialization.
703
+ - **Full Pipeline Control**:
704
+ - **Argument Mutation**: Mutate or inject parameters in `ctx.args` before the tool handler runs.
705
+ - **Context Enrichment**: Attach session tokens, database clients, or authenticated user info onto `ctx.context`.
706
+ - **Early Short-Circuiting**: Return cached data or mock responses without invoking downstream handlers.
707
+ - **Error Interception & Recovery**: Wrap `await next()` in `try ... catch` to transform errors into user-friendly responses or fallback values.
708
+ - **Response Transformation**: Inspect or redact sensitive properties from the returned tool output.
709
+ - **Universal Coverage**: Works identically across remote MCP clients (HTTP/SSE, stdio), programmatic invocations (`app.callTool`), inter-tool calls (`context.callTool`), and CLI calls (`mcponce call`).
710
+
711
+ ```ts
712
+ import { createMcpServer } from "mcponce";
713
+
714
+ const app = createMcpServer({ name: "secure-api-server" });
715
+
716
+ // 1. Global Timing & Audit Logging Middleware
717
+ app.use(async (ctx, next) => {
718
+ const start = Date.now();
719
+ console.log(`[Audit] Starting execution of tool: ${ctx.tool}`);
720
+
721
+ const result = await next();
722
+
723
+ console.log(`[Audit] Completed ${ctx.tool} in ${Date.now() - start}ms`);
724
+ return result;
725
+ });
726
+
727
+ // 2. Authentication Guard on Admin Tools (Pattern-based)
728
+ app.use("admin_*", async (ctx, next) => {
729
+ if (!ctx.args.apiKey || ctx.args.apiKey !== process.env.ADMIN_API_KEY) {
730
+ throw new Error("Unauthorized: Valid admin apiKey required");
731
+ }
732
+ return next();
733
+ });
734
+
735
+ // 3. Context Enrichment & Input Normalization Middleware
736
+ app.use(async (ctx, next) => {
737
+ // Attach authenticated identity to shared context
738
+ ctx.context.user = { id: 42, role: "developer" };
739
+
740
+ // Normalize string arguments
741
+ if (typeof ctx.args.query === "string") {
742
+ ctx.args.query = ctx.args.query.trim().toLowerCase();
743
+ }
744
+ return next();
745
+ });
746
+
747
+ // 4. Tool-Specific Middleware
748
+ const confirmGuard = async (ctx, next) => {
749
+ if (!ctx.args.confirmed) {
750
+ return { status: "aborted", message: "Operation requires confirmation" };
751
+ }
752
+ return next();
753
+ };
754
+
755
+ app.tool({
756
+ name: "admin_purge_database",
757
+ middleware: [confirmGuard],
758
+ handler: async (args, context) => {
759
+ // context.user is accessible here
760
+ return { purgedBy: context.user.id };
761
+ }
762
+ });
763
+ ```
764
+
765
+ ### Tool Analytics & Telemetry
766
+
767
+ `mcponce` automatically collects in-memory telemetry with zero performance overhead:
768
+
769
+ - **Invocation Counts & Durations**: Tracks total, successful, failed, timeout, and cancellation counts, as well as `minDurationMs`, `maxDurationMs`, `avgDurationMs`, and `lastDurationMs` for each tool.
770
+ - **Inter-Tool Call Graph**: Automatically maps which tools call which other tools (`compound_calc ──(x12)──> calculate`).
771
+ - **Recent Invocations Feed**: Capped circular buffer of recent executions with millisecond durations, statuses, and caller origins.
772
+ - **Multi-Channel Access**:
773
+ - **CLI**: `node server.js analytics` renders a formatted terminal dashboard table.
774
+ - **HTTP Endpoints**: `GET /analytics` returns full telemetry JSON; `GET /info` includes high-level totals.
775
+ - **Programmatic**: `app.getAnalytics()` and `app.resetAnalytics()`.
776
+ - **MCP Clients**: Any connected client can inspect the built-in `system://analytics` resource.
777
+
778
+ ```ts
779
+ const analytics = app.getAnalytics();
780
+ console.log(`Total calls: ${analytics.summary.totalInvocations}`);
781
+ console.log(`Average duration: ${analytics.summary.averageExecutionTimeMs}ms`);
782
+ console.log(analytics.tools["calculate"]);
783
+ ```
784
+
785
+ ### Prometheus & OpenTelemetry Metrics (`GET /metrics`)
786
+
787
+ `mcponce` exposes standard Prometheus 0.0.4 text exposition format metrics out of the box for Kubernetes, Grafana, Datadog, and Prometheus scrapers:
788
+
789
+ - **HTTP Scrape Endpoint**: `GET /metrics` (`Content-Type: text/plain; version=0.0.4; charset=utf-8`)
790
+ - **Programmatic Access**: `app.getMetrics()` returns the full Prometheus metric string.
791
+ - **Built-in MCP Resource**: `system://metrics` allows connected AI clients to read live Prometheus counters.
792
+
793
+ Exposed standard metrics:
794
+ - `mcp_server_info{server="...",version="..."} 1`
795
+ - `mcp_server_uptime_seconds{server="..."} <seconds>`
796
+ - `mcp_active_sessions{server="..."} <gauge>`
797
+ - `mcp_sessions_total{server="..."} <counter>`
798
+ - `mcp_tool_invocations_total{server="...",status="success|error|timeout|cancelled"} <counter>`
799
+ - `mcp_tool_calls_total{server="...",tool="...",status="..."} <counter>`
800
+ - `mcp_tool_duration_seconds_total{server="...",tool="..."} <counter>`
801
+ - `mcp_tool_duration_seconds_avg{server="...",tool="..."} <gauge>`
802
+ - `mcp_tool_cache_hits_total{server="...",tool="..."} <counter>`
803
+ - `mcp_tool_retries_total{server="...",tool="..."} <counter>`
804
+ - `mcp_inter_tool_calls_total{server="...",caller="...",target="..."} <counter>`
805
+ - `mcp_cache_entries{server="..."} <gauge>`
806
+ - `mcp_cache_hits_total{server="..."} <counter>`
807
+ - `mcp_cache_misses_total{server="..."} <counter>`
808
+ - `mcp_cache_evictions_total{server="..."} <counter>`
809
+
810
+ ```ts
811
+ // Scrape directly from code or test:
812
+ const metricsString = app.getMetrics();
813
+ console.log(metricsString);
814
+ ```
815
+
816
+ ## Client Configuration
817
+
818
+ Add to your MCP client config (e.g. `claude_desktop_config.json`, `cursor.json`). You can pass `--background` (or `-b`) directly as an argument:
819
+
820
+ ```json
821
+ {
822
+ "mcpServers": {
823
+ "my-server": {
824
+ "command": "node",
825
+ "args": ["/absolute/path/to/my-mcp.js", "--background"]
826
+ }
827
+ }
828
+ }
829
+ ```
830
+
831
+ ## Standalone Single-Executable Operation
832
+
833
+ `mcponce` is built first and foremost for **single-executable standalone operation**:
834
+
835
+ - You don't need any daemon or central manager running.
836
+ - Simply run your file: `node my-mcp.js` (or compile it to a standalone binary with `bun build --compile`, `pkg`, or `sea`).
837
+ - Point Claude Desktop, Cursor, or Antigravity directly to the file.
838
+ - The file automatically starts the background HTTP server on demand, single-instance coordinates, proxies stdio safely, and cleanly terminates when the client disconnects.
839
+
840
+ ### Standalone CLI Commands
841
+
842
+ You can test tools and run diagnostics directly on any individual server file without the central CLI or opening Claude/Cursor:
843
+
844
+ ```bash
845
+ node my-mcp.js tools # List all registered tools, descriptions, and schemas
846
+ node my-mcp.js call <tool> [params...] # Execute a tool directly with CLI flags or JSON
847
+ node my-mcp.js call <tool> --help # View detailed parameter schema and usage example
848
+ node my-mcp.js info # Inspect running status, PID, port, active sessions
849
+ node my-mcp.js analytics # View tool execution metrics and call graph
850
+ node my-mcp.js start # Start in background (if background: true configured)
851
+ node my-mcp.js stop # Stop the running server instance
852
+ node my-mcp.js restart # Restart the server instance
853
+ node my-mcp.js logs [count] # View recent server logs
854
+ node my-mcp.js --dev # Run with diagnostic logs piped to stderr
855
+ node my-mcp.js --help # Show help
856
+ ```
857
+
858
+ #### Direct Tool Invocation & Testing via CLI
859
+
860
+ You can execute any tool directly from the terminal without setting up an MCP client:
861
+
862
+ ```bash
863
+ # 1. Discover registered tools and their parameter types
864
+ node my-mcp.js tools
865
+
866
+ # 2. Inspect a specific tool's parameter schema and usage example
867
+ node my-mcp.js call calculate --help
868
+
869
+ # 3. Call tool using named flags with automatic type casting
870
+ node my-mcp.js call calculate --operation add --a 10 --b 25
871
+ node my-mcp.js call hello --name Alice
872
+
873
+ # 4. Call tool with an inline JSON payload (or mix with flag overrides)
874
+ node my-mcp.js call calculate '{"operation": "multiply", "a": 6, "b": 7}'
875
+ node my-mcp.js call calculate '{"operation": "add", "a": 10}' --b 20
876
+
877
+ # 5. Output raw JSON for scripts, automation, or piping to jq
878
+ node my-mcp.js call calculate --operation add -a 10 -b 25 --json | jq .result
879
+ ```
880
+
881
+ ---
882
+
883
+ ## Background Execution with Unitup (Optional)
884
+
885
+ `mcponce` supports running the shared MCP server as a detached background service using [Unitup](https://github.com/litepacks/unitup).
886
+
887
+ You can enable background mode in **3 convenient ways**:
888
+
889
+ 1. **Via CLI parameter (`--background` / `-b`)** — *Zero code changes needed*:
890
+ ```bash
891
+ node server.js --background
892
+ ```
893
+ Or in your MCP client config (e.g. `claude_desktop_config.json`):
894
+ ```json
895
+ {
896
+ "mcpServers": {
897
+ "my-server": {
898
+ "command": "node",
899
+ "args": ["/path/to/server.js", "--background"]
900
+ }
901
+ }
902
+ }
903
+ ```
904
+
905
+ 2. **Via Server Configuration (`background: true`)**:
906
+ ```ts
907
+ const app = createMcpServer({
908
+ name: "browsertrack",
909
+ background: true
910
+ });
911
+
912
+ app.run();
913
+ ```
914
+
915
+ 3. **Programmatically (`app.start({ background: true })`)**:
916
+ ```ts
917
+ const app = createMcpServer("browsertrack");
918
+
919
+ await app.start({ background: true }); // Starts or reuses background server
920
+ await app.stop({ background: true }); // Stops background process and cleans runtime state
921
+ await app.restart({ background: true }); // Restarts background process and waits for /health
922
+ ```
923
+
924
+ ### Behavior & Architecture
925
+
926
+ - **Default (`background: false` or omitted)**: Uses the standard native on-demand lifecycle.
927
+ - **Enabled (via CLI `--background`, `background: true`, or `app.start({ background: true })`)**:
928
+ - The client executable checks for an existing healthy background instance.
929
+ - If none is running, it acquires the startup lock and uses **Unitup** to spawn the detached background server.
930
+ - Waits for `GET /health` verification before connecting as a stdio bridge.
931
+ - When the initial client (e.g. Claude) disconnects, **the background server remains alive** for other clients (Cursor, Antigravity, VS Code).
932
+ - Multiple distinct applications (e.g. `browsertrack`, `softscope`, `recallite`) each run their own independent background singleton.
933
+ - **Source of Truth**: `mcponce` remains the sole authority for health verification, atomic locking, dynamic port discovery, and runtime metadata. Unitup is strictly an internal process-management detail.
934
+ - **Optional Dependency**: Unitup is only loaded when background mode is active. If enabled without Unitup installed, a clear error guides the user:
935
+ ```text
936
+ Background mode requires Unitup, but Unitup is not installed.
937
+
938
+ Install it with:
939
+
940
+ npm install unitup
941
+ ```
942
+ - **Logs**: Unitup stdout and stderr logs are saved directly in `app.getLogDirectory()` (`<dataDir>/logs/unitup.stdout.log`).
943
+
944
+ ---
945
+
946
+ ## Central Management CLI (`mcponce`)
947
+
948
+ As an **optional addition**, `mcponce` comes with a global CLI that tracks all local MCP servers created on your machine in a lightweight JSON registry (`~/.mcponce/servers.json` or OS equivalent):
949
+
950
+ ```bash
951
+ # List all registered MCP servers, statuses, PIDs, and ports
952
+ npx mcponce list
953
+
954
+ # Auto-configure server into Claude Desktop or Cursor
955
+ npx mcponce install ./server.js
956
+ npx mcponce install my-server claude
957
+ npx mcponce uninstall my-server claude
958
+
959
+ # Inspect detailed metrics and active sessions
960
+ npx mcponce status
961
+ npx mcponce status my-server
962
+
963
+ # Discover tools available on any running server
964
+ npx mcponce tools my-server
965
+
966
+ # Invoke a tool on a running server directly with CLI flags or JSON
967
+ npx mcponce call my-server calculate --operation add -a 10 -b 20
968
+ npx mcponce call my-server hello --name Alice
969
+
970
+ # View logs of any server from anywhere
971
+ npx mcponce logs my-server 100
972
+
973
+ # Stop a running server (or all servers)
974
+ npx mcponce stop my-server
975
+ npx mcponce stop --all
976
+
977
+ # Clean up stopped servers from registry
978
+ npx mcponce clean
979
+ ```
980
+
981
+ ### Opt-out / Isolated Mode
982
+
983
+ If you do not want an individual server to register in the central `servers.json`, you can disable it either in code or via environment variable:
984
+
985
+ ```ts
986
+ const app = createMcpServer({
987
+ name: "isolated-mcp",
988
+ registerInCentral: false // Operates 100% standalone and isolated
989
+ });
990
+ ```
991
+
992
+ Or run with:
993
+
994
+ ```bash
995
+ MCP_DISABLE_REGISTRY=1 node my-mcp.js
996
+ ```
997
+
998
+ ## Application Data and Logs
999
+
1000
+ Runtime metadata (`runtime.json`, `instance.lock`) and logs are saved per-server in:
1001
+
1002
+ - **macOS**: `~/Library/Application Support/<name>/logs/`
1003
+ - **Linux**: `$XDG_STATE_HOME/<name>/logs/` or `~/.local/state/<name>/logs/`
1004
+ - **Windows**: `%LOCALAPPDATA%\<name>\logs\`
1005
+
1006
+ The central registry is stored at:
1007
+ - **macOS/Linux**: `~/.mcponce/servers.json` (or `$XDG_STATE_HOME/mcponce/servers.json`)
1008
+ - **Windows**: `%LOCALAPPDATA%\mcponce\servers.json`
1009
+
1010
+ ## License
1011
+
1012
+ MIT
1013
+