@casys/mcp-server 0.23.0 → 0.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +66 -22
- package/mod.ts +3 -3
- package/package.json +1 -1
- package/src/http/body.ts +72 -0
- package/src/http/request-guards.ts +137 -0
- package/src/http/wire.ts +41 -0
- package/src/mcp-app.ts +349 -984
- package/src/mrtr/mod.ts +7 -0
- package/src/mrtr/replay-store.ts +103 -0
- package/src/mrtr/types.ts +14 -0
- package/src/observability/metrics.ts +0 -42
- package/src/types.ts +20 -32
- package/src/validation/schema-validator.ts +56 -0
- package/src/sampling/sampling-bridge.ts +0 -193
package/src/mrtr/mod.ts
CHANGED
|
@@ -15,6 +15,13 @@ export type {
|
|
|
15
15
|
MrtrOptions,
|
|
16
16
|
} from "./types.js";
|
|
17
17
|
|
|
18
|
+
// Atomic single-use enforcement for verified requestState nonces.
|
|
19
|
+
export type {
|
|
20
|
+
MemoryMrtrReplayStoreOptions,
|
|
21
|
+
MrtrReplayStore,
|
|
22
|
+
} from "./replay-store.js";
|
|
23
|
+
export { MemoryMrtrReplayStore } from "./replay-store.js";
|
|
24
|
+
|
|
18
25
|
// requestState seal/verify (HMAC-SHA256 integrity protection)
|
|
19
26
|
export type {
|
|
20
27
|
RequestStatePayload,
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Atomic nonce consumption for MRTR requestState tokens.
|
|
3
|
+
*
|
|
4
|
+
* Integrity verification proves that a token was minted by the server and is
|
|
5
|
+
* bound to the current request. A replay store adds the separate single-use
|
|
6
|
+
* property by reserving the signed nonce before business logic runs.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Store used to consume a verified MRTR nonce exactly once.
|
|
11
|
+
*
|
|
12
|
+
* Implementations MUST make the check-and-reserve operation atomic. Return
|
|
13
|
+
* `true` only for the caller that reserved the nonce, `false` when it was
|
|
14
|
+
* already consumed, and throw when availability cannot be established.
|
|
15
|
+
*
|
|
16
|
+
* `expiresAt` is the signed token expiry as Unix epoch seconds. Stores should
|
|
17
|
+
* remove the reservation after that time; retaining it longer is safe but
|
|
18
|
+
* wastes capacity.
|
|
19
|
+
*
|
|
20
|
+
* A load-balanced deployment MUST provide one shared implementation to every
|
|
21
|
+
* McpApp instance. Redis can implement the contract with `SET key 1 NX EXAT`.
|
|
22
|
+
*/
|
|
23
|
+
export interface MrtrReplayStore {
|
|
24
|
+
consume(nonce: string, expiresAt: number): boolean | Promise<boolean>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface MemoryMrtrReplayStoreOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Maximum live reservations before the store fails closed.
|
|
30
|
+
*
|
|
31
|
+
* Default: 100,000.
|
|
32
|
+
*/
|
|
33
|
+
maxEntries?: number;
|
|
34
|
+
|
|
35
|
+
/** Test seam for the current Unix epoch time in seconds. */
|
|
36
|
+
nowSecs?: () => number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Process-local replay protection.
|
|
41
|
+
*
|
|
42
|
+
* This is the safe default for one continuously running McpApp process. It
|
|
43
|
+
* cannot coordinate separate processes or survive a restart; horizontally
|
|
44
|
+
* scaled or restart-safe deployments must inject a durable shared
|
|
45
|
+
* `MrtrReplayStore`.
|
|
46
|
+
*/
|
|
47
|
+
export class MemoryMrtrReplayStore implements MrtrReplayStore {
|
|
48
|
+
private readonly entries = new Map<string, number>();
|
|
49
|
+
private readonly maxEntries: number;
|
|
50
|
+
private readonly nowSecs: () => number;
|
|
51
|
+
|
|
52
|
+
constructor(options: MemoryMrtrReplayStoreOptions = {}) {
|
|
53
|
+
const maxEntries = options.maxEntries ?? 100_000;
|
|
54
|
+
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`MemoryMrtrReplayStore maxEntries must be a positive integer (got ${maxEntries})`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
this.maxEntries = maxEntries;
|
|
60
|
+
this.nowSecs = options.nowSecs ?? (() => Math.floor(Date.now() / 1000));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
consume(nonce: string, expiresAt: number): boolean {
|
|
64
|
+
if (!/^[0-9a-f]{32}$/.test(nonce)) {
|
|
65
|
+
throw new Error("MRTR replay nonce must be 32 lowercase hex characters");
|
|
66
|
+
}
|
|
67
|
+
if (!Number.isSafeInteger(expiresAt) || expiresAt < 0) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
"MRTR replay expiry must be a non-negative safe-integer Unix timestamp",
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const now = this.nowSecs();
|
|
74
|
+
if (!Number.isSafeInteger(now) || now < 0) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
"MRTR replay clock must return a non-negative safe-integer Unix timestamp",
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const existingExpiry = this.entries.get(nonce);
|
|
80
|
+
if (existingExpiry !== undefined) {
|
|
81
|
+
if (existingExpiry > now) return false;
|
|
82
|
+
this.entries.delete(nonce);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (expiresAt <= now) return false;
|
|
86
|
+
|
|
87
|
+
if (this.entries.size >= this.maxEntries) {
|
|
88
|
+
for (const [storedNonce, storedExpiry] of this.entries) {
|
|
89
|
+
if (storedExpiry <= now) this.entries.delete(storedNonce);
|
|
90
|
+
}
|
|
91
|
+
if (this.entries.size >= this.maxEntries) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`MRTR replay store capacity exceeded (${this.maxEntries} live nonces)`,
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// No await may occur between the check and this write. In one JS process,
|
|
99
|
+
// that makes the reservation atomic across concurrent request continuations.
|
|
100
|
+
this.entries.set(nonce, expiresAt);
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
}
|
package/src/mrtr/types.ts
CHANGED
|
@@ -90,4 +90,18 @@ export interface MrtrOptions {
|
|
|
90
90
|
* shared store on the first use).
|
|
91
91
|
*/
|
|
92
92
|
defaultTtlSecs?: number;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Atomic store used to reject a second use of the same signed requestState.
|
|
96
|
+
*
|
|
97
|
+
* With a signing key and no explicit store, McpApp uses a process-local
|
|
98
|
+
* MemoryMrtrReplayStore. That protects one continuously running process only:
|
|
99
|
+
* a restart loses its reservations. Every instance in a load-balanced
|
|
100
|
+
* deployment MUST receive the same durable shared store implementation.
|
|
101
|
+
*
|
|
102
|
+
* The nonce is consumed before the handler runs. This provides at-most-once
|
|
103
|
+
* admission, not exactly-once completion: if the handler commits a mutation
|
|
104
|
+
* and its response is lost, the same token is still rejected on retry.
|
|
105
|
+
*/
|
|
106
|
+
replayStore?: import("./replay-store.js").MrtrReplayStore;
|
|
93
107
|
}
|
|
@@ -60,8 +60,6 @@ export interface ServerMetricsSnapshot {
|
|
|
60
60
|
auth_success: number;
|
|
61
61
|
auth_failed: number;
|
|
62
62
|
auth_cache_hits: number;
|
|
63
|
-
sessions_created: number;
|
|
64
|
-
sessions_expired: number;
|
|
65
63
|
};
|
|
66
64
|
histograms: {
|
|
67
65
|
tool_call_duration_ms: Histogram;
|
|
@@ -69,8 +67,6 @@ export interface ServerMetricsSnapshot {
|
|
|
69
67
|
gauges: {
|
|
70
68
|
active_requests: number;
|
|
71
69
|
queued_requests: number;
|
|
72
|
-
active_sessions: number;
|
|
73
|
-
sse_clients: number;
|
|
74
70
|
rate_limiter_keys: number;
|
|
75
71
|
};
|
|
76
72
|
collected_at: number;
|
|
@@ -109,8 +105,6 @@ export class ServerMetrics {
|
|
|
109
105
|
private authSuccess = 0;
|
|
110
106
|
private authFailed = 0;
|
|
111
107
|
private authCacheHits = 0;
|
|
112
|
-
private sessionsCreated = 0;
|
|
113
|
-
private sessionsExpired = 0;
|
|
114
108
|
|
|
115
109
|
// Histogram
|
|
116
110
|
private toolCallDuration = createHistogram();
|
|
@@ -121,8 +115,6 @@ export class ServerMetrics {
|
|
|
121
115
|
// Gauges (set externally via setGauge)
|
|
122
116
|
private activeRequests = 0;
|
|
123
117
|
private queuedRequests = 0;
|
|
124
|
-
private activeSessions = 0;
|
|
125
|
-
private sseClients = 0;
|
|
126
118
|
private rateLimiterKeys = 0;
|
|
127
119
|
|
|
128
120
|
/**
|
|
@@ -166,22 +158,12 @@ export class ServerMetrics {
|
|
|
166
158
|
this.authCacheHits++;
|
|
167
159
|
}
|
|
168
160
|
|
|
169
|
-
recordSessionCreated(): void {
|
|
170
|
-
this.sessionsCreated++;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
recordSessionExpired(count: number): void {
|
|
174
|
-
this.sessionsExpired += count;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
161
|
/**
|
|
178
162
|
* Update gauge values (called periodically or on-demand)
|
|
179
163
|
*/
|
|
180
164
|
setGauges(gauges: {
|
|
181
165
|
activeRequests?: number;
|
|
182
166
|
queuedRequests?: number;
|
|
183
|
-
activeSessions?: number;
|
|
184
|
-
sseClients?: number;
|
|
185
167
|
rateLimiterKeys?: number;
|
|
186
168
|
}): void {
|
|
187
169
|
if (gauges.activeRequests !== undefined) {
|
|
@@ -190,10 +172,6 @@ export class ServerMetrics {
|
|
|
190
172
|
if (gauges.queuedRequests !== undefined) {
|
|
191
173
|
this.queuedRequests = gauges.queuedRequests;
|
|
192
174
|
}
|
|
193
|
-
if (gauges.activeSessions !== undefined) {
|
|
194
|
-
this.activeSessions = gauges.activeSessions;
|
|
195
|
-
}
|
|
196
|
-
if (gauges.sseClients !== undefined) this.sseClients = gauges.sseClients;
|
|
197
175
|
if (gauges.rateLimiterKeys !== undefined) {
|
|
198
176
|
this.rateLimiterKeys = gauges.rateLimiterKeys;
|
|
199
177
|
}
|
|
@@ -213,8 +191,6 @@ export class ServerMetrics {
|
|
|
213
191
|
auth_success: this.authSuccess,
|
|
214
192
|
auth_failed: this.authFailed,
|
|
215
193
|
auth_cache_hits: this.authCacheHits,
|
|
216
|
-
sessions_created: this.sessionsCreated,
|
|
217
|
-
sessions_expired: this.sessionsExpired,
|
|
218
194
|
},
|
|
219
195
|
histograms: {
|
|
220
196
|
tool_call_duration_ms: { ...this.toolCallDuration },
|
|
@@ -222,8 +198,6 @@ export class ServerMetrics {
|
|
|
222
198
|
gauges: {
|
|
223
199
|
active_requests: this.activeRequests,
|
|
224
200
|
queued_requests: this.queuedRequests,
|
|
225
|
-
active_sessions: this.activeSessions,
|
|
226
|
-
sse_clients: this.sseClients,
|
|
227
201
|
rate_limiter_keys: this.rateLimiterKeys,
|
|
228
202
|
},
|
|
229
203
|
collected_at: Date.now(),
|
|
@@ -285,16 +259,6 @@ export class ServerMetrics {
|
|
|
285
259
|
"Auth token cache hits",
|
|
286
260
|
m.counters.auth_cache_hits,
|
|
287
261
|
);
|
|
288
|
-
counter(
|
|
289
|
-
"sessions_created_total",
|
|
290
|
-
"Sessions created",
|
|
291
|
-
m.counters.sessions_created,
|
|
292
|
-
);
|
|
293
|
-
counter(
|
|
294
|
-
"sessions_expired_total",
|
|
295
|
-
"Sessions expired by cleanup",
|
|
296
|
-
m.counters.sessions_expired,
|
|
297
|
-
);
|
|
298
262
|
|
|
299
263
|
// --- Per-tool counters ---
|
|
300
264
|
lines.push(`# HELP ${prefix}_tool_calls_by_name Tool calls by tool name`);
|
|
@@ -340,8 +304,6 @@ export class ServerMetrics {
|
|
|
340
304
|
"Requests waiting in queue",
|
|
341
305
|
m.gauges.queued_requests,
|
|
342
306
|
);
|
|
343
|
-
gauge("active_sessions", "Active HTTP sessions", m.gauges.active_sessions);
|
|
344
|
-
gauge("sse_clients", "Connected SSE clients", m.gauges.sse_clients);
|
|
345
307
|
gauge(
|
|
346
308
|
"rate_limiter_keys",
|
|
347
309
|
"Tracked rate limiter keys",
|
|
@@ -364,14 +326,10 @@ export class ServerMetrics {
|
|
|
364
326
|
this.authSuccess = 0;
|
|
365
327
|
this.authFailed = 0;
|
|
366
328
|
this.authCacheHits = 0;
|
|
367
|
-
this.sessionsCreated = 0;
|
|
368
|
-
this.sessionsExpired = 0;
|
|
369
329
|
this.toolCallDuration = createHistogram();
|
|
370
330
|
this.perTool.clear();
|
|
371
331
|
this.activeRequests = 0;
|
|
372
332
|
this.queuedRequests = 0;
|
|
373
|
-
this.activeSessions = 0;
|
|
374
|
-
this.sseClients = 0;
|
|
375
333
|
this.rateLimiterKeys = 0;
|
|
376
334
|
this.startTime = Date.now();
|
|
377
335
|
}
|
package/src/types.ts
CHANGED
|
@@ -80,8 +80,9 @@ export interface McpAppOptions {
|
|
|
80
80
|
validateSchema?: boolean;
|
|
81
81
|
|
|
82
82
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
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.
|
|
85
86
|
*/
|
|
86
87
|
enableSampling?: boolean;
|
|
87
88
|
|
|
@@ -92,8 +93,9 @@ export interface McpAppOptions {
|
|
|
92
93
|
instructions?: string;
|
|
93
94
|
|
|
94
95
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
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.
|
|
97
99
|
*/
|
|
98
100
|
samplingClient?: SamplingClient;
|
|
99
101
|
|
|
@@ -144,27 +146,14 @@ export interface McpAppOptions {
|
|
|
144
146
|
expectResources?: boolean;
|
|
145
147
|
|
|
146
148
|
/**
|
|
147
|
-
* HTTP transport mode
|
|
149
|
+
* HTTP transport mode. Only `"stateless"` is supported as of spec 2026-07-28.
|
|
148
150
|
*
|
|
149
|
-
* -
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
* `Mcp-Session-Id`. `protocolVersion` is read from
|
|
154
|
-
* `params._meta["io.modelcontextprotocol/protocolVersion"]` on every
|
|
155
|
-
* request. `GET /mcp` returns 405 (Track G replaces the SSE channel with
|
|
156
|
-
* `subscriptions/listen`).
|
|
157
|
-
*
|
|
158
|
-
* The mode does **not** gate the spec-2026-07-28 result envelope — the
|
|
159
|
-
* negotiated version does. `"stateless"` also accepts `2025-06-18` and
|
|
160
|
-
* `2025-11-25`, and a peer on one of those gets the legacy shape over this same
|
|
161
|
-
* transport. `"stateful"` advertises `2025-06-18` and negotiates nothing
|
|
162
|
-
* per-request, so it never carries the envelope.
|
|
163
|
-
*
|
|
164
|
-
* Default: `"stateful"`.
|
|
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.
|
|
165
155
|
*/
|
|
166
|
-
|
|
167
|
-
transport?: "stateful" | "stateless";
|
|
156
|
+
transport?: "stateless";
|
|
168
157
|
|
|
169
158
|
/**
|
|
170
159
|
* Cache hints emitted on list and read results (spec 2026-07-28,
|
|
@@ -638,10 +627,11 @@ export type ToolErrorMapper = (
|
|
|
638
627
|
) => string | null;
|
|
639
628
|
|
|
640
629
|
/**
|
|
641
|
-
* Sampling client interface
|
|
642
|
-
*
|
|
630
|
+
* Sampling client interface — no-op as of 0.24.0. The SamplingBridge was
|
|
631
|
+
* removed with MCP 2026-07-28. This type is kept for source compatibility
|
|
632
|
+
* only and will be removed in 0.25.0.
|
|
643
633
|
*
|
|
644
|
-
* @deprecated
|
|
634
|
+
* @deprecated No-op as of 0.24.0. Will be removed in 0.25.0.
|
|
645
635
|
*/
|
|
646
636
|
export interface SamplingClient {
|
|
647
637
|
/**
|
|
@@ -653,10 +643,9 @@ export interface SamplingClient {
|
|
|
653
643
|
}
|
|
654
644
|
|
|
655
645
|
/**
|
|
656
|
-
* Parameters for sampling request
|
|
657
|
-
* Compatible with MCP sampling protocol
|
|
646
|
+
* Parameters for sampling request — no-op as of 0.24.0.
|
|
658
647
|
*
|
|
659
|
-
* @deprecated
|
|
648
|
+
* @deprecated No-op as of 0.24.0. Will be removed in 0.25.0.
|
|
660
649
|
*/
|
|
661
650
|
export interface SamplingParams {
|
|
662
651
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
@@ -676,10 +665,9 @@ export interface SamplingParams {
|
|
|
676
665
|
}
|
|
677
666
|
|
|
678
667
|
/**
|
|
679
|
-
* Result from sampling request
|
|
680
|
-
* Compatible with MCP sampling protocol
|
|
668
|
+
* Result from sampling request — no-op as of 0.24.0.
|
|
681
669
|
*
|
|
682
|
-
* @deprecated
|
|
670
|
+
* @deprecated No-op as of 0.24.0. Will be removed in 0.25.0.
|
|
683
671
|
*/
|
|
684
672
|
export interface SamplingResult {
|
|
685
673
|
content: Array<{
|
|
@@ -28,6 +28,16 @@ interface AjvValidateFunction {
|
|
|
28
28
|
errors?: AjvErrorObject[] | null;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* Count with its noun, agreeing in number.
|
|
33
|
+
*
|
|
34
|
+
* A bound of 1 is a legitimate schema (`minItems: 1`), and "must have at least
|
|
35
|
+
* 1 items" reads as a bug in the server rather than a problem with the input.
|
|
36
|
+
*/
|
|
37
|
+
function plural(n: number, singular: string, plural = `${singular}s`): string {
|
|
38
|
+
return `${n} ${n === 1 ? singular : plural}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
31
41
|
/**
|
|
32
42
|
* Validation error with formatted message
|
|
33
43
|
*/
|
|
@@ -205,6 +215,52 @@ export class SchemaValidator {
|
|
|
205
215
|
expected = param.pattern;
|
|
206
216
|
break;
|
|
207
217
|
|
|
218
|
+
// Collection bounds. ajv enforces these already — what was missing is a
|
|
219
|
+
// message shaped like the others, with a structured `expected`. Without
|
|
220
|
+
// it these fell through to `default` and surfaced ajv's bare prose
|
|
221
|
+
// ("must NOT have more than 8 items"), which states the limit but names
|
|
222
|
+
// neither the property nor an `expected` a caller can act on.
|
|
223
|
+
//
|
|
224
|
+
// `expected` says "items"/"properties" rather than "length": it is read
|
|
225
|
+
// on its own as a recovery hint, where "length <= 8" is indistinguishable
|
|
226
|
+
// from the character bound that minLength/maxLength above produce.
|
|
227
|
+
case "minItems":
|
|
228
|
+
message = `Property ${path} must have at least ${
|
|
229
|
+
plural(param.limit, "item")
|
|
230
|
+
}`;
|
|
231
|
+
expected = `items >= ${param.limit}`;
|
|
232
|
+
break;
|
|
233
|
+
|
|
234
|
+
case "maxItems":
|
|
235
|
+
message = `Property ${path} must have at most ${
|
|
236
|
+
plural(param.limit, "item")
|
|
237
|
+
}`;
|
|
238
|
+
expected = `items <= ${param.limit}`;
|
|
239
|
+
break;
|
|
240
|
+
|
|
241
|
+
case "uniqueItems":
|
|
242
|
+
// ajv reports the two colliding array indices, zero-based, and in
|
|
243
|
+
// either order depending on how it optimised the comparison. The
|
|
244
|
+
// indices are not what is equal — the items at them are.
|
|
245
|
+
message =
|
|
246
|
+
`Property ${path} must not contain duplicate items (items at indices ${param.j} and ${param.i} are equal)`;
|
|
247
|
+
expected = "unique items";
|
|
248
|
+
break;
|
|
249
|
+
|
|
250
|
+
case "minProperties":
|
|
251
|
+
message = `Property ${path} must have at least ${
|
|
252
|
+
plural(param.limit, "property", "properties")
|
|
253
|
+
}`;
|
|
254
|
+
expected = `properties >= ${param.limit}`;
|
|
255
|
+
break;
|
|
256
|
+
|
|
257
|
+
case "maxProperties":
|
|
258
|
+
message = `Property ${path} must have at most ${
|
|
259
|
+
plural(param.limit, "property", "properties")
|
|
260
|
+
}`;
|
|
261
|
+
expected = `properties <= ${param.limit}`;
|
|
262
|
+
break;
|
|
263
|
+
|
|
208
264
|
case "additionalProperties":
|
|
209
265
|
message = `Unknown property: ${param.additionalProperty}`;
|
|
210
266
|
break;
|
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sampling Bridge for Bidirectional LLM Communication
|
|
3
|
-
*
|
|
4
|
-
* Enables MCP servers to delegate complex tasks back to the client's LLM
|
|
5
|
-
* via the sampling protocol. Manages pending requests with timeout and
|
|
6
|
-
* response routing.
|
|
7
|
-
*
|
|
8
|
-
* @module lib/server/sampling-bridge
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import type {
|
|
12
|
-
PromiseResolver,
|
|
13
|
-
SamplingClient,
|
|
14
|
-
SamplingParams,
|
|
15
|
-
SamplingResult,
|
|
16
|
-
} from "../types.js";
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* SamplingBridge manages bidirectional sampling requests
|
|
20
|
-
*
|
|
21
|
-
* Features:
|
|
22
|
-
* - Request/response correlation via unique IDs
|
|
23
|
-
* - Automatic timeout for pending requests (60s default)
|
|
24
|
-
* - Promise-based async/await API
|
|
25
|
-
* - Support for both Anthropic and OpenAI sampling
|
|
26
|
-
*
|
|
27
|
-
* @deprecated Deprecated (MCP 2026-07-28). Removal after 2027-07-28. Prefer the explicit handle-based pattern.
|
|
28
|
-
*
|
|
29
|
-
* @example
|
|
30
|
-
* ```typescript
|
|
31
|
-
* const bridge = new SamplingBridge(samplingClient);
|
|
32
|
-
*
|
|
33
|
-
* // Delegate task to LLM
|
|
34
|
-
* const result = await bridge.requestSampling({
|
|
35
|
-
* messages: [{ role: 'user', content: 'Analyze this data...' }]
|
|
36
|
-
* });
|
|
37
|
-
* ```
|
|
38
|
-
*/
|
|
39
|
-
export class SamplingBridge {
|
|
40
|
-
private pendingRequests = new Map<number, PromiseResolver<SamplingResult>>();
|
|
41
|
-
private nextId = 1;
|
|
42
|
-
private samplingClient: SamplingClient;
|
|
43
|
-
private defaultTimeout = 60000; // 60 seconds
|
|
44
|
-
|
|
45
|
-
constructor(client: SamplingClient, options?: { timeout?: number }) {
|
|
46
|
-
this.samplingClient = client;
|
|
47
|
-
if (options?.timeout) {
|
|
48
|
-
this.defaultTimeout = options.timeout;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Request sampling from the client's LLM
|
|
54
|
-
*
|
|
55
|
-
* @param params - Sampling parameters (messages, model preferences, etc.)
|
|
56
|
-
* @param timeout - Override default timeout (ms)
|
|
57
|
-
* @returns Promise that resolves with sampling result
|
|
58
|
-
* @throws {Error} If request times out or client fails
|
|
59
|
-
*/
|
|
60
|
-
async requestSampling(
|
|
61
|
-
params: SamplingParams,
|
|
62
|
-
timeout?: number,
|
|
63
|
-
): Promise<SamplingResult> {
|
|
64
|
-
const id = this.nextId++;
|
|
65
|
-
const timeoutMs = timeout ?? this.defaultTimeout;
|
|
66
|
-
|
|
67
|
-
// Create timeout promise for race condition
|
|
68
|
-
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
69
|
-
const timeoutPromise = new Promise<never>((_, reject) => {
|
|
70
|
-
timeoutId = setTimeout(() => {
|
|
71
|
-
this.pendingRequests.delete(id);
|
|
72
|
-
reject(
|
|
73
|
-
new Error(`Sampling request ${id} timed out after ${timeoutMs}ms`),
|
|
74
|
-
);
|
|
75
|
-
}, timeoutMs);
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
// Track pending request for potential external response handling
|
|
79
|
-
const resultPromise = new Promise<SamplingResult>((resolve, reject) => {
|
|
80
|
-
this.pendingRequests.set(id, { resolve, reject });
|
|
81
|
-
});
|
|
82
|
-
|
|
83
|
-
try {
|
|
84
|
-
// Race between client response and timeout
|
|
85
|
-
// Also race with external response via handleResponse()
|
|
86
|
-
const clientPromise = this.samplingClient.createMessage(params);
|
|
87
|
-
const result = await Promise.race([
|
|
88
|
-
clientPromise.then((r) => {
|
|
89
|
-
// Resolve the pending request tracker as well
|
|
90
|
-
const pending = this.pendingRequests.get(id);
|
|
91
|
-
if (pending) {
|
|
92
|
-
pending.resolve(r);
|
|
93
|
-
}
|
|
94
|
-
return r;
|
|
95
|
-
}),
|
|
96
|
-
timeoutPromise,
|
|
97
|
-
resultPromise, // Allow external handleResponse() to resolve
|
|
98
|
-
]);
|
|
99
|
-
return result;
|
|
100
|
-
} catch (error) {
|
|
101
|
-
// Clean up pending request on error
|
|
102
|
-
this.pendingRequests.delete(id);
|
|
103
|
-
throw error;
|
|
104
|
-
} finally {
|
|
105
|
-
// Always clear timeout to prevent memory leak
|
|
106
|
-
if (timeoutId) {
|
|
107
|
-
clearTimeout(timeoutId);
|
|
108
|
-
}
|
|
109
|
-
// Clean up pending request
|
|
110
|
-
this.pendingRequests.delete(id);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Handle sampling response from client (for bidirectional stdio)
|
|
116
|
-
*
|
|
117
|
-
* Used when MCP server receives sampling responses via stdin.
|
|
118
|
-
* Resolves the corresponding pending promise.
|
|
119
|
-
*
|
|
120
|
-
* @param id - Request ID from original sampling request
|
|
121
|
-
* @param result - Sampling result from client
|
|
122
|
-
*/
|
|
123
|
-
handleResponse(id: number, result: SamplingResult): void {
|
|
124
|
-
const pending = this.pendingRequests.get(id);
|
|
125
|
-
|
|
126
|
-
if (!pending) {
|
|
127
|
-
console.error(
|
|
128
|
-
`[SamplingBridge] Received response for unknown request: ${id}`,
|
|
129
|
-
);
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
this.pendingRequests.delete(id);
|
|
134
|
-
pending.resolve(result);
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Handle sampling error from client
|
|
139
|
-
*
|
|
140
|
-
* @param id - Request ID
|
|
141
|
-
* @param error - Error from client
|
|
142
|
-
*/
|
|
143
|
-
handleError(id: number, error: Error): void {
|
|
144
|
-
const pending = this.pendingRequests.get(id);
|
|
145
|
-
|
|
146
|
-
if (!pending) {
|
|
147
|
-
console.error(
|
|
148
|
-
`[SamplingBridge] Received error for unknown request: ${id}`,
|
|
149
|
-
);
|
|
150
|
-
return;
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
this.pendingRequests.delete(id);
|
|
154
|
-
pending.reject(error);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* Get count of pending sampling requests
|
|
159
|
-
*/
|
|
160
|
-
getPendingCount(): number {
|
|
161
|
-
return this.pendingRequests.size;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
/**
|
|
165
|
-
* Cancel all pending requests (useful for shutdown)
|
|
166
|
-
*/
|
|
167
|
-
cancelAll(): void {
|
|
168
|
-
for (const [id, pending] of this.pendingRequests.entries()) {
|
|
169
|
-
pending.reject(
|
|
170
|
-
new Error(`Sampling request ${id} cancelled (server shutdown)`),
|
|
171
|
-
);
|
|
172
|
-
}
|
|
173
|
-
this.pendingRequests.clear();
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Get sampling client for direct access
|
|
178
|
-
*/
|
|
179
|
-
getClient(): SamplingClient {
|
|
180
|
-
return this.samplingClient;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
/**
|
|
184
|
-
* Alias for requestSampling() - implements SamplingClient interface
|
|
185
|
-
* This allows the bridge to be used as a drop-in replacement for SamplingClient
|
|
186
|
-
*
|
|
187
|
-
* @param params - Sampling parameters
|
|
188
|
-
* @returns Sampling result
|
|
189
|
-
*/
|
|
190
|
-
createMessage(params: SamplingParams): Promise<SamplingResult> {
|
|
191
|
-
return this.requestSampling(params);
|
|
192
|
-
}
|
|
193
|
-
}
|