@casys/mcp-server 0.22.0 → 0.23.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.
@@ -12,6 +12,23 @@ import type {
12
12
  Implementation,
13
13
  } from "@modelcontextprotocol/sdk/types.js";
14
14
 
15
+ /**
16
+ * MCP logging severities (RFC 5424 syslog levels), ordered least to most severe.
17
+ *
18
+ * Declared locally rather than imported: the SDK's `LoggingLevel` is tied to the
19
+ * `logging/setLevel` RPC that spec 2026-07-28 removed, and this type now serves a
20
+ * per-request field instead.
21
+ */
22
+ export type McpLogLevel =
23
+ | "debug"
24
+ | "info"
25
+ | "notice"
26
+ | "warning"
27
+ | "error"
28
+ | "critical"
29
+ | "alert"
30
+ | "emergency";
31
+
15
32
  /**
16
33
  * Context passed through the middleware pipeline.
17
34
  * Each middleware can read and enrich the context.
@@ -35,6 +52,22 @@ export interface MiddlewareContext {
35
52
  /** Client capabilities metadata (stateless HTTP transport, when provided) */
36
53
  clientCapabilities?: ClientCapabilities;
37
54
 
55
+ /** MRTR: answers the client echoed back on a retry (spec 2026-07-28). */
56
+ inputResponses?: Record<string, unknown>;
57
+
58
+ /** MRTR: whether the echoed `requestState` passed integrity verification. */
59
+ retryVerified?: boolean;
60
+
61
+ /**
62
+ * Log level the client requested **for this request** (spec 2026-07-28).
63
+ *
64
+ * Replaces the removed `logging/setLevel` RPC: there is no server-wide level
65
+ * to mutate any more, so the level travels with the call that wants it. Absent
66
+ * means the client asked for no logging — and the spec is explicit that a
67
+ * server **MUST NOT** emit `notifications/message` in that case.
68
+ */
69
+ logLevel?: McpLogLevel;
70
+
38
71
  /** Extensible by middlewares (e.g., authInfo added by auth middleware) */
39
72
  [key: string]: unknown;
40
73
  }
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Capability check for MRTR inputRequests (spec 2026-07-28, SEP-2322).
3
+ *
4
+ * Rule 7 (MUST NOT): "Servers MUST NOT emit an inputRequest for a capability
5
+ * the client has not declared in io.modelcontextprotocol/clientCapabilities."
6
+ *
7
+ * In the stateless transport model, `clientCapabilities` is per-request: it
8
+ * arrives in `params._meta["io.modelcontextprotocol/clientCapabilities"]` and
9
+ * is therefore already parsed by the time this check runs. There is no session
10
+ * to cache it from — each call carries its own capability declaration.
11
+ *
12
+ * The function is pure: it takes the data it needs and returns a typed result.
13
+ * No network, no server state, no side effects.
14
+ *
15
+ * @module lib/server/mrtr/capability-check
16
+ */
17
+
18
+ import type { InputRequestEntry } from "./types.js";
19
+
20
+ // ── Types ─────────────────────────────────────────────────────────────────────
21
+
22
+ /** Successful capability check — all methods map to declared capabilities. */
23
+ export interface CapabilityCheckOk {
24
+ /**
25
+ * The canonical form of `inputRequests` — the value the caller MUST emit.
26
+ *
27
+ * Checking a JSON clone and then serialising the original is two serialisations,
28
+ * and a stateful `toJSON()` can return different values for each. That is not a
29
+ * theoretical gap: it reopens exactly the bypass canonicalisation was added to
30
+ * close. Emit this, not the input.
31
+ */
32
+ readonly canonicalRequests?: Record<string, unknown>;
33
+ readonly ok: true;
34
+ }
35
+
36
+ /** Failed capability check — one or more capabilities are missing. */
37
+ export interface CapabilityCheckFail {
38
+ /**
39
+ * Which fault this is.
40
+ *
41
+ * `missing_capability` — the client did not declare something the request needs.
42
+ * That is the client's to fix, and `-32021` says exactly that.
43
+ *
44
+ * `malformed` — the SERVER produced an input request that is structurally
45
+ * invalid: an unknown method, a missing or non-object `params`, a map that will
46
+ * not serialise. Reporting those as a missing capability tells the client to
47
+ * declare something it already has, and hides a server bug behind a client-facing
48
+ * error.
49
+ */
50
+ readonly kind: "missing_capability" | "malformed";
51
+ /**
52
+ * `ClientCapabilities`-shaped payload for the error's `data`, when the missing
53
+ * capability is nested. Absent for top-level ones, where the caller derives it
54
+ * from `missingCapabilities`.
55
+ */
56
+ readonly requiredCapabilities?: Record<string, unknown>;
57
+ readonly ok: false;
58
+ /**
59
+ * Top-level `ClientCapabilities` keys the client did not declare but the
60
+ * `inputRequests` map requires.
61
+ *
62
+ * Forward these directly into `-32021 MissingRequiredClientCapabilityError`
63
+ * as `data.requiredCapabilities` (spec 2026-07-28 §per-request protocol fields).
64
+ *
65
+ * Example: `["sampling", "elicitation"]` if both are absent.
66
+ */
67
+ readonly missingCapabilities: string[];
68
+ }
69
+
70
+ export type CapabilityCheckResult = CapabilityCheckOk | CapabilityCheckFail;
71
+
72
+ // ── Method → capability mapping ───────────────────────────────────────────────
73
+ //
74
+ // Spec 2026-07-28: only these three methods are legal in `inputRequests`.
75
+ // Any unrecognised method is treated as a missing capability (fail-safe): an
76
+ // unknown method is a server-authoring error, and the spec forbids emitting it
77
+ // on the wire. Rejecting it here prevents that wire violation.
78
+
79
+ /**
80
+ * The only methods an input request may carry, mapped to the capability each needs.
81
+ *
82
+ * Exported so the Tasks boundary enforces the same grammar. A task that requests
83
+ * input uses MRTR request shapes, and a second, looser list there is how a task
84
+ * ends up asking for a method no client implements — which strands it rather than
85
+ * failing it.
86
+ */
87
+ export const METHOD_TO_CAPABILITY: Readonly<Record<string, string>> = {
88
+ "elicitation/create": "elicitation",
89
+ "sampling/createMessage": "sampling",
90
+ "roots/list": "roots",
91
+ };
92
+
93
+ // ── checkInputRequestCapabilities ─────────────────────────────────────────────
94
+
95
+ /**
96
+ * Verify that every `inputRequest` entry maps to a capability the client declared.
97
+ *
98
+ * Mapping (spec 2026-07-28):
99
+ * elicitation/create → clientCapabilities.elicitation
100
+ * sampling/createMessage → clientCapabilities.sampling
101
+ * roots/list → clientCapabilities.roots
102
+ *
103
+ * Unknown methods fail-safe: the spec only permits the three methods above.
104
+ * An unknown method in `inputRequests` is a server-authoring bug and is
105
+ * rejected here before it reaches the wire.
106
+ *
107
+ * @param inputRequests - The map from the handler's `InputRequiredSignal`.
108
+ * @param clientCapabilities - Parsed from `params._meta[STATELESS_CLIENT_CAPABILITIES_KEY]`.
109
+ * `undefined` when the client sent no `_meta` at all —
110
+ * treated as "no capabilities declared".
111
+ * @returns `{ ok: true }` or `{ ok: false, missingCapabilities: string[] }`.
112
+ */
113
+ function isRecord(v: unknown): v is Record<string, unknown> {
114
+ return typeof v === "object" && v !== null && !Array.isArray(v);
115
+ }
116
+
117
+ /**
118
+ * Reduce a value to what it will actually be on the wire.
119
+ *
120
+ * The gate must inspect the JSON representation, not the live object: the two can
121
+ * differ. `new String("url")` is not `=== "url"` but serialises to `"url"`, and a
122
+ * `toJSON()` can introduce fields — `tools`, say — that exist only after
123
+ * serialisation. Checking the live object then shipping the serialised one means
124
+ * the check and the payload disagree, which is precisely the gap a caller would
125
+ * use to obtain an input request the client cannot service.
126
+ *
127
+ * Returns `undefined` when the value cannot be serialised at all, which callers
128
+ * treat as malformed.
129
+ */
130
+ function canonicalise(value: unknown): unknown {
131
+ try {
132
+ return JSON.parse(JSON.stringify(value ?? null));
133
+ } catch {
134
+ return undefined;
135
+ }
136
+ }
137
+
138
+ export function checkInputRequestCapabilities(
139
+ inputRequests: Record<string, InputRequestEntry>,
140
+ clientCapabilities: Record<string, unknown> | undefined,
141
+ ): CapabilityCheckResult {
142
+ // Collect every capability key that is required by the inputRequests.
143
+ // Use a Set to deduplicate: multiple slots may require the same capability.
144
+ // Canonicalise the WHOLE map once. Everything below inspects this clone, and the
145
+ // caller emits it — so the value checked and the value sent are the same object,
146
+ // serialised once.
147
+ const canonicalRequests = canonicalise(inputRequests);
148
+ if (!isRecord(canonicalRequests)) {
149
+ return {
150
+ ok: false,
151
+ kind: "malformed",
152
+ missingCapabilities: ["<inputRequests could not be serialised>"],
153
+ };
154
+ }
155
+
156
+ const required = new Set<string>();
157
+ for (const entry of Object.values(canonicalRequests) as InputRequestEntry[]) {
158
+ // Sub-capabilities: declaring `elicitation` does not grant URL mode, and
159
+ // declaring `sampling` does not grant tool-using sampling. Checking only the
160
+ // top-level key let a server ask for a mode the client cannot service, which
161
+ // strands the request exactly as an undeclared capability would.
162
+ // The map VALUE must itself be an object. `{ k: null }` serialises fine, so it
163
+ // survived canonicalisation and then threw on `entry.params` — landing in the
164
+ // generic tool-error path as a 200, not the 500 a malformed server output
165
+ // requires. Checked before anything dereferences it.
166
+ if (!isRecord(entry)) {
167
+ return {
168
+ ok: false,
169
+ kind: "malformed",
170
+ missingCapabilities: [
171
+ "<inputRequests values must be request objects>",
172
+ ],
173
+ };
174
+ }
175
+
176
+ // `method` must be a string, and looked up as an OWN key.
177
+ //
178
+ // Two distinct faults hid here. A non-string method — `{ toString: null }`
179
+ // survives JSON — throws a TypeError when used as a property key, landing in
180
+ // the generic tool-error path as a 200. And `"toString"` or `"constructor"`
181
+ // resolve INHERITED properties of the mapping object, so `capKey` came back
182
+ // as a function rather than undefined and produced a nonsense
183
+ // missing-capability error naming a method that does not exist.
184
+ if (typeof entry.method !== "string") {
185
+ return {
186
+ ok: false,
187
+ kind: "malformed",
188
+ missingCapabilities: ["<inputRequest method must be a string>"],
189
+ };
190
+ }
191
+
192
+ // Already canonical: `entry` came out of the clone above. A `params` that is
193
+ // present but not an object is malformed — reading it as `{}` would skip the
194
+ // sub-capability checks entirely, a server-authoring bug resolving to "no
195
+ // extra capability needed".
196
+ //
197
+ // `null` is rejected along with the rest, deliberately. I had intended to let
198
+ // it through as equivalent to "absent", but the two are not the same: omitting
199
+ // `params` says the request needs none, while `params: null` asserts a value
200
+ // that the schema types as an object. Accepting it would mean the sub-capability
201
+ // checks silently do not run for a request that looks like it declared
202
+ // something.
203
+ //
204
+ // Absence is method-specific: the schema requires `params` on
205
+ // `elicitation/create` (message + requestedSchema) and `sampling/createMessage`
206
+ // (messages + maxTokens). Only `ListRootsRequest` may omit it. Accepting an
207
+ // omission everywhere let a request ship that no client could service — it has
208
+ // nothing to render or sample.
209
+ if (entry.params === undefined && entry.method !== "roots/list") {
210
+ return {
211
+ ok: false,
212
+ kind: "malformed",
213
+ missingCapabilities: [
214
+ `<${entry.method} requires params>`,
215
+ ],
216
+ };
217
+ }
218
+ if (entry.params !== undefined && !isRecord(entry.params)) {
219
+ return {
220
+ ok: false,
221
+ kind: "malformed",
222
+ missingCapabilities: [
223
+ `<malformed inputRequest params for ${entry.method}>`,
224
+ ],
225
+ };
226
+ }
227
+ const params = isRecord(entry.params) ? entry.params : {};
228
+ if (entry.method === "elicitation/create" && params["mode"] === "url") {
229
+ const elicitation = isRecord(clientCapabilities?.["elicitation"])
230
+ ? clientCapabilities["elicitation"] as Record<string, unknown>
231
+ : undefined;
232
+ if (elicitation?.["url"] === undefined) {
233
+ return {
234
+ ok: false,
235
+ kind: "missing_capability",
236
+ missingCapabilities: ["elicitation.url"],
237
+ // Nested, matching ClientCapabilities. A flat "elicitation.url" key
238
+ // deserialises to `{}` on a typed client — it reads as "nothing
239
+ // missing", the opposite of the message.
240
+ requiredCapabilities: { elicitation: { url: {} } },
241
+ };
242
+ }
243
+ }
244
+ if (
245
+ entry.method === "sampling/createMessage" &&
246
+ (params["tools"] !== undefined || params["toolChoice"] !== undefined)
247
+ ) {
248
+ const sampling = isRecord(clientCapabilities?.["sampling"])
249
+ ? clientCapabilities["sampling"] as Record<string, unknown>
250
+ : undefined;
251
+ if (sampling?.["tools"] === undefined) {
252
+ return {
253
+ ok: false,
254
+ kind: "missing_capability",
255
+ missingCapabilities: ["sampling.tools"],
256
+ requiredCapabilities: { sampling: { tools: {} } },
257
+ };
258
+ }
259
+ }
260
+
261
+ const capKey = Object.hasOwn(METHOD_TO_CAPABILITY, entry.method)
262
+ ? METHOD_TO_CAPABILITY[entry.method]
263
+ : undefined;
264
+ if (capKey === undefined) {
265
+ // MRTR permits exactly three methods. An unknown one is invalid outright,
266
+ // so it must fail regardless of what the client declared — mapping it to
267
+ // its own name let a client "satisfy" it by declaring a capability of the
268
+ // same name, which is not a capability at all.
269
+ return {
270
+ ok: false,
271
+ kind: "malformed",
272
+ missingCapabilities: [
273
+ `<unsupported inputRequest method: ${entry.method}>`,
274
+ ],
275
+ };
276
+ }
277
+ required.add(capKey);
278
+ }
279
+
280
+ if (required.size === 0) {
281
+ // Empty inputRequests map — nothing to check
282
+ return { ok: true, canonicalRequests };
283
+ }
284
+
285
+ const missing: string[] = [];
286
+ for (const capKey of required) {
287
+ // The client "declared" the capability when its key is present in
288
+ // `clientCapabilities` with any value (including `{}`). An absent key or
289
+ // an undefined `clientCapabilities` object means "not declared".
290
+ const declared = clientCapabilities !== undefined &&
291
+ Object.hasOwn(clientCapabilities, capKey);
292
+ if (!declared) missing.push(capKey);
293
+ }
294
+
295
+ if (missing.length > 0) {
296
+ return {
297
+ ok: false,
298
+ kind: "missing_capability",
299
+ missingCapabilities: missing,
300
+ };
301
+ }
302
+ return { ok: true, canonicalRequests };
303
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * MRTR — Multi Round-Trip Requests (Track B, spec 2026-07-28, SEP-2322).
3
+ *
4
+ * Public re-export barrel. Import everything the transport layer needs from
5
+ * this single path rather than reaching into sub-modules directly.
6
+ *
7
+ * @module lib/server/mrtr
8
+ */
9
+
10
+ // Types shared across all MRTR code
11
+ export type {
12
+ InputRequestEntry,
13
+ InputRequestMethod,
14
+ InputRequiredSignal,
15
+ MrtrOptions,
16
+ } from "./types.js";
17
+
18
+ // requestState seal/verify (HMAC-SHA256 integrity protection)
19
+ export type {
20
+ RequestStatePayload,
21
+ RequestStateRejectionReason,
22
+ VerifyResult,
23
+ } from "./request-state.js";
24
+ export {
25
+ exportStateKey,
26
+ generateStateKey,
27
+ importStateKey,
28
+ paramsDigest,
29
+ sealRequestState,
30
+ verifyRequestState,
31
+ } from "./request-state.js";
32
+
33
+ // Capability check (spec rule 7 — MUST NOT emit for undeclared capabilities)
34
+ export type {
35
+ CapabilityCheckFail,
36
+ CapabilityCheckOk,
37
+ CapabilityCheckResult,
38
+ } from "./capability-check.js";
39
+ export { checkInputRequestCapabilities } from "./capability-check.js";