@casys/mcp-server 0.26.1 → 0.27.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.
Files changed (62) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +10 -627
  4. package/esm/mod.d.ts +1 -0
  5. package/esm/mod.js +1 -0
  6. package/package.json +28 -25
  7. package/mod.ts +0 -302
  8. package/src/auth/as-metadata-proxy.ts +0 -288
  9. package/src/auth/config.ts +0 -368
  10. package/src/auth/jwt-provider.ts +0 -327
  11. package/src/auth/middleware.ts +0 -257
  12. package/src/auth/mod.ts +0 -89
  13. package/src/auth/multi-tenant-middleware.ts +0 -236
  14. package/src/auth/presets.ts +0 -351
  15. package/src/auth/provider.ts +0 -49
  16. package/src/auth/scope-middleware.ts +0 -59
  17. package/src/auth/static-token-provider.ts +0 -197
  18. package/src/auth/types.ts +0 -207
  19. package/src/client-auth/callback-server.ts +0 -166
  20. package/src/client-auth/client-id-metadata.ts +0 -260
  21. package/src/client-auth/connect.ts +0 -72
  22. package/src/client-auth/mod.ts +0 -44
  23. package/src/client-auth/provider.ts +0 -300
  24. package/src/client-auth/token-store/file-store.ts +0 -73
  25. package/src/client-auth/token-store/memory-store.ts +0 -32
  26. package/src/client-auth/types.ts +0 -95
  27. package/src/concurrency/rate-limiter.ts +0 -190
  28. package/src/concurrency/request-queue.ts +0 -140
  29. package/src/http/body.ts +0 -72
  30. package/src/http/request-guards.ts +0 -137
  31. package/src/http/wire.ts +0 -41
  32. package/src/inspector/launcher.ts +0 -131
  33. package/src/mcp-app.ts +0 -4595
  34. package/src/middleware/backpressure.ts +0 -36
  35. package/src/middleware/mod.ts +0 -21
  36. package/src/middleware/rate-limit.ts +0 -45
  37. package/src/middleware/runner.ts +0 -63
  38. package/src/middleware/types.ts +0 -104
  39. package/src/middleware/validation.ts +0 -28
  40. package/src/mrtr/capability-check.ts +0 -303
  41. package/src/mrtr/mod.ts +0 -54
  42. package/src/mrtr/replay-store.ts +0 -103
  43. package/src/mrtr/request-state.ts +0 -435
  44. package/src/mrtr/retry-guard.ts +0 -110
  45. package/src/mrtr/types.ts +0 -107
  46. package/src/observability/metrics.ts +0 -336
  47. package/src/observability/mod.ts +0 -21
  48. package/src/observability/otel.ts +0 -330
  49. package/src/runtime/runtime.deno.ts +0 -149
  50. package/src/runtime/runtime.node.ts +0 -324
  51. package/src/runtime/runtime.ts +0 -50
  52. package/src/runtime/types.ts +0 -130
  53. package/src/security/channel-hmac.ts +0 -140
  54. package/src/security/csp.ts +0 -89
  55. package/src/security/message-signer.ts +0 -223
  56. package/src/subscriptions/subscription-registry.ts +0 -558
  57. package/src/tasks/mod.ts +0 -33
  58. package/src/tasks/task-store.ts +0 -1014
  59. package/src/transport/request-headers.ts +0 -661
  60. package/src/types.ts +0 -908
  61. package/src/ui/viewer-utils.ts +0 -117
  62. package/src/validation/schema-validator.ts +0 -307
package/src/types.ts DELETED
@@ -1,908 +0,0 @@
1
- /**
2
- * Type definitions for the MCP Concurrent Server Framework
3
- *
4
- * This module provides TypeScript types for building high-performance
5
- * MCP servers with built-in concurrency control and backpressure.
6
- *
7
- * @module lib/server/types
8
- */
9
-
10
- import type { McpUiToolMeta as McpUiToolMetaBase } from "@modelcontextprotocol/ext-apps";
11
- import type {
12
- ClientCapabilities,
13
- Implementation,
14
- } from "@modelcontextprotocol/sdk/types.js";
15
-
16
- /**
17
- * Rate limit configuration
18
- */
19
- export interface RateLimitOptions {
20
- /** Maximum requests per window */
21
- maxRequests: number;
22
-
23
- /** Time window in milliseconds */
24
- windowMs: number;
25
-
26
- /**
27
- * Function to extract client identifier from request context
28
- * Default: uses "default" for all requests (global rate limit)
29
- */
30
- keyExtractor?: (context: RateLimitContext) => string;
31
-
32
- /**
33
- * Behavior when rate limit is exceeded
34
- * - 'reject': Return error immediately
35
- * - 'wait': Wait for slot with backoff (default)
36
- */
37
- onLimitExceeded?: "reject" | "wait";
38
- }
39
-
40
- /**
41
- * Context passed to rate limit key extractor
42
- */
43
- export interface RateLimitContext {
44
- /** Tool being called */
45
- toolName: string;
46
-
47
- /** Tool arguments */
48
- args: Record<string, unknown>;
49
- }
50
-
51
- /**
52
- * Configuration options for McpApp
53
- */
54
- export interface McpAppOptions {
55
- /** Server name (shown in MCP protocol) */
56
- name: string;
57
-
58
- /** Server version */
59
- version: string;
60
-
61
- /** Maximum concurrent requests (default: 10) */
62
- maxConcurrent?: number;
63
-
64
- /** Backpressure strategy when at capacity (default: 'sleep') */
65
- backpressureStrategy?: "sleep" | "queue" | "reject";
66
-
67
- /** Sleep duration in ms for 'sleep' strategy (default: 10) */
68
- backpressureSleepMs?: number;
69
-
70
- /**
71
- * Rate limiting configuration
72
- * If provided, requests will be rate limited per client
73
- */
74
- rateLimit?: RateLimitOptions;
75
-
76
- /**
77
- * Enable JSON Schema validation for tool arguments (default: false)
78
- * When enabled, validates arguments against tool's inputSchema before execution
79
- */
80
- validateSchema?: boolean;
81
-
82
- /**
83
- * @deprecated No-op as of 0.24.0. The SamplingBridge was removed in the
84
- * MCP 2026-07-28 spec drop. Passing this option has zero effect and emits
85
- * a console warning at startup. Will be removed in 0.25.0.
86
- */
87
- enableSampling?: boolean;
88
-
89
- /**
90
- * Instructions for the LLM on how to use this server's tools.
91
- * Sent in the MCP initialize response. The LLM sees this before any tool call.
92
- */
93
- instructions?: string;
94
-
95
- /**
96
- * @deprecated No-op as of 0.24.0. The SamplingBridge was removed in the
97
- * MCP 2026-07-28 spec drop. Passing this option has zero effect and emits
98
- * a console warning at startup. Will be removed in 0.25.0.
99
- */
100
- samplingClient?: SamplingClient;
101
-
102
- /** Custom logger function (default: console.error) */
103
- logger?: (msg: string) => void;
104
-
105
- /**
106
- * Custom error handler for tool execution errors.
107
- *
108
- * When set, errors thrown by tool handlers are passed to this function.
109
- * Return a message string to produce `{ content: [{type:"text", text: msg}], isError: true }`
110
- * instead of re-throwing. Return null to rethrow as a JSON-RPC error.
111
- *
112
- * Default: undefined (all errors are re-thrown, existing behaviour).
113
- */
114
- toolErrorMapper?: ToolErrorMapper;
115
-
116
- /**
117
- * OAuth2/Bearer authentication configuration.
118
- * When provided, HTTP requests require a valid Bearer token.
119
- * STDIO transport is unaffected (local, no auth needed).
120
- */
121
- auth?: import("./auth/types.js").AuthOptions;
122
-
123
- /**
124
- * Content Security Policy for HTML resources (MCP Apps).
125
- * When provided, injects a CSP `<meta>` tag into HTML content before serving.
126
- * This protects against XSS even in STDIO mode where HTTP headers are unavailable.
127
- *
128
- * @example
129
- * ```typescript
130
- * resourceCsp: { allowInline: true }
131
- * ```
132
- */
133
- resourceCsp?: import("./security/csp.js").CspOptions;
134
-
135
- /**
136
- * Pre-declare the `resources` capability before transport connection.
137
- *
138
- * When true, installs `resources/list` and `resources/read` handlers at
139
- * construction time (before start/startHttp). Resources can then be added
140
- * dynamically after startup via registerResource() without hitting the
141
- * SDK's "Cannot register capabilities after connecting to transport" error.
142
- *
143
- * Use this when resources are discovered asynchronously (e.g., MCP relay/proxy
144
- * that discovers child servers after the stdio handshake).
145
- */
146
- expectResources?: boolean;
147
-
148
- /**
149
- * HTTP transport mode. Only `"stateless"` is supported as of spec 2026-07-28.
150
- *
151
- * Per-request transport: no handshake, no `Mcp-Session-Id`.
152
- * `protocolVersion` is read from
153
- * `params._meta["io.modelcontextprotocol/protocolVersion"]` on every
154
- * request. `GET /mcp` returns 405; use `subscriptions/listen` instead.
155
- */
156
- transport?: "stateless";
157
-
158
- /**
159
- * Cache hints emitted on list and read results (spec 2026-07-28,
160
- * `CacheableResult`, SEP-2549).
161
- *
162
- * `ttlMs` and `cacheScope` are **required** fields of those results, so the
163
- * framework always emits them. The defaults are deliberately inert:
164
- *
165
- * - `ttlMs: 0` — "revalidate every time", the HTTP `max-age=0` equivalent.
166
- * Caching is a per-deployment decision: a server whose tool list is built
167
- * from a live database must not have a stale window chosen for it. Opt in
168
- * with a real value.
169
- * - `cacheScope: "private"` — shared intermediaries must not cache the
170
- * response. Anything else would be unsafe by default here, since results can
171
- * be scoped to the authenticated principal or tenant. Use `"public"` only for
172
- * a server whose lists are genuinely identical for every caller.
173
- */
174
- cache?: {
175
- /** Freshness window in milliseconds. Default `0`. */
176
- ttlMs?: number;
177
- /** Whether shared caches may store the response. Default `"private"`. */
178
- scope?: "public" | "private";
179
- };
180
-
181
- /**
182
- * Authorization key a task is bound to, derived from the request that created it.
183
- *
184
- * A task can only be read, answered or cancelled by a caller whose key matches.
185
- * The default is the authenticated subject, which is right for a
186
- * single-authority deployment and **not enough** for anything that authorizes on
187
- * more than identity: a tenant-scoped server where the same subject may act for
188
- * several tenants needs the tenant in the key, or a task created under one
189
- * tenant stays reachable from another.
190
- *
191
- * The framework cannot derive that itself — tenancy lives in a consumer's own
192
- * middleware — so it is a hook rather than a guess. Return a stable string; it is
193
- * compared verbatim.
194
- *
195
- * **It must derive everything from its two arguments.** `tasks/*` requests do
196
- * not run the middleware pipeline, so anything a middleware injects into the
197
- * pipeline context — the built-in tenant middleware's `tenantId`, for instance —
198
- * is NOT visible here. Read the header, or resolve it yourself; the hook may be
199
- * async precisely so a lookup is possible. A hook that expects pipeline state
200
- * silently sees `undefined` on every call, which collapses every caller onto one
201
- * key.
202
- *
203
- * Returning an empty or non-string value is refused rather than accepted, since
204
- * that is what the obvious implementation yields when the value it reads is
205
- * absent, and accepting it would share tasks between callers.
206
- *
207
- * Called on task creation and on every `tasks/get` / `tasks/update` /
208
- * `tasks/cancel`. It must return the same key for the same caller across those
209
- * calls, or the creator stops being able to reach its own task (fail-closed).
210
- *
211
- * @example
212
- * ```typescript
213
- * taskOwnerKey: (authInfo, request) =>
214
- * `${authInfo?.subject}@${request.headers.get("x-tenant-id")}`
215
- * ```
216
- */
217
- taskOwnerKey?: (
218
- authInfo: import("./auth/types.js").AuthInfo | undefined,
219
- request: Request,
220
- ) => string | Promise<string>;
221
-
222
- /**
223
- * Multi Round-Trip Requests (spec 2026-07-28, SEP-2322).
224
- *
225
- * Configures how `requestState` is protected when a tool handler asks the
226
- * client for input mid-call. Consulted by stateless HTTP and by the v2 stdio
227
- * serving entry. On a legacy stdio connection the SDK fulfils the embedded
228
- * requests through its compatibility shim, then re-enters the same verified
229
- * handler; application code keeps one MRTR contract across both eras.
230
- *
231
- * Without `signingKey`, `requestState` travels unprotected and the server logs
232
- * a warning at startup. That is only acceptable when tampering with it can
233
- * cause nothing worse than the request failing.
234
- */
235
- mrtr?: import("./mrtr/mod.js").MrtrOptions;
236
-
237
- /**
238
- * Protocol extensions this server declares (spec 2026-07-28).
239
- *
240
- * Keyed by reverse-DNS extension identifier — e.g.
241
- * `{ "io.modelcontextprotocol/tasks": {} }`. Surfaced under
242
- * `capabilities.extensions` on `server/discover` and `initialize`, and only
243
- * when non-empty: an empty object would assert "no extensions supported",
244
- * which is a claim the framework cannot make on a consumer's behalf.
245
- *
246
- * Declaring an extension here does not implement it — it advertises what the
247
- * consumer has wired up.
248
- */
249
- extensions?: Readonly<Record<string, unknown>>;
250
- }
251
-
252
- // ============================================
253
- // MCP Apps Types (SEP-1865)
254
- // ============================================
255
-
256
- /**
257
- * MCP Apps UI metadata for tools (SEP-1865 + PML extensions)
258
- *
259
- * Extends the base `McpUiToolMeta` from `@modelcontextprotocol/ext-apps`
260
- * (the official MCP Apps contract) with PML-specific `emits`/`accepts`
261
- * fields for cross-UI sync rules. The server narrows/extends the spec type;
262
- * the contract itself is owned upstream by the protocol, not by this repo.
263
- *
264
- * @example
265
- * ```typescript
266
- * const tool: MCPTool = {
267
- * name: "query_table",
268
- * description: "Query database table",
269
- * inputSchema: { ... },
270
- * _meta: {
271
- * ui: {
272
- * resourceUri: "ui://mcp-std/table-viewer",
273
- * emits: ["filter", "select"],
274
- * accepts: ["setData", "highlight"]
275
- * }
276
- * }
277
- * };
278
- * ```
279
- */
280
- export interface McpUiToolMeta extends McpUiToolMetaBase {
281
- /**
282
- * Resource URI for the UI. MUST use ui:// scheme.
283
- * Narrows the optional base field to required for server tools.
284
- * @example "ui://mcp-std/table-viewer"
285
- */
286
- resourceUri: string;
287
-
288
- /**
289
- * Events this UI can emit (PML extension for sync rules)
290
- * Used by PML orchestrator to build cross-UI event routing
291
- * @example ["filter", "select", "sort", "paginate"]
292
- */
293
- emits?: string[];
294
-
295
- /**
296
- * Events this UI can accept (PML extension for sync rules)
297
- * Used by PML orchestrator to build cross-UI event routing
298
- * @example ["setData", "highlight", "scrollTo"]
299
- */
300
- accepts?: string[];
301
- }
302
-
303
- /**
304
- * MCP Tool metadata container.
305
- *
306
- * Carries optional UI hints and routing metadata for MCP Apps (SEP-1865).
307
- */
308
- export interface MCPToolMeta {
309
- /** UI configuration for rendering this tool's output in an MCP App */
310
- ui?: McpUiToolMeta;
311
- }
312
-
313
- /**
314
- * MCP Resource definition for registration
315
- */
316
- export interface MCPResource {
317
- /**
318
- * Resource URI. SHOULD use ui:// scheme for MCP Apps.
319
- * @example "ui://mcp-std/table-viewer"
320
- */
321
- uri: string;
322
-
323
- /** Human-readable name */
324
- name: string;
325
-
326
- /** Description of the resource */
327
- description?: string;
328
-
329
- /** Optional display title, distinct from the protocol-required `name`. */
330
- title?: string;
331
-
332
- /** Optional visual hints advertised in `resources/list`. */
333
- icons?: Array<{
334
- src: string;
335
- mimeType?: string;
336
- sizes?: string[];
337
- theme?: "light" | "dark";
338
- }>;
339
-
340
- /** Optional client-facing resource annotations. */
341
- annotations?: {
342
- audience?: Array<"user" | "assistant">;
343
- priority?: number;
344
- lastModified?: string;
345
- };
346
-
347
- /** Optional protocol/extension metadata advertised in `resources/list`. */
348
- _meta?: Record<string, unknown>;
349
-
350
- /** MIME type, when known before the resource is read. */
351
- mimeType?: string;
352
-
353
- /**
354
- * Byte size of the resource when it is known.
355
- *
356
- * This is an exact byte-size attestation: when supplied, every read must
357
- * return exactly this many UTF-8 bytes for `text`, or decoded bytes for
358
- * `blob`. It is surfaced in `resources/list` so clients can make loading
359
- * decisions before reading. Must be a non-negative safe integer.
360
- */
361
- size?: number;
362
- }
363
-
364
- /**
365
- * Common fields of every resource response.
366
- */
367
- interface ResourceContentBase {
368
- /** URI of the resource. It must exactly match the URI that was requested. */
369
- uri: string;
370
- /** Non-empty MIME type of the content. */
371
- mimeType: string;
372
- /** Optional MCP metadata passed through to the protocol response. */
373
- _meta?: Record<string, unknown>;
374
- }
375
-
376
- /** A UTF-8/text resource response. */
377
- export interface TextResourceContent extends ResourceContentBase {
378
- /** Text payload, including HTML for MCP Apps. */
379
- text: string;
380
- /** Text and blob payloads are mutually exclusive. */
381
- blob?: never;
382
- }
383
-
384
- /** A binary resource response encoded as canonical standard base64. */
385
- export interface BlobResourceContent extends ResourceContentBase {
386
- /** Standard, padded base64 payload. */
387
- blob: string;
388
- /** Text and blob payloads are mutually exclusive. */
389
- text?: never;
390
- }
391
-
392
- /**
393
- * Content returned by a resource handler.
394
- *
395
- * Exactly one payload form is allowed: `text` for text/HTML, or `blob` for
396
- * binary content encoded as canonical standard base64. The framework validates
397
- * the same XOR contract at runtime before writing the response, which keeps
398
- * JavaScript consumers and unchecked handler results on the protocol-safe path.
399
- */
400
- export type ResourceContent = TextResourceContent | BlobResourceContent;
401
-
402
- /**
403
- * Resource handler callback
404
- *
405
- * @param uri - The requested resource URI as URL object
406
- * @returns A text or base64-blob ResourceContent whose URI matches `uri`
407
- *
408
- * @example
409
- * ```typescript
410
- * const handler: ResourceHandler = async (uri) => ({
411
- * uri: uri.toString(),
412
- * mimeType: MCP_APP_MIME_TYPE,
413
- * text: "<html>...</html>"
414
- * });
415
- *
416
- * // For binary content, return `blob` instead of `text`:
417
- * // { uri: uri.toString(), mimeType: "image/png", blob: "iVBORw0KGgo..." }
418
- * ```
419
- */
420
- export type ResourceHandler = (
421
- uri: URL,
422
- ) => Promise<ResourceContent> | ResourceContent;
423
-
424
- /** MCP Apps MIME type constant */
425
- export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app" as const;
426
-
427
- /** URI scheme for MCP Apps resources */
428
- export const MCP_APP_URI_SCHEME = "ui:" as const;
429
-
430
- /**
431
- * Well-known extension identifier for the MCP Apps protocol.
432
- *
433
- * Clients advertise MCP Apps support by including this key in
434
- * `clientCapabilities.extensions` (per the MCP SDK 1.29 extensions
435
- * feature). Servers read it via {@link getMcpAppsCapability} to decide
436
- * whether to register UI-rendering tools or fall back to text-only.
437
- *
438
- * @see {@link https://github.com/modelcontextprotocol/ext-apps | MCP Apps spec}
439
- */
440
- export const MCP_APPS_EXTENSION_ID = "io.modelcontextprotocol/ui" as const;
441
-
442
- /**
443
- * MCP Apps protocol spec version this package targets.
444
- *
445
- * Matches the dated spec at
446
- * https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx
447
- *
448
- * Bump this constant in the same commit that adopts a newer dated spec.
449
- */
450
- export const MCP_APPS_PROTOCOL_VERSION = "2026-01-26" as const;
451
-
452
- /**
453
- * MCP Apps capability advertised by a client.
454
- *
455
- * Returned by {@link getMcpAppsCapability} after reading
456
- * `clientCapabilities.extensions[MCP_APPS_EXTENSION_ID]`.
457
- *
458
- * The capability object is intentionally minimal — the spec keeps it
459
- * extensible by adding fields rather than removing them, so consumers
460
- * MUST tolerate unknown fields.
461
- */
462
- export interface McpAppsClientCapability {
463
- /**
464
- * MIME types the client can render as MCP Apps.
465
- *
466
- * Typically includes `"text/html;profile=mcp-app"`. An empty or
467
- * absent array means the client advertised support but listed no
468
- * concrete mime types — defensively assume nothing.
469
- */
470
- mimeTypes?: string[];
471
- }
472
-
473
- /**
474
- * Read the MCP Apps capability from a client's advertised capabilities.
475
- *
476
- * Best-effort, defensive reader. Returns `undefined` for any of:
477
- * - `null` / `undefined` input
478
- * - `clientCapabilities` without an `extensions` field
479
- * - `extensions` without the {@link MCP_APPS_EXTENSION_ID} key
480
- * - extension value that is not a plain object (string, number, null, ...)
481
- *
482
- * Malformed `mimeTypes` (wrong type, non-string entries) are silently
483
- * filtered rather than thrown — agents reading this function need a
484
- * predictable contract that never crashes downstream consumers on
485
- * untrusted client data.
486
- *
487
- * **Validation scope:** this function only validates the *type* of
488
- * `mimeTypes` entries (must be string). It does NOT validate that the
489
- * strings look like valid mime types (e.g. empty strings or garbage
490
- * content pass through). Consumers should compare against known
491
- * constants like {@link MCP_APP_MIME_TYPE} via `.includes()` rather
492
- * than treating the array as a generic allowlist.
493
- *
494
- * @param clientCapabilities - The `ClientCapabilities` object from the
495
- * MCP SDK initialize handshake. May be `null` or `undefined` if the
496
- * client never sent capabilities.
497
- * @returns The MCP Apps capability if the client advertised support,
498
- * otherwise `undefined`.
499
- *
500
- * @example
501
- * ```typescript
502
- * const cap = getMcpAppsCapability(client.getClientCapabilities());
503
- * if (cap?.mimeTypes?.includes(MCP_APP_MIME_TYPE)) {
504
- * // register UI-rendering tools
505
- * } else {
506
- * // register text-only fallback tools
507
- * }
508
- * ```
509
- */
510
- export function getMcpAppsCapability(
511
- clientCapabilities:
512
- | (Record<string, unknown> & { extensions?: Record<string, unknown> })
513
- | null
514
- | undefined,
515
- ): McpAppsClientCapability | undefined {
516
- if (clientCapabilities === null || clientCapabilities === undefined) {
517
- return undefined;
518
- }
519
- const extensions = clientCapabilities.extensions;
520
- if (extensions === null || typeof extensions !== "object") {
521
- return undefined;
522
- }
523
- const raw = extensions[MCP_APPS_EXTENSION_ID];
524
- if (raw === null || typeof raw !== "object") {
525
- return undefined;
526
- }
527
- // We have a capability object — extract known fields defensively.
528
- const result: McpAppsClientCapability = {};
529
- const rawMimeTypes = (raw as Record<string, unknown>).mimeTypes;
530
- if (Array.isArray(rawMimeTypes)) {
531
- const validMimeTypes = rawMimeTypes.filter(
532
- (m): m is string => typeof m === "string",
533
- );
534
- if (validMimeTypes.length > 0) {
535
- result.mimeTypes = validMimeTypes;
536
- }
537
- }
538
- return result;
539
- }
540
-
541
- // ============================================
542
- // MCP Tool Types
543
- // ============================================
544
-
545
- /**
546
- * Behavioural hints for model clients (MCP SDK 1.27 ToolAnnotations).
547
- * Passed through in tools/list so hosts can adapt their UI accordingly.
548
- */
549
- export interface ToolAnnotations {
550
- /** Short human-readable title, may differ from tool name */
551
- title?: string;
552
- /** If true, tool has no side-effects and is safe to call speculatively */
553
- readOnlyHint?: boolean;
554
- /** If true, executing may produce irreversible effects */
555
- destructiveHint?: boolean;
556
- /** If true, repeated calls with same args produce same result */
557
- idempotentHint?: boolean;
558
- /** If true, tool may interact with entities outside the MCP system */
559
- openWorldHint?: boolean;
560
- }
561
-
562
- /**
563
- * MCP Tool definition (compatible with MCP protocol)
564
- */
565
- export interface MCPTool {
566
- /** Tool name */
567
- name: string;
568
-
569
- /** Human-readable description */
570
- description: string;
571
-
572
- /** JSON Schema for tool input */
573
- inputSchema: Record<string, unknown>;
574
-
575
- /**
576
- * JSON Schema for the tool's structured output (MCP SDK 1.27).
577
- * Passed through in tools/list so hosts can validate tool results.
578
- */
579
- outputSchema?: Record<string, unknown>;
580
-
581
- /** Behavioural hints passed to model clients */
582
- annotations?: ToolAnnotations;
583
-
584
- /**
585
- * Tool metadata including UI configuration for MCP Apps
586
- * @see McpUiToolMeta
587
- */
588
- _meta?: MCPToolMeta;
589
-
590
- /**
591
- * Required OAuth scopes to call this tool.
592
- * Only enforced when auth is configured on the server.
593
- * If empty or undefined, no scope check is performed.
594
- */
595
- requiredScopes?: string[];
596
- }
597
-
598
- /**
599
- * Tool handler function.
600
- *
601
- * Receives validated arguments and returns a result (or throws).
602
- * The return value is serialised as JSON inside a `text` content block.
603
- *
604
- * **Security**: Never pass `args` values directly to shell commands or SQL.
605
- * Always validate / sanitise inside the handler or via `inputSchema`.
606
- *
607
- * @param args - Validated tool arguments from the MCP client
608
- * @returns Tool result (string, object, or Promise thereof)
609
- *
610
- * @example
611
- * ```typescript
612
- * const handler: ToolHandler = async (args) => {
613
- * const rows = await db.query(args.sql as string);
614
- * return { rows, count: rows.length };
615
- * };
616
- * ```
617
- */
618
- export interface ToolHandlerContext {
619
- readonly toolName: string;
620
- readonly request?: Request;
621
- readonly sessionId?: string;
622
- readonly authInfo?: import("./auth/types.js").AuthInfo;
623
- readonly clientInfo?: Implementation;
624
- readonly clientCapabilities?: ClientCapabilities;
625
-
626
- /**
627
- * Answers to a previous `InputRequiredResult`, keyed by the ids the server
628
- * assigned (spec 2026-07-28 MRTR).
629
- *
630
- * Present only on a retry. Read from `params.inputResponses` — a sibling of
631
- * `_meta`, not a member of it, unlike every other per-request field. Getting
632
- * that wrong yields a silent `undefined` even when the client sent them.
633
- */
634
- readonly inputResponses?: Record<string, unknown>;
635
-
636
- /**
637
- * True when the client echoed a `requestState` that passed integrity
638
- * verification, so the handler may trust this is a legitimate retry of its own
639
- * earlier request.
640
- *
641
- * The token carries no application state — it binds the principal, method,
642
- * argument digest and expiry. Since the digest guarantees the arguments are
643
- * byte-identical to the original call, a handler reconstructs its context from
644
- * those arguments rather than from the token.
645
- */
646
- readonly retryVerified?: boolean;
647
-
648
- /**
649
- * Log level requested for this call (spec 2026-07-28), read from
650
- * `params._meta["io.modelcontextprotocol/logLevel"]`.
651
- *
652
- * `undefined` means the client requested no logging. A handler **MUST NOT**
653
- * emit `notifications/message` in that case — the level is not a filter you
654
- * may default, it is the client's opt-in.
655
- */
656
- readonly logLevel?: import("./middleware/types.js").McpLogLevel;
657
- }
658
-
659
- export type ToolHandler = (
660
- args: Record<string, unknown>,
661
- ctx?: ToolHandlerContext,
662
- ) => Promise<unknown> | unknown;
663
-
664
- /**
665
- * Structured tool result: separates the LLM text summary (content)
666
- * from the machine-readable payload (structuredContent).
667
- *
668
- * When a ToolHandler returns this shape, the framework produces a
669
- * CallToolResult with both `content` and `structuredContent` set,
670
- * keeping heavy data out of the LLM context.
671
- */
672
- export interface StructuredToolResult {
673
- /** Human-readable summary shown in content[0].text */
674
- content: string;
675
- /** Structured data conforming to the tool's outputSchema */
676
- structuredContent: Record<string, unknown>;
677
- }
678
-
679
- /**
680
- * Maps a thrown error to either a business error result (isError: true)
681
- * or signals that the error should be re-thrown as a JSON-RPC error.
682
- *
683
- * @returns A message string to produce `{ isError: true }`, or null to rethrow.
684
- */
685
- export type ToolErrorMapper = (
686
- error: unknown,
687
- toolName: string,
688
- ) => string | null;
689
-
690
- /**
691
- * Sampling client interface — no-op as of 0.24.0. The SamplingBridge was
692
- * removed with MCP 2026-07-28. This type is kept for source compatibility
693
- * only and will be removed in 0.25.0.
694
- *
695
- * @deprecated No-op as of 0.24.0. Will be removed in 0.25.0.
696
- */
697
- export interface SamplingClient {
698
- /**
699
- * Request LLM completion from the client
700
- * @param params - Sampling parameters (messages, tools, etc.)
701
- * @returns Completion result with content and stop reason
702
- */
703
- createMessage(params: SamplingParams): Promise<SamplingResult>;
704
- }
705
-
706
- /**
707
- * Parameters for sampling request — no-op as of 0.24.0.
708
- *
709
- * @deprecated No-op as of 0.24.0. Will be removed in 0.25.0.
710
- */
711
- export interface SamplingParams {
712
- messages: Array<{ role: "user" | "assistant"; content: string }>;
713
- /** Tools available for the agent to use. Client handles execution. */
714
- tools?: Array<{
715
- name: string;
716
- description: string;
717
- inputSchema: Record<string, unknown>;
718
- }>;
719
- /** "auto" = LLM decides, "required" = must use tool, "none" = no tools */
720
- toolChoice?: "auto" | "required" | "none";
721
- maxTokens?: number;
722
- /** Hint for client: max agentic loop iterations */
723
- maxIterations?: number;
724
- /** Tool name patterns to filter (e.g., ['git_*', 'vfs_*']) */
725
- allowedToolPatterns?: string[];
726
- }
727
-
728
- /**
729
- * Result from sampling request — no-op as of 0.24.0.
730
- *
731
- * @deprecated No-op as of 0.24.0. Will be removed in 0.25.0.
732
- */
733
- export interface SamplingResult {
734
- content: Array<{
735
- type: string;
736
- text?: string;
737
- name?: string;
738
- input?: Record<string, unknown>;
739
- }>;
740
- stopReason: "end_turn" | "tool_use" | "max_tokens";
741
- }
742
-
743
- /**
744
- * Queue metrics for monitoring
745
- */
746
- export interface QueueMetrics {
747
- /** Number of requests currently executing */
748
- inFlight: number;
749
-
750
- /** Number of requests waiting in queue */
751
- queued: number;
752
- }
753
-
754
- /**
755
- * Promise resolver for pending requests
756
- */
757
- export interface PromiseResolver<T = unknown> {
758
- resolve: (value: T) => void;
759
- reject: (error: Error) => void;
760
- }
761
-
762
- /**
763
- * Request queue options
764
- */
765
- export interface QueueOptions {
766
- maxConcurrent: number;
767
- strategy: "sleep" | "queue" | "reject";
768
- sleepMs: number;
769
- }
770
-
771
- // ============================================
772
- // HTTP Server Types
773
- // ============================================
774
-
775
- /**
776
- * Context passed to HTTP rate limit key extractor
777
- */
778
- export interface HttpRateLimitContext {
779
- /** Client IP address (from x-forwarded-for/x-real-ip) */
780
- ip: string;
781
-
782
- /** HTTP method */
783
- method: string;
784
-
785
- /** HTTP path (e.g. /mcp) */
786
- path: string;
787
-
788
- /** HTTP headers */
789
- headers: Headers;
790
-
791
- /** MCP session ID, if present */
792
- sessionId?: string;
793
- }
794
-
795
- /**
796
- * HTTP rate limit configuration
797
- */
798
- export interface HttpRateLimitOptions {
799
- /** Maximum requests per window */
800
- maxRequests: number;
801
-
802
- /** Time window in milliseconds */
803
- windowMs: number;
804
-
805
- /**
806
- * Function to extract client identifier from HTTP context
807
- * Default: uses IP address
808
- */
809
- keyExtractor?: (context: HttpRateLimitContext) => string;
810
-
811
- /**
812
- * Behavior when rate limit is exceeded
813
- * - 'reject': Return error immediately
814
- * - 'wait': Wait for slot with backoff
815
- */
816
- onLimitExceeded?: "reject" | "wait";
817
- }
818
-
819
- /**
820
- * Options for starting an HTTP server
821
- */
822
- // Re-exported from the runtime port so consumers can import the canonical
823
- // fetch handler type from the same module as HttpServerOptions.
824
- export type { FetchHandler } from "./runtime/types.js";
825
- import type { FetchHandler } from "./runtime/types.js";
826
-
827
- export interface HttpServerOptions {
828
- /**
829
- * Port to listen on. Ignored when {@link embedded} is `true`.
830
- */
831
- port: number;
832
-
833
- /** Hostname to bind to (default: "0.0.0.0") */
834
- hostname?: string;
835
-
836
- /** Enable CORS (default: true) */
837
- cors?: boolean;
838
-
839
- /**
840
- * Allowed CORS origins (default: "*")
841
- * Use an allowlist in production.
842
- */
843
- corsOrigins?: "*" | string[];
844
-
845
- /**
846
- * Maximum request body size in bytes (default: 1_000_000).
847
- * Set to null to disable the limit.
848
- */
849
- maxBodyBytes?: number | null;
850
-
851
- /**
852
- * Require auth for HTTP mode. If true and auth is not configured, startHttp throws.
853
- */
854
- requireAuth?: boolean;
855
-
856
- /**
857
- * IP-based rate limiting for HTTP endpoints.
858
- */
859
- ipRateLimit?: HttpRateLimitOptions;
860
-
861
- /**
862
- * Custom HTTP routes registered alongside MCP protocol routes.
863
- * Uses Web standard Request/Response (no framework dependency).
864
- */
865
- customRoutes?: Array<{
866
- method: "get" | "post";
867
- path: string;
868
- handler: (req: Request) => Response | Promise<Response>;
869
- }>;
870
-
871
- /**
872
- * Callback when server is ready
873
- * @param info - Server address info
874
- */
875
- onListen?: (info: { hostname: string; port: number }) => void;
876
-
877
- /**
878
- * Embedded mode: skip binding a port and instead surface the Hono fetch
879
- * handler via the {@link embeddedHandlerCallback} option. Used by
880
- * {@link McpApp.getFetchHandler} so consumers (Fresh, Hono,
881
- * Express, etc.) can mount the MCP HTTP stack inside their own server
882
- * without giving up port ownership.
883
- *
884
- * When `true`, `port`, `hostname`, and `onListen` are ignored.
885
- */
886
- embedded?: boolean;
887
-
888
- /**
889
- * Receives the Hono fetch handler when running in embedded mode.
890
- * Required when {@link embedded} is `true`. Called exactly once,
891
- * synchronously, before `startHttp` returns.
892
- *
893
- * Most consumers should use {@link McpApp.getFetchHandler}
894
- * instead of setting this directly.
895
- */
896
- embeddedHandlerCallback?: (handler: FetchHandler) => void;
897
- }
898
-
899
- /**
900
- * HTTP server instance returned by startHttp
901
- */
902
- export interface HttpServerInstance {
903
- /** Shutdown the HTTP server */
904
- shutdown(): Promise<void>;
905
-
906
- /** Server address info */
907
- addr: { hostname: string; port: number };
908
- }