@jangmanj/mcp 0.0.0-stage → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +337 -2
  3. package/adapters/pi/bridge.ts +721 -0
  4. package/adapters/pi/config.ts +364 -0
  5. package/adapters/pi/content-offloaded.ts +53 -0
  6. package/adapters/pi/content.ts +78 -0
  7. package/adapters/pi/diagnostics.ts +26 -0
  8. package/adapters/pi/elicitation.ts +133 -0
  9. package/adapters/pi/index.ts +210 -0
  10. package/adapters/pi/oauth.ts +219 -0
  11. package/adapters/pi/pi-api.ts +133 -0
  12. package/adapters/pi/resources.ts +177 -0
  13. package/adapters/pi/result-files.ts +32 -0
  14. package/adapters/pi/tasks.ts +49 -0
  15. package/dist/auth/client-credentials.d.ts +65 -0
  16. package/dist/auth/client-credentials.js +388 -0
  17. package/dist/auth/discovery.d.ts +28 -0
  18. package/dist/auth/discovery.js +125 -0
  19. package/dist/auth/index.d.ts +9 -0
  20. package/dist/auth/index.js +5 -0
  21. package/dist/auth/node-ports.d.ts +8 -0
  22. package/dist/auth/node-ports.js +67 -0
  23. package/dist/auth/protocol.d.ts +12 -0
  24. package/dist/auth/protocol.js +39 -0
  25. package/dist/auth/provider.d.ts +114 -0
  26. package/dist/auth/provider.js +407 -0
  27. package/dist/auth/safe-fetch.d.ts +14 -0
  28. package/dist/auth/safe-fetch.js +130 -0
  29. package/dist/client/events.d.ts +33 -0
  30. package/dist/client/events.js +84 -0
  31. package/dist/client/index.d.ts +65 -0
  32. package/dist/client/index.js +128 -0
  33. package/dist/core/auth-types.d.ts +36 -0
  34. package/dist/core/auth-types.js +11 -0
  35. package/dist/core/bearer-challenge.d.ts +3 -0
  36. package/dist/core/bearer-challenge.js +63 -0
  37. package/dist/core/cancel.d.ts +70 -0
  38. package/dist/core/cancel.js +177 -0
  39. package/dist/core/extension.d.ts +33 -0
  40. package/dist/core/extension.js +145 -0
  41. package/dist/core/index.d.ts +73 -0
  42. package/dist/core/index.js +129 -0
  43. package/dist/core/jsonrpc.d.ts +49 -0
  44. package/dist/core/jsonrpc.js +80 -0
  45. package/dist/core/lifecycle.d.ts +128 -0
  46. package/dist/core/lifecycle.js +251 -0
  47. package/dist/core/outcome.d.ts +98 -0
  48. package/dist/core/outcome.js +32 -0
  49. package/dist/core/ports.d.ts +144 -0
  50. package/dist/core/ports.js +67 -0
  51. package/dist/core/progress.d.ts +81 -0
  52. package/dist/core/progress.js +205 -0
  53. package/dist/core/request.d.ts +108 -0
  54. package/dist/core/request.js +578 -0
  55. package/dist/core/schema/index.d.ts +1 -0
  56. package/dist/core/schema/index.js +1 -0
  57. package/dist/core/schema/types.d.ts +4154 -0
  58. package/dist/core/schema/types.js +6 -0
  59. package/dist/core/telemetry.d.ts +25 -0
  60. package/dist/core/telemetry.js +37 -0
  61. package/dist/ext-events/index.d.ts +79 -0
  62. package/dist/ext-events/index.js +218 -0
  63. package/dist/ext-events/model.d.ts +10 -0
  64. package/dist/ext-events/model.js +6 -0
  65. package/dist/ext-events/push.d.ts +18 -0
  66. package/dist/ext-events/push.js +101 -0
  67. package/dist/ext-events/stream.d.ts +6 -0
  68. package/dist/ext-events/stream.js +60 -0
  69. package/dist/ext-server-cards/index.d.ts +107 -0
  70. package/dist/ext-server-cards/index.js +249 -0
  71. package/dist/ext-skills/cache.d.ts +20 -0
  72. package/dist/ext-skills/cache.js +101 -0
  73. package/dist/ext-skills/client.d.ts +82 -0
  74. package/dist/ext-skills/client.js +292 -0
  75. package/dist/ext-skills/extension.d.ts +16 -0
  76. package/dist/ext-skills/extension.js +29 -0
  77. package/dist/ext-skills/index.d.ts +4 -0
  78. package/dist/ext-skills/index.js +4 -0
  79. package/dist/ext-skills/verify.d.ts +57 -0
  80. package/dist/ext-skills/verify.js +168 -0
  81. package/dist/index.d.ts +1 -0
  82. package/dist/index.js +1 -0
  83. package/dist/mrtr-cache/cache.d.ts +51 -0
  84. package/dist/mrtr-cache/cache.js +295 -0
  85. package/dist/mrtr-cache/client.d.ts +24 -0
  86. package/dist/mrtr-cache/client.js +44 -0
  87. package/dist/mrtr-cache/common.d.ts +10 -0
  88. package/dist/mrtr-cache/common.js +9 -0
  89. package/dist/mrtr-cache/elicitation.d.ts +42 -0
  90. package/dist/mrtr-cache/elicitation.js +221 -0
  91. package/dist/mrtr-cache/index.d.ts +9 -0
  92. package/dist/mrtr-cache/index.js +8 -0
  93. package/dist/mrtr-cache/mrtr.d.ts +37 -0
  94. package/dist/mrtr-cache/mrtr.js +250 -0
  95. package/dist/mrtr-cache/refresh.d.ts +8 -0
  96. package/dist/mrtr-cache/refresh.js +30 -0
  97. package/dist/mrtr-cache/stream.d.ts +5 -0
  98. package/dist/mrtr-cache/stream.js +18 -0
  99. package/dist/mrtr-cache/subscriptions.d.ts +96 -0
  100. package/dist/mrtr-cache/subscriptions.js +288 -0
  101. package/dist/mrtr-cache/tasks.d.ts +103 -0
  102. package/dist/mrtr-cache/tasks.js +444 -0
  103. package/dist/ops/common.d.ts +18 -0
  104. package/dist/ops/common.js +39 -0
  105. package/dist/ops/completion.d.ts +44 -0
  106. package/dist/ops/completion.js +65 -0
  107. package/dist/ops/content.d.ts +40 -0
  108. package/dist/ops/content.js +117 -0
  109. package/dist/ops/icons.d.ts +29 -0
  110. package/dist/ops/icons.js +82 -0
  111. package/dist/ops/index.d.ts +30 -0
  112. package/dist/ops/index.js +28 -0
  113. package/dist/ops/pagination.d.ts +32 -0
  114. package/dist/ops/pagination.js +65 -0
  115. package/dist/ops/prompts.d.ts +32 -0
  116. package/dist/ops/prompts.js +68 -0
  117. package/dist/ops/resources.d.ts +42 -0
  118. package/dist/ops/resources.js +104 -0
  119. package/dist/ops/schema.d.ts +39 -0
  120. package/dist/ops/schema.js +163 -0
  121. package/dist/ops/tools.d.ts +88 -0
  122. package/dist/ops/tools.js +169 -0
  123. package/dist/ops/uri-template.d.ts +3 -0
  124. package/dist/ops/uri-template.js +101 -0
  125. package/dist/server/index.d.ts +5 -0
  126. package/dist/server/index.js +5 -0
  127. package/dist/server/mrtr.d.ts +38 -0
  128. package/dist/server/mrtr.js +99 -0
  129. package/dist/server/protocol.d.ts +21 -0
  130. package/dist/server/protocol.js +49 -0
  131. package/dist/server/server.d.ts +105 -0
  132. package/dist/server/server.js +383 -0
  133. package/dist/server/skills.d.ts +45 -0
  134. package/dist/server/skills.js +73 -0
  135. package/dist/server/uri.d.ts +2 -0
  136. package/dist/server/uri.js +27 -0
  137. package/dist/server-events/bus.d.ts +40 -0
  138. package/dist/server-events/bus.js +84 -0
  139. package/dist/server-events/events.d.ts +36 -0
  140. package/dist/server-events/events.js +108 -0
  141. package/dist/server-events/index.d.ts +6 -0
  142. package/dist/server-events/index.js +6 -0
  143. package/dist/server-events/notices.d.ts +24 -0
  144. package/dist/server-events/notices.js +31 -0
  145. package/dist/server-events/subscriptions.d.ts +33 -0
  146. package/dist/server-events/subscriptions.js +77 -0
  147. package/dist/server-events/tasks.d.ts +43 -0
  148. package/dist/server-events/tasks.js +101 -0
  149. package/dist/server-events/types.d.ts +25 -0
  150. package/dist/server-events/types.js +34 -0
  151. package/dist/server-transport/auth.d.ts +20 -0
  152. package/dist/server-transport/auth.js +29 -0
  153. package/dist/server-transport/channel.d.ts +17 -0
  154. package/dist/server-transport/channel.js +47 -0
  155. package/dist/server-transport/http.d.ts +19 -0
  156. package/dist/server-transport/http.js +209 -0
  157. package/dist/server-transport/index.d.ts +4 -0
  158. package/dist/server-transport/index.js +4 -0
  159. package/dist/server-transport/stdio.d.ts +16 -0
  160. package/dist/server-transport/stdio.js +83 -0
  161. package/dist/telemetry-otel/index.d.ts +64 -0
  162. package/dist/telemetry-otel/index.js +196 -0
  163. package/dist/testing/index.d.ts +36 -0
  164. package/dist/testing/index.js +140 -0
  165. package/dist/transport-http/headers.d.ts +24 -0
  166. package/dist/transport-http/headers.js +140 -0
  167. package/dist/transport-http/index.d.ts +3 -0
  168. package/dist/transport-http/index.js +3 -0
  169. package/dist/transport-http/sse.d.ts +33 -0
  170. package/dist/transport-http/sse.js +152 -0
  171. package/dist/transport-http/transport.d.ts +66 -0
  172. package/dist/transport-http/transport.js +854 -0
  173. package/dist/transport-stdio/framing.d.ts +50 -0
  174. package/dist/transport-stdio/framing.js +154 -0
  175. package/dist/transport-stdio/index.d.ts +4 -0
  176. package/dist/transport-stdio/index.js +4 -0
  177. package/dist/transport-stdio/stderr-ring.d.ts +27 -0
  178. package/dist/transport-stdio/stderr-ring.js +105 -0
  179. package/dist/transport-stdio/transport.d.ts +142 -0
  180. package/dist/transport-stdio/transport.js +743 -0
  181. package/dist/transport-stdio/write-queue.d.ts +48 -0
  182. package/dist/transport-stdio/write-queue.js +147 -0
  183. package/package.json +134 -4
@@ -0,0 +1,99 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { ServerError } from "../server-events/index.js";
3
+ /** Multi Round-Trip Request interim result. At least one field is required. */
4
+ export function inputRequired(input) {
5
+ if (input.inputRequests === undefined && input.requestState === undefined) {
6
+ throw new ServerError(-32603, "input_required needs inputRequests or requestState");
7
+ }
8
+ return {
9
+ resultType: "input_required",
10
+ ...(input.inputRequests !== undefined ? { inputRequests: input.inputRequests } : {}),
11
+ ...(input.requestState !== undefined ? { requestState: input.requestState } : {}),
12
+ };
13
+ }
14
+ /** Opaque, integrity-protected requestState (HMAC-SHA256 over method + payload). */
15
+ export function issueRequestState(secret, method, payload = {}) {
16
+ const body = Buffer.from(JSON.stringify({ method, payload }), "utf8");
17
+ const signature = createHmac("sha256", secret).update(body).digest("base64url");
18
+ return `${body.toString("base64url")}.${signature}`;
19
+ }
20
+ /** Verify and decode requestState; tampered or wrong-method state is rejected. */
21
+ export function verifyRequestState(secret, state, method) {
22
+ if (typeof state !== "string")
23
+ throw new ServerError(-32602, "requestState must be a string");
24
+ const [encoded, signature] = state.split(".");
25
+ if (!encoded || !signature)
26
+ throw new ServerError(-32602, "invalid requestState");
27
+ const body = Buffer.from(encoded, "base64url");
28
+ const expected = createHmac("sha256", secret).update(body).digest("base64url");
29
+ const a = Buffer.from(signature);
30
+ const b = Buffer.from(expected);
31
+ if (a.length !== b.length || !timingSafeEqual(a, b))
32
+ throw new ServerError(-32602, "invalid requestState");
33
+ try {
34
+ const parsed = JSON.parse(body.toString("utf8"));
35
+ if (parsed.method !== method || typeof parsed.payload !== "object" || parsed.payload === null) {
36
+ throw new ServerError(-32602, "requestState method mismatch");
37
+ }
38
+ return parsed.payload;
39
+ }
40
+ catch (error) {
41
+ if (error instanceof ServerError)
42
+ throw error;
43
+ throw new ServerError(-32602, "invalid requestState");
44
+ }
45
+ }
46
+ /** Validate a retry's inputResponses shape; unknown keys are ignored by design. */
47
+ export function readInputResponses(params) {
48
+ const responses = params.inputResponses;
49
+ if (responses === undefined)
50
+ return undefined;
51
+ if (typeof responses !== "object" || responses === null || Array.isArray(responses)) {
52
+ throw new ServerError(-32602, "inputResponses must be an object");
53
+ }
54
+ return responses;
55
+ }
56
+ /**
57
+ * Server-side MRTR correlation: issue an interim result, then validate the
58
+ * retry's requestState and inputResponses. States are single-use to prevent
59
+ * replay of one-time inputs.
60
+ */
61
+ export class MrtrRegistry {
62
+ secret;
63
+ #pending = new Map();
64
+ constructor(secret) {
65
+ this.secret = secret;
66
+ }
67
+ begin(method, input) {
68
+ const requestState = issueRequestState(this.secret, method, input.payload ?? {});
69
+ this.#pending.set(requestState, { method, ...(input.inputRequests !== undefined ? { inputRequests: input.inputRequests } : {}) });
70
+ return inputRequired({
71
+ ...(input.inputRequests !== undefined ? { inputRequests: input.inputRequests } : {}),
72
+ requestState,
73
+ });
74
+ }
75
+ /** Validate a retry and consume its state. Missing inputs are re-requested. */
76
+ resume(method, params) {
77
+ const state = params.requestState;
78
+ if (state === undefined) {
79
+ if (params.inputResponses !== undefined)
80
+ throw new ServerError(-32602, "inputResponses without requestState");
81
+ return { payload: {} };
82
+ }
83
+ const pending = this.#pending.get(state);
84
+ if (!pending || pending.method !== method)
85
+ throw new ServerError(-32602, "unknown or mismatched requestState");
86
+ const payload = verifyRequestState(this.secret, state, method);
87
+ if (pending.inputRequests) {
88
+ const responses = readInputResponses(params);
89
+ const missing = Object.keys(pending.inputRequests).filter((key) => responses?.[key] === undefined);
90
+ if (!responses || missing.length > 0) {
91
+ return { payload, retry: inputRequired({ inputRequests: pending.inputRequests, requestState: state }) };
92
+ }
93
+ this.#pending.delete(state);
94
+ return { inputResponses: responses, payload };
95
+ }
96
+ this.#pending.delete(state);
97
+ return { payload };
98
+ }
99
+ }
@@ -0,0 +1,21 @@
1
+ import { type Obj } from "../server-events/index.js";
2
+ export declare const PROTOCOL_VERSION = "2026-07-28";
3
+ export interface CacheHints {
4
+ /** Freshness hint in milliseconds; 0 means immediately stale. */
5
+ readonly ttlMs: number;
6
+ readonly cacheScope: "public" | "private";
7
+ }
8
+ export declare const DEFAULT_CACHE_HINTS: CacheHints;
9
+ /** Ordinary complete result, with optional CacheableResult fields. */
10
+ export declare function complete(result: Obj, cache?: CacheHints): Obj;
11
+ export interface Page<T> {
12
+ readonly items: readonly T[];
13
+ readonly nextCursor?: string;
14
+ }
15
+ /**
16
+ * Offset-based opaque server cursors. Input order must be deterministic;
17
+ * clients never see or parse the offset. Invalid cursors are -32602.
18
+ */
19
+ export declare function paginate<T>(items: readonly T[], cursor: unknown, pageSize?: number): Page<T>;
20
+ /** Validate the stateless per-request metadata required on every request. */
21
+ export declare function validateRequestMeta(params: Obj | undefined, supportedVersions?: readonly string[]): void;
@@ -0,0 +1,49 @@
1
+ import { ServerError } from "../server-events/index.js";
2
+ export const PROTOCOL_VERSION = "2026-07-28";
3
+ export const DEFAULT_CACHE_HINTS = { ttlMs: 0, cacheScope: "private" };
4
+ /** Ordinary complete result, with optional CacheableResult fields. */
5
+ export function complete(result, cache) {
6
+ return {
7
+ resultType: "complete",
8
+ ...result,
9
+ ...(cache !== undefined ? { ttlMs: cache.ttlMs, cacheScope: cache.cacheScope } : {}),
10
+ };
11
+ }
12
+ /**
13
+ * Offset-based opaque server cursors. Input order must be deterministic;
14
+ * clients never see or parse the offset. Invalid cursors are -32602.
15
+ */
16
+ export function paginate(items, cursor, pageSize = 100) {
17
+ let offset = 0;
18
+ if (cursor !== undefined && cursor !== null) {
19
+ if (typeof cursor !== "string" || !/^\d+$/u.test(cursor))
20
+ throw new ServerError(-32602, "invalid cursor");
21
+ offset = Number.parseInt(cursor, 10);
22
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > items.length) {
23
+ throw new ServerError(-32602, "invalid cursor");
24
+ }
25
+ }
26
+ const page = items.slice(offset, offset + pageSize);
27
+ return {
28
+ items: page,
29
+ ...(offset + pageSize < items.length ? { nextCursor: String(offset + pageSize) } : {}),
30
+ };
31
+ }
32
+ /** Validate the stateless per-request metadata required on every request. */
33
+ export function validateRequestMeta(params, supportedVersions = [PROTOCOL_VERSION]) {
34
+ const meta = params?.["_meta"];
35
+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {
36
+ throw new ServerError(-32602, "missing required _meta");
37
+ }
38
+ const version = meta["io.modelcontextprotocol/protocolVersion"];
39
+ if (typeof version !== "string" || !supportedVersions.includes(version)) {
40
+ throw new ServerError(-32022, "unsupported protocol version", {
41
+ requested: typeof version === "string" ? version : undefined,
42
+ supported: supportedVersions,
43
+ });
44
+ }
45
+ const capabilities = meta["io.modelcontextprotocol/clientCapabilities"];
46
+ if (typeof capabilities !== "object" || capabilities === null || Array.isArray(capabilities)) {
47
+ throw new ServerError(-32602, "missing io.modelcontextprotocol/clientCapabilities");
48
+ }
49
+ }
@@ -0,0 +1,105 @@
1
+ import type { JsonRpcNotification, JsonRpcRequest, RequestId } from "../core/index.js";
2
+ import { type SchemaValidator } from "../ops/index.js";
3
+ import { EventsServer, SubscriptionsServer, TaskCenter, type Obj } from "../server-events/index.js";
4
+ import { type CacheHints } from "./protocol.js";
5
+ import { SkillsRegistry, type SkillInput } from "./skills.js";
6
+ export interface ToolDefinition {
7
+ readonly name: string;
8
+ readonly description?: string;
9
+ readonly inputSchema?: Obj;
10
+ readonly outputSchema?: Obj;
11
+ readonly annotations?: Obj;
12
+ readonly handler: (args: unknown, ctx: {
13
+ readonly signal: AbortSignal;
14
+ readonly requestId: RequestId;
15
+ }) => unknown | Promise<unknown>;
16
+ }
17
+ export interface ResourceDefinition {
18
+ readonly uri: string;
19
+ readonly name: string;
20
+ readonly description?: string;
21
+ readonly mimeType?: string;
22
+ readonly handler: () => unknown | Promise<unknown>;
23
+ }
24
+ export interface ResourceTemplateDefinition {
25
+ readonly uriTemplate: string;
26
+ readonly name: string;
27
+ readonly description?: string;
28
+ readonly mimeType?: string;
29
+ readonly handler: (uri: string, vars: Record<string, string>) => unknown | Promise<unknown>;
30
+ }
31
+ export interface PromptDefinition {
32
+ readonly name: string;
33
+ readonly description?: string;
34
+ readonly arguments?: ReadonlyArray<{
35
+ readonly name: string;
36
+ readonly description?: string;
37
+ readonly required?: boolean;
38
+ }>;
39
+ readonly handler: (args: Record<string, string>) => unknown | Promise<unknown>;
40
+ }
41
+ export type CompletionHandler = (input: {
42
+ readonly ref: Obj;
43
+ readonly argument: {
44
+ readonly name: string;
45
+ readonly value: string;
46
+ };
47
+ readonly context?: Obj;
48
+ }) => {
49
+ readonly values: string[];
50
+ readonly total?: number;
51
+ readonly hasMore?: boolean;
52
+ } | Promise<{
53
+ readonly values: string[];
54
+ readonly total?: number;
55
+ readonly hasMore?: boolean;
56
+ }>;
57
+ export interface McpServerOptions {
58
+ readonly serverInfo: {
59
+ readonly name: string;
60
+ readonly version: string;
61
+ readonly title?: string;
62
+ };
63
+ readonly instructions?: string;
64
+ readonly supportedVersions?: readonly string[];
65
+ readonly cache?: CacheHints;
66
+ readonly pageSize?: number;
67
+ readonly validator?: SchemaValidator;
68
+ readonly subscriptions?: SubscriptionsServer;
69
+ readonly events?: EventsServer;
70
+ readonly tasks?: TaskCenter;
71
+ readonly skills?: SkillsRegistry;
72
+ readonly onComplete?: CompletionHandler;
73
+ }
74
+ /** Wrap a TaskCenter state as a task-handle result (resultType "task"). */
75
+ export declare function taskResult(state: Obj): Obj;
76
+ /**
77
+ * Transport-agnostic MCP 2026-07-28 server for the ordinary request surface:
78
+ * server/discover, tools, resources/templates, prompts, and completion.
79
+ * Push streams live in @mcp-client/server-events; the host owns JSON-RPC
80
+ * dispatch, error mapping, and transports.
81
+ */
82
+ export declare class McpServer {
83
+ #private;
84
+ constructor(options: McpServerOptions);
85
+ registerTool(def: ToolDefinition): this;
86
+ registerResource(def: ResourceDefinition): this;
87
+ registerResourceTemplate(def: ResourceTemplateDefinition): this;
88
+ registerPrompt(def: PromptDefinition): this;
89
+ get events(): EventsServer | undefined;
90
+ get subscriptions(): SubscriptionsServer | undefined;
91
+ get tasks(): TaskCenter | undefined;
92
+ get skills(): SkillsRegistry | undefined;
93
+ registerSkill(input: SkillInput): this;
94
+ capabilities(): Obj;
95
+ discover(): Obj;
96
+ /** Handle notifications/cancelled: aborts the in-flight request, if any. */
97
+ handleNotification(msg: JsonRpcNotification): void;
98
+ /** Abort an in-flight request. The host should suppress its response. */
99
+ cancel(requestId: RequestId): void;
100
+ wasCancelled(requestId: RequestId): boolean;
101
+ /** Handle one ordinary JSON-RPC request; throws ServerError for the host to map. */
102
+ handleRequest(msg: JsonRpcRequest): Promise<Obj>;
103
+ /** Public schema view for transports validating Mcp-Param-* headers. */
104
+ toolSchema(name: string): Obj | undefined;
105
+ }
@@ -0,0 +1,383 @@
1
+ import { createBuiltinValidator } from "../ops/index.js";
2
+ import { EventsServer, ServerError, SubscriptionsServer, TaskCenter, } from "../server-events/index.js";
3
+ import { complete, DEFAULT_CACHE_HINTS, paginate, PROTOCOL_VERSION, validateRequestMeta } from "./protocol.js";
4
+ import { matchUriTemplate } from "./uri.js";
5
+ import { SkillsRegistry } from "./skills.js";
6
+ /** Wrap a TaskCenter state as a task-handle result (resultType "task"). */
7
+ export function taskResult(state) {
8
+ return { resultType: "task", ...state };
9
+ }
10
+ /**
11
+ * Transport-agnostic MCP 2026-07-28 server for the ordinary request surface:
12
+ * server/discover, tools, resources/templates, prompts, and completion.
13
+ * Push streams live in @mcp-client/server-events; the host owns JSON-RPC
14
+ * dispatch, error mapping, and transports.
15
+ */
16
+ export class McpServer {
17
+ #options;
18
+ #validator;
19
+ #tools = new Map();
20
+ #resources = new Map();
21
+ #templates = new Map();
22
+ #prompts = new Map();
23
+ #compiled = new Map();
24
+ #versions;
25
+ #inFlight = new Map();
26
+ #cancelled = new Set();
27
+ constructor(options) {
28
+ this.#options = options;
29
+ this.#validator = options.validator ?? createBuiltinValidator();
30
+ this.#versions = options.supportedVersions ?? [PROTOCOL_VERSION];
31
+ }
32
+ registerTool(def) {
33
+ if (!def.name)
34
+ throw new ServerError(-32602, "tool name required");
35
+ const schema = def.inputSchema ?? { type: "object", properties: {} };
36
+ if (schema.type !== "object")
37
+ throw new ServerError(-32602, `tool ${def.name}: inputSchema must be type object`);
38
+ this.#compiled.set(def.name, this.#validator.compile(schema));
39
+ this.#tools.set(def.name, def);
40
+ this.#options.subscriptions?.notifyToolsChanged();
41
+ return this;
42
+ }
43
+ registerResource(def) {
44
+ this.#resources.set(def.uri, def);
45
+ this.#options.subscriptions?.notifyResourcesChanged();
46
+ return this;
47
+ }
48
+ registerResourceTemplate(def) {
49
+ this.#templates.set(def.uriTemplate, def);
50
+ this.#options.subscriptions?.notifyResourcesChanged();
51
+ return this;
52
+ }
53
+ registerPrompt(def) {
54
+ this.#prompts.set(def.name, def);
55
+ this.#options.subscriptions?.notifyPromptsChanged();
56
+ return this;
57
+ }
58
+ get events() {
59
+ return this.#options.events;
60
+ }
61
+ get subscriptions() {
62
+ return this.#options.subscriptions;
63
+ }
64
+ get tasks() {
65
+ return this.#options.tasks;
66
+ }
67
+ get skills() {
68
+ return this.#options.skills;
69
+ }
70
+ registerSkill(input) {
71
+ const registry = this.#options.skills ?? new SkillsRegistry();
72
+ registry.register(input);
73
+ this.#options.skills = registry;
74
+ return this;
75
+ }
76
+ capabilities() {
77
+ const caps = {};
78
+ const listChanged = this.#options.subscriptions !== undefined;
79
+ if (this.#tools.size > 0)
80
+ caps.tools = listChanged ? { listChanged: true } : {};
81
+ if (this.#resources.size > 0 || this.#templates.size > 0 || this.#options.skills !== undefined) {
82
+ caps.resources = listChanged ? { listChanged: true, subscribe: true } : {};
83
+ }
84
+ if (this.#prompts.size > 0)
85
+ caps.prompts = listChanged ? { listChanged: true } : {};
86
+ if (this.#options.onComplete)
87
+ caps.completions = {};
88
+ const extensions = {
89
+ ...this.#options.events?.capabilities().extensions,
90
+ ...this.#options.tasks?.capabilities().extensions,
91
+ ...this.#options.skills?.capabilities().extensions,
92
+ };
93
+ if (Object.keys(extensions).length > 0)
94
+ caps.extensions = extensions;
95
+ return caps;
96
+ }
97
+ discover() {
98
+ return complete({
99
+ supportedVersions: [...this.#versions],
100
+ capabilities: this.capabilities(),
101
+ serverInfo: this.#options.serverInfo,
102
+ ...(this.#options.instructions !== undefined ? { instructions: this.#options.instructions } : {}),
103
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
104
+ }
105
+ /** Handle notifications/cancelled: aborts the in-flight request, if any. */
106
+ handleNotification(msg) {
107
+ if (msg.method !== "notifications/cancelled")
108
+ return;
109
+ const requestId = msg.params?.requestId;
110
+ if (typeof requestId === "string" || typeof requestId === "number")
111
+ this.cancel(requestId);
112
+ }
113
+ /** Abort an in-flight request. The host should suppress its response. */
114
+ cancel(requestId) {
115
+ this.#cancelled.add(requestId);
116
+ this.#inFlight.get(requestId)?.abort();
117
+ }
118
+ wasCancelled(requestId) {
119
+ return this.#cancelled.has(requestId);
120
+ }
121
+ /** Handle one ordinary JSON-RPC request; throws ServerError for the host to map. */
122
+ async handleRequest(msg) {
123
+ const ac = new AbortController();
124
+ this.#inFlight.set(msg.id, ac);
125
+ if (this.#cancelled.has(msg.id))
126
+ ac.abort();
127
+ try {
128
+ return await this.#handleRequest(msg, ac.signal);
129
+ }
130
+ finally {
131
+ this.#inFlight.delete(msg.id);
132
+ }
133
+ }
134
+ async #handleRequest(msg, signal) {
135
+ const params = (msg.params ?? {});
136
+ validateRequestMeta(params, this.#versions);
137
+ switch (msg.method) {
138
+ case "server/discover":
139
+ return this.discover();
140
+ case "tools/list": {
141
+ const tools = [...this.#tools.values()].sort((a, b) => a.name.localeCompare(b.name));
142
+ const page = paginate(tools, params.cursor, this.#options.pageSize);
143
+ return complete({
144
+ tools: page.items.map((tool) => this.#toolSchema(tool)),
145
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
146
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
147
+ }
148
+ case "tools/call":
149
+ return this.#callTool(params, msg.id, signal);
150
+ case "resources/list": {
151
+ const resources = [...this.#resources.values()].sort((a, b) => a.uri.localeCompare(b.uri));
152
+ const page = paginate(resources, params.cursor, this.#options.pageSize);
153
+ return complete({
154
+ resources: page.items.map((r) => this.#resourceSchema(r)),
155
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
156
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
157
+ }
158
+ case "resources/templates/list": {
159
+ const templates = [...this.#templates.values()].sort((a, b) => a.uriTemplate.localeCompare(b.uriTemplate));
160
+ const page = paginate(templates, params.cursor, this.#options.pageSize);
161
+ return complete({
162
+ resourceTemplates: page.items.map((t) => ({
163
+ uriTemplate: t.uriTemplate,
164
+ name: t.name,
165
+ ...(t.description !== undefined ? { description: t.description } : {}),
166
+ ...(t.mimeType !== undefined ? { mimeType: t.mimeType } : {}),
167
+ })),
168
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
169
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
170
+ }
171
+ case "resources/read":
172
+ return this.#readResource(params);
173
+ case "prompts/list": {
174
+ const prompts = [...this.#prompts.values()].sort((a, b) => a.name.localeCompare(b.name));
175
+ const page = paginate(prompts, params.cursor, this.#options.pageSize);
176
+ return complete({
177
+ prompts: page.items.map((p) => ({
178
+ name: p.name,
179
+ ...(p.description !== undefined ? { description: p.description } : {}),
180
+ ...(p.arguments !== undefined ? { arguments: p.arguments } : {}),
181
+ })),
182
+ ...(page.nextCursor !== undefined ? { nextCursor: page.nextCursor } : {}),
183
+ }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
184
+ }
185
+ case "prompts/get":
186
+ return this.#getPrompt(params);
187
+ case "completion/complete":
188
+ return this.#complete(params);
189
+ case "events/list":
190
+ return this.#events().list();
191
+ case "events/poll":
192
+ return this.#events().poll(params);
193
+ case "tasks/get":
194
+ return this.#tasks().get(params);
195
+ case "tasks/cancel":
196
+ return this.#tasks().cancel(params);
197
+ case "tasks/update":
198
+ return this.#tasks().update(params);
199
+ case "skills/list":
200
+ return this.#skills().list(params.cursor, this.#options.cache ?? DEFAULT_CACHE_HINTS);
201
+ case "skills/get": {
202
+ if (typeof params.uri !== "string")
203
+ throw new ServerError(-32602, "skill uri required");
204
+ return this.#skills().get(params.uri, this.#options.cache ?? DEFAULT_CACHE_HINTS);
205
+ }
206
+ case "subscriptions/listen":
207
+ case "events/stream":
208
+ throw new ServerError(-32601, `${msg.method} requires a PushChannel from the host transport`);
209
+ default:
210
+ throw new ServerError(-32601, `method not found: ${msg.method}`);
211
+ }
212
+ }
213
+ #events() {
214
+ if (!this.#options.events)
215
+ throw new ServerError(-32601, "events extension unavailable");
216
+ return this.#options.events;
217
+ }
218
+ #tasks() {
219
+ if (!this.#options.tasks)
220
+ throw new ServerError(-32601, "tasks extension unavailable");
221
+ return this.#options.tasks;
222
+ }
223
+ #skills() {
224
+ if (!this.#options.skills)
225
+ throw new ServerError(-32601, "skills extension unavailable");
226
+ return this.#options.skills;
227
+ }
228
+ #toolSchema(tool) {
229
+ return {
230
+ name: tool.name,
231
+ ...(tool.description !== undefined ? { description: tool.description } : {}),
232
+ inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
233
+ ...(tool.outputSchema !== undefined ? { outputSchema: tool.outputSchema } : {}),
234
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
235
+ };
236
+ }
237
+ /** Public schema view for transports validating Mcp-Param-* headers. */
238
+ toolSchema(name) {
239
+ const tool = this.#tools.get(name);
240
+ return tool ? this.#toolSchema(tool) : undefined;
241
+ }
242
+ #resourceSchema(resource) {
243
+ return {
244
+ uri: resource.uri,
245
+ name: resource.name,
246
+ ...(resource.description !== undefined ? { description: resource.description } : {}),
247
+ ...(resource.mimeType !== undefined ? { mimeType: resource.mimeType } : {}),
248
+ };
249
+ }
250
+ async #callTool(params, requestId, signal) {
251
+ const name = params.name;
252
+ if (typeof name !== "string")
253
+ throw new ServerError(-32602, "tool name required");
254
+ const tool = this.#tools.get(name);
255
+ if (!tool)
256
+ throw new ServerError(-32602, `unknown tool: ${name}`);
257
+ const compiled = this.#compiled.get(name);
258
+ if (compiled && !compiled.ok)
259
+ throw new ServerError(-32603, `tool ${name}: ${compiled.message}`);
260
+ const args = params.arguments ?? {};
261
+ if (compiled?.ok) {
262
+ const verdict = compiled.validate(args);
263
+ if (!verdict.valid)
264
+ throw new ServerError(-32602, `invalid tool arguments: ${verdict.errors[0]?.message ?? "schema mismatch"}`, { issues: verdict.errors });
265
+ }
266
+ let returned;
267
+ try {
268
+ if (signal.aborted)
269
+ throw new ServerError(-32800, "request cancelled");
270
+ returned = await tool.handler(args, { signal, requestId });
271
+ if (signal.aborted)
272
+ throw new ServerError(-32800, "request cancelled");
273
+ }
274
+ catch (error) {
275
+ if (error instanceof ServerError)
276
+ throw error;
277
+ if (signal.aborted)
278
+ throw new ServerError(-32800, "request cancelled");
279
+ return complete({
280
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
281
+ isError: true,
282
+ });
283
+ }
284
+ if (typeof returned === "object" && returned !== null && "resultType" in returned)
285
+ return returned;
286
+ const result = normalizeToolResult(returned);
287
+ if (tool.outputSchema && result.structuredContent !== undefined) {
288
+ const output = this.#validator.compile(tool.outputSchema);
289
+ if (!output.ok)
290
+ throw new ServerError(-32603, `tool ${name}: ${output.message}`);
291
+ const verdict = output.validate(result.structuredContent);
292
+ if (!verdict.valid)
293
+ throw new ServerError(-32603, `tool ${name}: output does not match outputSchema`, { issues: verdict.errors });
294
+ }
295
+ return complete(result);
296
+ }
297
+ async #readResource(params) {
298
+ const uri = params.uri;
299
+ if (typeof uri !== "string")
300
+ throw new ServerError(-32602, "resource uri required");
301
+ const exact = this.#resources.get(uri);
302
+ if (exact) {
303
+ return complete({ contents: await resourceContents(uri, exact.mimeType, await exact.handler()) }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
304
+ }
305
+ for (const template of this.#templates.values()) {
306
+ const vars = matchUriTemplate(template.uriTemplate, uri);
307
+ if (vars) {
308
+ return complete({ contents: await resourceContents(uri, template.mimeType, await template.handler(uri, vars)) }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
309
+ }
310
+ }
311
+ const skillFile = this.#options.skills?.read(uri);
312
+ if (skillFile)
313
+ return complete({ contents: [skillFile] }, this.#options.cache ?? DEFAULT_CACHE_HINTS);
314
+ throw new ServerError(-32602, `resource not found: ${uri}`);
315
+ }
316
+ async #getPrompt(params) {
317
+ const name = params.name;
318
+ if (typeof name !== "string")
319
+ throw new ServerError(-32602, "prompt name required");
320
+ const prompt = this.#prompts.get(name);
321
+ if (!prompt)
322
+ throw new ServerError(-32602, `unknown prompt: ${name}`);
323
+ const args = params.arguments ?? {};
324
+ if (typeof args !== "object" || args === null || Array.isArray(args))
325
+ throw new ServerError(-32602, "prompt arguments must be an object");
326
+ for (const arg of prompt.arguments ?? []) {
327
+ if (arg.required === true && typeof args[arg.name] !== "string") {
328
+ throw new ServerError(-32602, `missing required prompt argument: ${arg.name}`);
329
+ }
330
+ }
331
+ const returned = await prompt.handler(args);
332
+ const result = Array.isArray(returned) ? { messages: returned } : returned;
333
+ if (typeof result !== "object" || result === null || !Array.isArray(result.messages)) {
334
+ throw new ServerError(-32603, `prompt ${name}: handler must return messages`);
335
+ }
336
+ return complete(result);
337
+ }
338
+ async #complete(params) {
339
+ const handler = this.#options.onComplete;
340
+ if (!handler)
341
+ throw new ServerError(-32601, "completion unavailable");
342
+ const argument = params.argument;
343
+ if (typeof argument !== "object" || argument === null || typeof argument.name !== "string" || typeof argument.value !== "string") {
344
+ throw new ServerError(-32602, "completion argument.name/value required");
345
+ }
346
+ const ref = params.ref;
347
+ if (typeof ref !== "object" || ref === null)
348
+ throw new ServerError(-32602, "completion ref required");
349
+ const result = await handler({
350
+ ref: ref,
351
+ argument: argument,
352
+ ...(params.context !== undefined ? { context: params.context } : {}),
353
+ });
354
+ const values = result.values.slice(0, 100);
355
+ return complete({
356
+ completion: {
357
+ values,
358
+ ...(result.total !== undefined ? { total: result.total } : {}),
359
+ ...(result.hasMore !== undefined || result.values.length > 100 ? { hasMore: result.hasMore ?? true } : {}),
360
+ },
361
+ });
362
+ }
363
+ }
364
+ function normalizeToolResult(returned) {
365
+ if (typeof returned === "object" && returned !== null && Array.isArray(returned.content))
366
+ return returned;
367
+ return { content: [{ type: "text", text: typeof returned === "string" ? returned : JSON.stringify(returned) }] };
368
+ }
369
+ async function resourceContents(uri, mimeType, returned) {
370
+ const entries = Array.isArray(returned) ? returned : [returned];
371
+ return entries.map((entry) => {
372
+ if (typeof entry === "string")
373
+ return { uri, text: entry, ...(mimeType !== undefined ? { mimeType } : {}) };
374
+ if (typeof entry !== "object" || entry === null)
375
+ throw new ServerError(-32603, "resource handler returned invalid contents");
376
+ const obj = entry;
377
+ const hasText = "text" in obj;
378
+ const hasBlob = "blob" in obj;
379
+ if (hasText === hasBlob)
380
+ throw new ServerError(-32603, "resource contents need exactly one of text/blob");
381
+ return { uri, ...obj, ...(mimeType !== undefined && obj.mimeType === undefined ? { mimeType } : {}) };
382
+ });
383
+ }