Repository navigation
Expand file tree
/
Copy pathcomposable-test-server.ts
More file actions
2057 lines (1934 loc) · 79.8 KB
/
Copy pathcomposable-test-server.ts
File metadata and controls
2057 lines (1934 loc) · 79.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Composable Test Server
*
* Provides types and functions for creating MCP test servers from configuration.
* This allows composing MCP test servers with different capabilities, tools, resources, and prompts.
*/
import * as z from "zod/v4";
import {
McpServer,
ResourceTemplate as SdkResourceTemplate,
completable,
isCompletable,
isInputRequiredResult,
} from "@modelcontextprotocol/server";
import {
setResourceText,
type ResourceUpdateBroadcast,
} from "./resource-update-broadcast.js";
import type {
Implementation,
Tool,
Resource,
ResourceTemplateType as ResourceTemplate,
Prompt,
CallToolResult,
InputRequiredResult,
PromptArgument,
RegisteredTool,
RegisteredResource,
RegisteredPrompt,
RegisteredResourceTemplate,
ServerContext,
ServerCapabilities,
Task,
GetTaskResult,
ListTasksResult,
ListToolsResult,
ListResourcesResult,
ListResourceTemplatesResult,
ListPromptsResult,
} from "@modelcontextprotocol/server";
import {
GetTaskRequestSchema,
GetTaskPayloadRequestSchema,
CancelTaskRequestSchema,
ListTasksRequestSchema,
TaskStatusNotificationSchema,
} from "@modelcontextprotocol/core";
import {
TASKS_EXTENSION_KEY,
ModernTaskRuntime,
createModernTaskTools,
wireModernTaskHandlers,
} from "./modern-tasks.js";
import { SKILLS_EXTENSION_KEY, wireSkillsHandlers } from "./skills.js";
import {
EVENTS_EXTENSION_KEY,
EventsRuntime,
createEventsControlTools,
type EventsConfig,
} from "./events.js";
import type { StallableOAuthEndpoint } from "./test-server-oauth.js";
/**
* MCP Apps extension id. Hardcoded for the same reason the Inspector's
* `core/mcp/extensions.ts` hardcodes it: the constant lives on ext-apps'
* `/server` subpath, and the test servers have no reason to depend on it.
*/
const UI_EXTENSION_KEY = "io.modelcontextprotocol/ui";
// Empty object JSON schema constant (from SDK's mcp.js)
const EMPTY_OBJECT_JSON_SCHEMA = {
type: "object",
properties: {},
} as const;
// A raw arg shape: field name → zod schema. Using the full `z.ZodType` (not
// `z.ZodRawShape`, which is a readonly `$ZodType` map) keeps it assignable to the
// SDK's `registerTool`/`registerPrompt` raw-shape overloads and mutable for the
// completable() wrapping below.
type ToolInputSchema = Record<string, z.ZodType>;
type PromptArgsSchema = Record<string, z.ZodType>;
/**
* Back-compat handler `extra` shape.
*
* SDK v2 removed `RequestHandlerExtra`; low-level handlers now receive a
* {@link ServerContext} whose per-request data lives under `ctx.mcpReq`. This
* type is the flattened view the composable test-server tool/resource/task
* handlers consume, rebuilt from `ctx.mcpReq` by {@link toHandlerExtra}.
*/
export interface HandlerExtra {
/** `_meta` sent with the request params (e.g. `_meta.progressToken`). */
_meta?: Record<string, unknown>;
/** The inbound JSON-RPC request id (for `relatedRequestId` on notifications). */
requestId?: string | number;
/** Abort signal for the in-flight request. */
signal?: AbortSignal;
/** Send a server→client request (`sampling/createMessage`, `elicitation/create`, `tasks/*`, …). */
sendRequest?: <T extends z.core.$ZodType>(
request: { method: string; params?: Record<string, unknown> },
resultSchema: T,
) => Promise<z.output<T>>;
/** Send a server→client notification. */
sendNotification?: (notification: {
method: string;
params?: Record<string, unknown>;
}) => Promise<void>;
/**
* Request-scoped, threshold-gated logging (the SDK's `ctx.mcpReq.log`). Emits
* a `notifications/message` only when the connection's negotiated level admits
* it — the modern per-request `logLevel` opt-in, or the legacy session level —
* and streams it on this request's response. Prefer over {@link sendNotification}
* for server logs so the era-correct gating is applied for you.
*/
log?: (level: string, data: unknown, logger?: string) => Promise<void> | void;
/**
* MRTR (2026-07-28): the bare input responses a retried request echoes back,
* keyed by the identifiers the server assigned in `inputRequests`. Present
* only on the retry round, so an MRTR tool branches on it to distinguish the
* original call (return `inputRequired(...)`) from the retry (return the final
* result). Undefined on legacy connections and on the first round.
*/
inputResponses?: Record<string, unknown>;
/** MRTR: the opaque `requestState` the client echoed on retry (resolved value). */
requestState?: unknown;
/**
* The inbound HTTP request's headers, on an HTTP transport (`ctx.http.req`).
* Undefined on stdio. Lets a fixture report what actually arrived on the
* wire — e.g. whether a SEP-2792 `Accept-Language` mirror agrees with the
* request's `_meta` (#2979).
*/
requestHeaders?: Headers;
}
/** Minimal structural view of `ctx.mcpReq` for building {@link HandlerExtra}. */
interface McpReqContext {
mcpReq?: {
id?: string | number;
_meta?: Record<string, unknown>;
signal?: AbortSignal;
send?: HandlerExtra["sendRequest"];
notify?: HandlerExtra["sendNotification"];
/**
* Request-scoped logging helper the SDK adds in `McpServer.buildContext`.
* It applies the era-correct threshold gating for us: on the modern
* (2026-07-28) leg it reads the per-request `logLevel` opt-in from the
* request envelope and drops the message when the client didn't opt in or
* the level is below the requested severity; on legacy it honors the
* session level from `logging/setLevel`. Emits through `notify`, so on the
* modern leg the response upgrades to SSE and the log rides this request's
* stream. Prefer this over a raw `notify`/`notification` for logs.
*/
log?: HandlerExtra["log"];
/** MRTR input responses on a retried request (2026-07-28). */
inputResponses?: Record<string, unknown>;
/** MRTR request-state accessor (resolves the echoed opaque token). */
requestState?: () => unknown;
};
}
/** Rebuild the legacy flattened `extra` object from a v2 {@link ServerContext}. */
function toHandlerExtra(ctx: ServerContext | undefined): HandlerExtra {
const mcpReq = (ctx as McpReqContext | undefined)?.mcpReq;
return {
_meta: mcpReq?._meta,
requestId: mcpReq?.id,
signal: mcpReq?.signal,
sendRequest: mcpReq?.send,
sendNotification: mcpReq?.notify,
log: mcpReq?.log?.bind(mcpReq),
inputResponses: mcpReq?.inputResponses,
requestState: mcpReq?.requestState?.(),
requestHeaders: ctx?.http?.req?.headers,
};
}
/**
* Derive `prompts/list` argument descriptors from a raw zod arg shape.
* Replaces the SDK's removed `getObjectShape` / `getSchemaDescription` /
* `isSchemaOptional` compat helpers. A field is `required` unless it accepts
* `undefined` (i.e. it is `.optional()` / `.default()` / nullish).
*/
function promptArgumentsFromRawShape(
shape: Record<string, z.ZodType> | undefined,
): PromptArgument[] | undefined {
if (!shape) return undefined;
return Object.entries(shape).map(([name, field]) => {
const schema = field as z.ZodType;
const acceptsUndefined = schema.safeParse(undefined).success;
return {
name,
description: schema.description,
required: !acceptsUndefined,
} as PromptArgument;
});
}
interface ServerState {
registeredTools: Map<string, RegisteredTool>; // Keyed by name
registeredResources: Map<string, RegisteredResource>; // Keyed by URI
registeredPrompts: Map<string, RegisteredPrompt>; // Keyed by name
registeredResourceTemplates: Map<string, RegisteredResourceTemplate>; // Keyed by uriTemplate
listChangedConfig: {
tools?: boolean;
resources?: boolean;
prompts?: boolean;
};
resourceSubscriptions: Set<string>; // Set of subscribed resource URIs
}
/**
* Context object passed to tool handlers containing both server and state
*/
export interface TestServerContext {
server: McpServer;
state: ServerState;
serverControl?: { isClosing(): boolean };
/** The cross-session hub, when {@link ServerConfig.resourceUpdateBroadcast} is set. */
resourceUpdateBroadcast?: ResourceUpdateBroadcast;
}
// ---------------------------------------------------------------------------
// Legacy (2025-11-25) tasks — re-implemented by hand.
//
// SDK v2 deleted the experimental tasks runtime (`InMemoryTaskStore`,
// `registerToolTask`, `client/server.experimental.tasks.*`). The Inspector still
// exercises the 2025-11-25 task wire methods end to end, so the composable
// server keeps answering them with a small in-memory store plus low-level
// custom-method handlers wired up in `createMcpServer`.
// ---------------------------------------------------------------------------
/** Task lifecycle status (2025-11-25 vocabulary). */
export type TaskStatus = Task["status"];
/** Loosely-typed argument bag handed to a task tool's `getTask`/`getTaskResult`. */
export type ShapeOutput<_Shape> = Record<string, unknown>;
/** Payload a task stores as its result (for `tasks/result`). */
export type StoredTaskResult = CallToolResult & Record<string, unknown>;
/**
* In-memory task store. Replaces the deleted SDK `InMemoryTaskStore`; keeps the
* subset of methods the composable fixtures use plus list/cancel for the
* `tasks/list` and `tasks/cancel` wire handlers.
*/
export class InMemoryTaskStore {
private tasks = new Map<string, Task>();
private results = new Map<string, StoredTaskResult>();
/** Optional hook fired on every status change (wired to `notifications/tasks/status`). */
onTaskStatusChanged?: (task: Task) => void;
private touch(task: Task): Task {
task.lastUpdatedAt = new Date().toISOString();
return task;
}
async createTask(options: { ttl?: number } = {}): Promise<Task> {
const now = new Date().toISOString();
const task: Task = {
taskId:
globalThis.crypto?.randomUUID?.() ??
`task-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`,
status: "working",
ttl: options.ttl ?? null,
createdAt: now,
lastUpdatedAt: now,
};
this.tasks.set(task.taskId, task);
this.onTaskStatusChanged?.(task);
return task;
}
async getTask(taskId: string): Promise<Task | undefined> {
return this.tasks.get(taskId);
}
async updateTaskStatus(
taskId: string,
status: TaskStatus,
statusMessage?: string,
): Promise<Task | undefined> {
const task = this.tasks.get(taskId);
if (!task) return undefined;
task.status = status;
if (statusMessage !== undefined) {
task.statusMessage = statusMessage;
}
this.touch(task);
this.onTaskStatusChanged?.(task);
return task;
}
async storeTaskResult(
taskId: string,
status: TaskStatus,
result: StoredTaskResult,
): Promise<void> {
this.results.set(taskId, result);
await this.updateTaskStatus(taskId, status);
}
async getTaskResult(taskId: string): Promise<StoredTaskResult> {
const result = this.results.get(taskId);
if (!result) {
throw new Error(`No result stored for task ${taskId}`);
}
return result;
}
async listTasks(): Promise<Task[]> {
return [...this.tasks.values()];
}
}
/** `extra` handed to a task tool's `createTask` (server→client requests + the store). */
export interface CreateTaskRequestHandlerExtra {
taskStore: InMemoryTaskStore;
/** `_meta` from the augmenting `tools/call` (e.g. `_meta.progressToken`). */
_meta?: Record<string, unknown>;
/** The inbound request id. */
requestId?: string | number;
/** Send a server→client request (`elicitation/create`, `sampling/createMessage`, `tasks/*`). */
sendRequest: <T extends z.core.$ZodType>(
request: { method: string; params?: Record<string, unknown> },
resultSchema: T,
) => Promise<z.output<T>>;
/** Send a server→client notification (`notifications/progress`, …). */
sendNotification: (notification: {
method: string;
params?: Record<string, unknown>;
}) => Promise<void>;
}
/** `extra` handed to a task tool's `getTask`/`getTaskResult`. */
export interface TaskRequestHandlerExtra {
taskId: string;
taskStore: InMemoryTaskStore;
}
/** Handler triplet for a task-augmented tool (replaces the SDK's `ToolTaskHandler`). */
export interface ToolTaskHandler {
createTask: (
args: Record<string, unknown>,
extra: CreateTaskRequestHandlerExtra,
) => Promise<{ task: Task }>;
getTask: (
args: Record<string, unknown>,
extra: TaskRequestHandlerExtra,
) => Promise<GetTaskResult>;
getTaskResult: (
args: Record<string, unknown>,
extra: TaskRequestHandlerExtra,
) => Promise<CallToolResult>;
}
export interface ToolDefinition {
name: string;
description: string;
inputSchema?: ToolInputSchema;
/** OAuth scopes required to invoke this tool (enforced at HTTP layer). */
requiredScopes?: string[];
/** Optional Zod object schema for tool output; when set, handler must return structuredContent. */
outputSchema?: unknown;
/** Passed through to the SDK so clients can read tool-level `_meta` (e.g. `_meta.ui.resourceUri` for MCP App tools). */
_meta?: Record<string, unknown>;
handler: (
params: Record<string, unknown>,
context?: TestServerContext,
extra?: HandlerExtra,
// A handler may return an `InputRequiredResult` (via `inputRequired(...)`)
// on the 2026-07-28 leg to drive an MRTR round-trip; the wrapper forwards it
// verbatim rather than coercing it to a `CallToolResult`.
) => Promise<CallToolResult | InputRequiredResult>;
}
export interface TaskToolDefinition {
name: string;
description: string;
inputSchema?: ToolInputSchema;
/** OAuth scopes required to invoke this tool (enforced at HTTP layer). */
requiredScopes?: string[];
execution?: { taskSupport: "required" | "optional" };
/** Passed through to the SDK so clients can read tool-level `_meta` (e.g. `_meta.ui.resourceUri` for an App-flavored task tool). Mirrors {@link ToolDefinition._meta}. */
_meta?: Record<string, unknown>;
handler: ToolTaskHandler;
}
export interface ResourceDefinition {
uri: string;
name: string;
description?: string;
mimeType?: string;
text?: string;
/**
* Included on the returned content item so clients can read resource-level `_meta` (e.g. `_meta.ui.csp` for MCP App UI resources).
* Only the default read handler applies this; a `customHandler` from `config.onRegisterResource` replaces the `contents` wholesale, so such a handler must re-add `_meta` itself if the resource needs it on the read response.
*/
_meta?: Record<string, unknown>;
/** OAuth scopes required to read this resource (enforced at HTTP layer). */
requiredScopes?: string[];
}
export interface PromptDefinition {
name: string;
description?: string;
/** OAuth scopes required to fetch this prompt (enforced at HTTP layer). */
requiredScopes?: string[];
promptString: string; // The prompt text with optional {argName} placeholders
argsSchema?: PromptArgsSchema; // Can include completable() schemas
// Optional completion callbacks keyed by argument name
// This is a convenience - users can also use completable() directly in argsSchema
completions?: Record<
string,
(
argumentValue: string,
context?: Record<string, string>,
) => Promise<string[]> | string[]
>;
}
export interface ResourceTemplateDefinition {
name: string;
uriTemplate: string; // URI template with {variable} placeholders (RFC 6570)
description?: string;
/** OAuth scopes required to read resources from this template (enforced at HTTP layer). */
requiredScopes?: string[];
inputSchema?: Record<string, z.ZodType>; // Schema for template variables
handler: (
uri: URL,
params: Record<string, unknown>,
context?: TestServerContext,
extra?: HandlerExtra,
) => Promise<{
contents: Array<{ uri: string; mimeType?: string; text: string }>;
}>;
// Optional callbacks for resource template operations
// list: Can return either:
// - string[] (convenience - will be converted to ListResourcesResult with uri and name)
// - ListResourcesResult (full control - includes uri, name, description, mimeType, etc.)
list?:
| (() => Promise<string[]> | string[])
| (() => Promise<ListResourcesResult> | ListResourcesResult);
// complete: Map of variable names to completion callbacks
// OR a single callback function that will be used for all variables
complete?:
| Record<
string,
(
value: string,
context?: Record<string, string>,
) => Promise<string[]> | string[]
>
| ((
argumentName: string,
argumentValue: string,
context?: Record<string, string>,
) => Promise<string[]> | string[]);
}
/**
* Configuration for composing an MCP server
*/
export interface ServerConfig {
serverInfo: Implementation; // Server metadata (name, version, etc.) - required
tools?: (ToolDefinition | TaskToolDefinition)[]; // Tools to register (optional, empty array means no tools, but tools capability is still advertised)
resources?: ResourceDefinition[]; // Resources to register (optional, empty array means no resources, but resources capability is still advertised)
resourceTemplates?: ResourceTemplateDefinition[]; // Resource templates to register (optional, empty array means no templates, but resources capability is still advertised)
prompts?: PromptDefinition[]; // Prompts to register (optional, empty array means no prompts, but prompts capability is still advertised)
logging?: boolean; // Whether to advertise logging capability (default: false)
onLogLevelSet?: (level: string) => void; // Optional callback when log level is set (for testing)
onRegisterResource?: (resource: ResourceDefinition) =>
| (() => Promise<{
contents: Array<{ uri: string; mimeType?: string; text: string }>;
}>)
| undefined; // Optional callback to customize resource handler during registration
serverType?: "sse" | "streamable-http"; // Transport type (default: "streamable-http")
port?: number; // Port to use (optional, will find available port if not specified)
/**
* Whether to advertise listChanged capability for each list type
* If enabled, modification tools will send list_changed notifications
*/
listChanged?: {
tools?: boolean; // default: false
resources?: boolean; // default: false
prompts?: boolean; // default: false
};
/**
* Whether to advertise resource subscriptions capability
* If enabled, server will advertise resources.subscribe capability
*/
subscriptions?: boolean; // default: false
/**
* Maximum page size for pagination (optional, undefined means no pagination)
* When set, custom list handlers will paginate results using this page size
*/
maxPageSize?: {
tools?: number;
resources?: number;
resourceTemplates?: number;
prompts?: number;
};
/**
* Hand out the **empty string** as the cursor for page two of every
* paginated list, instead of the usual numeric index (#2220).
*
* An MCP cursor is opaque: the spec constrains neither its content nor its
* length, so `""` is a legal `nextCursor` and a conforming client has to send
* it back verbatim. A client that builds its request params with a
* truthiness check cannot tell `""` from "no cursor", so it drops it and
* silently re-requests page one — a list that stops after one page, or a
* walk that loops on it forever, with no error anywhere because the request
* is perfectly well-formed.
*
* Nothing else in this repo produces that shape: every other fixture's
* cursor is a non-empty index string, which the buggy guard happens to carry
* correctly. Off by default so the existing pagination fixtures keep their
* numeric cursors.
*/
emptyStringCursor?: boolean; // default: false
/**
* Emit the named registered tools **twice** in `tools/list`, with the same
* `name` on both entries and " (duplicate)" appended to the second's title.
*
* Nothing else in this repo can produce this shape: every preset registers a
* unique name, and the SDK's `registerTool` rejects a repeat. But a real
* server can and does return duplicates, and the Inspector has to render that
* faithfully rather than break on it (#1957 — duplicate names collided in the
* Tools sidebar's React keys, so filtering left unrelated rows on screen).
*
* Deliberately a list of names rather than a blanket flag, so a config can
* duplicate part of its tool set and leave the rest alone — that mix is what
* makes a search filter's behavior legible. A name that isn't registered is
* ignored.
*/
duplicateToolNames?: string[];
/**
* URIs to emit **twice** in `resources/list` (same `uri`, the second's title
* marked "(duplicate)").
*
* The `resources/list` analogue of {@link duplicateToolNames}, and
* unreachable the same way: `registerResource` keys on the URI, so no preset
* can produce a repeat. A real server can — two resource sources
* concatenated — and the Inspector has to render that faithfully rather than
* collide on the React key (#2206).
*
* Matched against **everything the list actually carries**, which is the
* static registrations *and* whatever a resource template's `list` callback
* contributes — not `state.registeredResources` alone (Copilot). Both land in
* the same Resources sidebar list and collide on the same React key, so
* scoping this to static registrations only would leave half the surface
* unreproducible. A URI that appears in neither is ignored.
*
* The copies go **after** the whole list rather than beside their twin, for
* the reason spelled out on `duplicateToolNames`: a head-adjacent pair
* happens to survive reconciliation, so only a separated pair exposes the
* defect.
*/
duplicateResourceUris?: string[];
/**
* Replace a registered tool's `inputSchema` / `outputSchema` in `tools/list`
* with a **raw** JSON Schema document (#1005).
*
* The presets build their schemas from Zod, which by construction cannot
* emit the constructs the schema-portability lint exists to find — a bare
* `true` in a `properties` map, an array-form `type`, a remote `$ref`. Those
* come from other generators (Go's `jsonschema` package emits `true` for
* `interface{}`), so reproducing them needs a hand-written document. Only the
* *advertised* schema is replaced; the tool's handler and its real Zod
* validation are untouched, so calling it still behaves as its preset does.
*
* ⚠️ **Overriding `outputSchema` changes what a client will accept.** A
* conforming client validates a tool result against the advertised output
* schema, so putting one on a preset whose handler returns no
* `structuredContent` makes every call to it fail — the Inspector rejects it
* with "declares an output schema but returned no structured content". Put an
* `outputSchema` override only on a tool that actually returns structured
* content (`get_temp`, `list_items`), and keep the override permissive enough
* that the real payload still validates.
*
* A name that isn't registered is ignored.
*/
rawToolSchemas?: Record<
string,
{ inputSchema?: unknown; outputSchema?: unknown }
>;
/**
* Gate a tool's visibility in `tools/list` on a client-declared extension
* (SEP-2133 `capabilities.extensions`). Maps extension id → tool name (the
* tool must be among the registered presets). The named tool is registered
* but starts disabled; on `notifications/initialized`, if the connected
* client declared that extension, it is enabled and appears in `tools/list`.
*
* Demonstrates that advertised client extensions change server tool
* registration (#1739 / #1633). Legacy stateful leg only — the modern
* per-request leg builds a fresh server per request with no persistent
* `oninitialized`, so a gated tool stays disabled there.
*/
extensionGatedTools?: Record<string, string>;
/**
* Whether to advertise tasks capability
* If enabled, server will advertise tasks capability with list and cancel support
*/
tasks?: {
list?: boolean; // default: true
cancel?: boolean; // default: true
};
/**
* Task store implementation (optional, defaults to a fresh {@link InMemoryTaskStore}).
* Only used if tasks capability is enabled.
*/
taskStore?: InMemoryTaskStore;
/**
* Advertise the modern (2026-07-28) `io.modelcontextprotocol/tasks` extension
* (SEP-2663) and wire its raw `tasks/get` / `tasks/update` / `tasks/cancel`
* handlers plus the `modern_task` / `modern_input_task` tools. Distinct from
* the legacy {@link ServerConfig.tasks} capability — meant to be paired with
* `modern: true`. See `modern-tasks.ts`.
*/
tasksExtension?: boolean;
/**
* Advertise the Skills extension (SEP-2640) and serve `skills/list` /
* `skills/get` plus the `skill://` files those entries name. The fixture set
* deliberately includes non-conforming skills — see `skills.ts`.
*
* Turning this on also declares **`directoryRead: true`** and serves
* `resources/directory/read` over the same `skill://` tree (#2248). The two
* are one switch rather than two on purpose: the sub-flag's whole hazard is
* advertising a method nothing answers — Connection Info reporting
* "Supported" for a call that returns `-32601` — and a config that cannot
* express the declaration without the handler cannot reach it. A fixture for
* the *undeclared* case is still available and is the more useful one:
* any config without `skills` at all, against which the Inspector must
* refuse to send the call locally.
*/
skills?: boolean;
/**
* With {@link ServerConfig.skills}, refuse `skills/list`, `skills/get` and
* `resources/directory/read` unless the client declared
* `io.modelcontextprotocol/skills` in its own capabilities — a strict
* SEP-2133 server (#2373). A modern request is refused with `-32021`
* MissingRequiredClientCapability carrying `data.requiredCapabilities`; a
* legacy one, whose era has no such code, with `-32601`. Off by default so
* the existing skills fixtures keep serving any client. Ignored without
* `skills`.
*/
skillsRequireClientExtension?: boolean;
/**
* Serve the Events extension (SEP-3415, `io.modelcontextprotocol/events`):
* advertise it to a **modern** `server/discover` only, serve `events/*` and
* the `eventsListChanged` listen filter over HTTP, and register the control
* tools (`emit_event`, `add_event_type`, `remove_event_type`,
* `inject_event_failure`, `get_event_stats`). `true` takes every default.
* HTTP only — see `events.ts`.
*/
events?: boolean | EventsConfig;
/**
* Shared Events runtime. Created lazily and cached here, like
* {@link ServerConfig.modernTaskRuntime}, so every per-request server on the
* modern leg sees one occurrence log. Do not set by hand.
*/
eventsRuntime?: EventsRuntime;
/**
* Advertise the MCP Apps `io.modelcontextprotocol/ui` extension with the
* nested `elicitation` setting — the server-side half of the app-rendered
* form elicitation negotiation (#1854, ext-apps#733).
*
* A client that also advertises it may render a `ui://` app for any
* `elicitation/create` this server attaches `_meta.ui.resourceUri` to; one
* that does not simply shows its own form, which is why this is safe to
* advertise unconditionally on a server that offers such a tool.
*/
appElicitation?: boolean;
/**
* Shared modern task runtime. Created lazily on first `createMcpServer` call
* and cached here so the stateless modern leg's per-request server instances
* share one task store (a task created by a `tools/call` must be visible to a
* later `tasks/get`). Do not set by hand.
*/
modernTaskRuntime?: ModernTaskRuntime;
/**
* OAuth 2.1 configuration for test server.
* - **combined** (default): this server is both MCP resource and authorization server.
* - **protected-resource**: MCP resource only; metadata points at external authorization server(s).
*/
oauth?: {
enabled: boolean;
/**
* combined — local AS + resource (existing behavior).
* protected-resource — external AS; JWT bearer validation against AS JWKS.
*/
mode?: "combined" | "protected-resource";
/**
* External authorization server URLs for protected-resource metadata
* (`authorization_servers` in RFC 9728). Required when mode is protected-resource.
*/
authorizationServers?: string[];
/**
* Protected resource identifier override for RFC 9728 metadata.
* Defaults to the MCP server base URL when omitted.
*/
resource?: string;
/**
* Serve the RFC 9728 protected-resource metadata document from this
* non-default path *instead of* `/.well-known/oauth-protected-resource`,
* and advertise it via `WWW-Authenticate: Bearer resource_metadata="…"`
* on every 401.
*
* The default well-known routes are deliberately left unserved, so a
* client that ignores the advertised URL cannot discover the document at
* all — which is what makes this a regression test for #2071 rather than
* a path that merely happens to work.
*/
resourceMetadataPath?: string;
/**
* Serve the RFC 8414 authorization-server metadata document from this
* non-default path *instead of* `/.well-known/oauth-authorization-server`
* (combined mode only).
*
* Set it to `/.well-known/openid-configuration` to reproduce #2172: a
* plain OAuth 2.0 authorization server — no `jwks_uri`, no
* `subject_types_supported`, no `id_token_signing_alg_values_supported` —
* publishing RFC 8414 metadata at the OIDC well-known path, which RFC 8414
* §5 permits. As with `resourceMetadataPath`, the default route is left
* unserved, so a client that cannot read the document where it actually
* lives fails outright rather than quietly succeeding elsewhere.
*/
asMetadataPath?: string;
/**
* OAuth authorization server issuer URL (combined mode AS metadata).
* If not provided, defaults to the test server's base URL.
*/
issuerUrl?: URL;
/**
* Allowed JWT `iss` values for access tokens (protected-resource mode).
* Defaults to authorizationServers plus issuer from AS metadata discovery.
*/
accessTokenIssuers?: string[];
/**
* JWKS URI override for access-token signature verification.
* When omitted, discovered from authorization server metadata.
*/
jwksUri?: string;
/**
* When set, require JWT `aud` to match this resource identifier.
*/
resourceAudience?: string;
scopesSupported?: string[];
requireAuth?: boolean;
/**
* Static/preregistered clients for testing
* These clients are pre-configured and don't require DCR
*/
staticClients?: Array<{
clientId: string;
clientSecret?: string;
redirectUris?: string[];
}>;
/**
* Whether to support Dynamic Client Registration (DCR)
* If true, exposes /register endpoint for client registration
*/
supportDCR?: boolean;
/**
* Whether to support CIMD (Client ID Metadata Documents)
* If true, server will fetch client metadata from clientMetadataUrl
*/
supportCIMD?: boolean;
/**
* Serve a CIMD client metadata document from this server, so a CIMD
* fixture is self-contained.
*
* CIMD makes the `client_id` a URL that the authorization server fetches
* to learn the client's metadata (SEP-991). Nothing in this repo served
* such a document, so exercising CIMD meant standing up a second host by
* hand — which is why #2242 shipped verified only by its tests. With this
* set, the server hosts the document at `clientMetadataPath` (default
* `/client-metadata.json`) and that URL is a usable `client_id`.
*
* `redirectUris` MUST list the Inspector's callback for the port you run
* it on (`<web origin>/oauth/callback`) — the authorization server checks
* the incoming `redirect_uri` against this list, and a mismatch fails the
* flow with `Invalid redirect_uri` rather than anything CIMD-specific.
*
* Only served when `supportCIMD` is true: a document advertising a client
* the server would then refuse is a worse fixture than none.
*/
clientMetadata?: {
redirectUris: string[];
clientName?: string;
scope?: string;
};
/**
* Where to serve `clientMetadata` (default `/client-metadata.json`).
*
* Must be origin-relative with no query or fragment, and is validated as
* such — both by `loadConfig` and again at server setup for a config built
* in code. Unlike the other metadata paths this one is not merely
* advertised: it becomes the document's own `client_id`, so an off-origin
* or query-bearing value would publish a client id this server cannot
* honour (Copilot).
*/
clientMetadataPath?: string;
/**
* Token expiration time in seconds (default: 3600)
*/
tokenExpirationSeconds?: number;
/**
* Whether to support refresh tokens (default: true)
*/
supportRefreshTokens?: boolean;
/**
* Endpoints that accept the request and then withhold the response, so the
* `AbortSignal.timeout` #2319 put on the OAuth path can be driven against a
* real, established, idle socket (#2382).
*
* A `fetch` stub cannot reproduce that state — it settles on the client
* side — which is why the five timeouts shipped covered only by unit tests.
* Name the *call*, not the path: exchange and refresh share `/oauth/token`,
* and two of the documents sit at configurable paths.
*
* Per endpoint rather than global, so a test can tell "discovery timed out"
* from "token exchange timed out" — the distinction the five separate
* timeouts exist to make.
*/
stallEndpoints?: StallableOAuthEndpoint[];
/**
* Answer a stalled endpoint after this many ms instead of never
* (default: 0, never). Lets one fixture cover both "slower than the
* client's budget" and "no answer at all".
*/
stallMs?: number;
/**
* Whether to advertise and serve the RFC 7009 `revocation_endpoint`
* (default: true). Set to `false` to reproduce an authorization server that
* offers no revocation, where the Inspector must send nothing and clear
* local state exactly as it always has. (#2144)
*/
supportRevocation?: boolean;
};
/**
* Serve the modern (2026-07-28) protocol era via the SDK's
* `createMcpHandler` instead of the 2025 session-based streamable transport.
* Only meaningful for `serverType: "streamable-http"` (the modern model is
* HTTP-centric: per-request POST + `server/discover`).
*
* When present, the HTTP server mounts `createMcpHandler(factory, { legacy })`
* so an SDK v2 client negotiating `protocolEra: "auto" | "modern"` reaches the
* modern leg end-to-end (populated `server/discover` result, sessionless).
*
* - `legacy: "stateless"` (default) — dual-era: modern envelope requests use
* the modern leg; legacy-classified requests (e.g. a plain `initialize`
* handshake) fall back to per-request stateless 2025 serving, so a
* `protocolEra: "legacy"` client still connects.
* - `legacy: "reject"` — modern-only strict: legacy-classified requests get
* the unsupported-protocol-version error, exercising the pin-failure and
* `server/discover` surfaces.
*/
modern?: {
legacy?: "stateless" | "reject";
/**
* When true, the modern HTTP leg installs a middleware that returns the
* SEP-2243 / SEP-2575 spec error codes for specially-named trigger tool
* calls (see `SPEC_ERROR_TRIGGERS` in test-server-http.ts). Used by the
* `modern-network-http` showcase to exercise the Inspector's Network-tab
* error rendering (a conformant server never produces these on demand).
*/
injectSpecErrors?: boolean;
/**
* When true, the modern HTTP leg installs a middleware that answers every
* `subscriptions/listen` with a bare JSON-RPC `result` — the spec's
* graceful-closure marker — instead of acknowledging it. That is the
* non-conformant server shape from #2097: "acknowledged and closed in the
* same breath". Used by the `subscriptions-never-acknowledged-http`
* showcase; a conformant server never does this on an opening listen.
*
* `"after-first"` acknowledges the first listen that **subscribes to a
* resource** and refuses every resource-subscription listen after it — the
* *reconnect* shape, and the only way to reach the Inspector's
* never-acknowledged badge by hand (it is gated on a live subscription,
* which a server refusing from the outset never lets you hold).
*
* A listen carrying no `resourceSubscriptions` is always acknowledged under
* this mode and does not consume the allowance. That exemption is what makes
* the mode reproducible: the Inspector already opens a listen at connect
* time when a list-change opt-in is live (#1920), so counting listens rather
* than resource-subscription listens would spend the allowance before the
* user clicks anything, refusing the very first Subscribe.
*
* `true` refuses every listen unconditionally, list-change-only ones
* included — the literal shape in the report.
*/
neverAcknowledgeSubscriptions?: boolean | "after-first";
/**
* When set, the modern HTTP leg answers every `subscriptions/listen` with
* this bare HTTP status — no JSON-RPC body, no `WWW-Authenticate` — the
* shape a proxy or gateway produces (#2722). Used by the
* `subscriptions-listen-refused-http` showcase (403). A transient status
* (503, 429) exercises the other half: the Inspector keeps retrying those.
*/
refuseSubscriptionsListen?: number;
};
/**
* Optional server control for orderly shutdown (test HTTP server).
* When present, progress-sending tools check isClosing() before sending and skip/break if closing.
*/
serverControl?: { isClosing(): boolean };
/**
* Called on every `resources/subscribe` (with `subscriptions: true`), with
* the subscribing session's context. Each HTTP session is its own server,
* so a test that must notify every session — a fan-out load test (#2913) —
* collects the contexts here and sends to each.
*/
onResourceSubscribe?: (uri: string, context: TestServerContext) => void;
/**
* Share resource updates across every session this config builds (#2964).
* Each session joins the hub and leaves when its connection closes, and
* `update_resource` publishes through it — so one call changes the resource
* in every session and notifies each one subscribed, the shape a
* `--load-subscribe` fan-out run needs. Pass one hub per server: a config
* file sets `broadcastResourceUpdates: true` and `resolveConfig` creates it.
*/
resourceUpdateBroadcast?: ResourceUpdateBroadcast;
}
/**
* Create and configure an McpServer instance from ServerConfig
* This centralizes the setup logic shared between HTTP and stdio test servers
*/
/**
* The shared Events runtime for a config, created on first use. `undefined`
* when the config does not turn the extension on.
*/
export function getEventsRuntime(
config: ServerConfig,
): EventsRuntime | undefined {
if (!config.events) return undefined;
return (config.eventsRuntime ??= new EventsRuntime(
config.events === true ? {} : config.events,
));
}
/**
* @param era The protocol era the instance will serve, when the caller knows
* it (the modern HTTP leg's factory passes it). Only the Events extension
* reads it: that extension is advertised to a modern `server/discover` and,
* absent `advertiseOnLegacy`, to nothing else.
*/
export function createMcpServer(
config: ServerConfig,
era?: "legacy" | "modern",
): McpServer {
// Build capabilities based on config
const capabilities: {
tools?: object;
resources?: { subscribe?: boolean };
prompts?: object;
logging?: object;
tasks?: {
list?: object;
cancel?: object;
requests?: { tools?: { call?: object } };
};
extensions?: Record<string, object>;
} = {};
// The modern tasks extension (SEP-2663) needs the tools capability too (its
// task-augmented tools list via `tools/list`), even when no `config.tools`
// were supplied.
if (config.tools !== undefined || config.tasksExtension || config.events) {
capabilities.tools = {};
}
if (
config.resources !== undefined ||
config.resourceTemplates !== undefined
) {
capabilities.resources = {};
// Add subscribe capability if subscriptions are enabled
if (config.subscriptions === true) {