@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,101 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { systemClock } from "../core/index.js";
3
+ import { notification, object, ServerError } from "./types.js";
4
+ import { requireTaskId } from "./subscriptions.js";
5
+ export const TASKS_EXTENSION_ID = "io.modelcontextprotocol/tasks";
6
+ const TERMINAL = new Set(["completed", "failed", "cancelled"]);
7
+ /**
8
+ * Optional async-task companion to the push center: task handles whose state
9
+ * changes are emitted as notifications/tasks and published on the "tasks"
10
+ * event stream. No tools framework — hosts decide which operations start tasks.
11
+ */
12
+ export class TaskCenter {
13
+ #tasks = new Map();
14
+ #clock;
15
+ #bus;
16
+ #channels = new Set();
17
+ constructor(opts = {}) {
18
+ this.#bus = opts.bus;
19
+ this.#clock = opts.clock ?? systemClock;
20
+ }
21
+ capabilities() {
22
+ return { extensions: { [TASKS_EXTENSION_ID]: {} } };
23
+ }
24
+ /** Attach a push channel (e.g. a subscriptions/listen channel) for notifications/tasks. */
25
+ attach(channel) {
26
+ this.#channels.add(channel);
27
+ channel.onClose(() => this.#channels.delete(channel));
28
+ }
29
+ create(init = {}) {
30
+ const state = {
31
+ taskId: init.taskId ?? randomUUID(),
32
+ status: init.inputRequests ? "input_required" : "working",
33
+ createdAt: new Date(this.#clock.now()).toISOString(),
34
+ ...(init.ttlMs !== undefined ? { ttlMs: init.ttlMs } : {}),
35
+ ...(init.pollIntervalMs !== undefined ? { pollIntervalMs: init.pollIntervalMs } : {}),
36
+ ...(init.inputRequests !== undefined ? { inputRequests: init.inputRequests } : {}),
37
+ };
38
+ this.#tasks.set(state.taskId, state);
39
+ this.#emit(state);
40
+ return state;
41
+ }
42
+ get(params) {
43
+ return this.#expireIfNeeded(this.#state(requireTaskId(params)));
44
+ }
45
+ cancel(params) {
46
+ const state = this.#expireIfNeeded(this.#state(requireTaskId(params)));
47
+ if (TERMINAL.has(state.status))
48
+ return state;
49
+ return this.#set(state.taskId, { status: "cancelled" });
50
+ }
51
+ /** Client input for an input_required task; resumes work. */
52
+ update(params) {
53
+ const state = this.#state(requireTaskId(params));
54
+ if (state.status !== "input_required")
55
+ throw new ServerError(-32602, "task is not awaiting input");
56
+ const inputResponses = params.inputResponses;
57
+ if (!object(inputResponses))
58
+ throw new ServerError(-32602, "inputResponses must be an object");
59
+ const next = { ...state, status: "working", inputResponses };
60
+ delete next.inputRequests;
61
+ return this.#set(state.taskId, next);
62
+ }
63
+ requestInput(taskId, inputRequests) {
64
+ this.#state(taskId);
65
+ return this.#set(taskId, { status: "input_required", inputRequests });
66
+ }
67
+ complete(taskId, result) {
68
+ this.#state(taskId);
69
+ return this.#set(taskId, { status: "completed", result });
70
+ }
71
+ fail(taskId, error) {
72
+ this.#state(taskId);
73
+ return this.#set(taskId, { status: "failed", error });
74
+ }
75
+ #state(taskId) {
76
+ const state = this.#tasks.get(taskId);
77
+ if (!state)
78
+ throw new ServerError(-32602, `unknown task: ${taskId}`);
79
+ return state;
80
+ }
81
+ #expireIfNeeded(state) {
82
+ if (TERMINAL.has(state.status) || state.ttlMs === undefined)
83
+ return state;
84
+ const createdAt = typeof state.createdAt === "string" ? Date.parse(state.createdAt) : Number.NaN;
85
+ if (Number.isFinite(createdAt) && createdAt + state.ttlMs <= this.#clock.now()) {
86
+ return this.#set(state.taskId, { status: "failed", error: { code: "task-expired" } });
87
+ }
88
+ return state;
89
+ }
90
+ #set(taskId, patch) {
91
+ const state = { ...this.#state(taskId), ...patch, taskId };
92
+ this.#tasks.set(taskId, state);
93
+ this.#emit(state);
94
+ return state;
95
+ }
96
+ #emit(state) {
97
+ for (const channel of this.#channels)
98
+ channel.notify(notification("notifications/tasks", { ...state }, channel.id));
99
+ this.#bus?.publish("tasks", state, {});
100
+ }
101
+ }
@@ -0,0 +1,25 @@
1
+ import type { JsonRpcNotification, RequestId } from "../core/index.js";
2
+ export type Obj = Record<string, unknown>;
3
+ /**
4
+ * Host-owned channel for one long-lived server response stream.
5
+ * The host transport creates one per subscriptions/listen or events/stream
6
+ * request and delivers notifications/final results to the client.
7
+ */
8
+ export interface PushChannel {
9
+ readonly id: RequestId;
10
+ notify(notification: JsonRpcNotification): void;
11
+ /** Final JSON-RPC result for the stream request (graceful close). */
12
+ finish(result: Obj): void;
13
+ /** Register cleanup for client disconnect/cancel. */
14
+ onClose(fn: () => void): void;
15
+ }
16
+ /** Error with a JSON-RPC code, for hosts to map onto error responses. */
17
+ export declare class ServerError extends Error {
18
+ readonly code: number;
19
+ readonly data?: unknown;
20
+ constructor(code: number, message: string, data?: unknown);
21
+ }
22
+ export declare function notification(method: string, params: Obj, subscriptionId?: RequestId): JsonRpcNotification;
23
+ export declare function object(x: unknown): x is Obj;
24
+ /** Deterministic key for name+arguments subscription identity. */
25
+ export declare function streamKey(name: string, args: Obj): string;
@@ -0,0 +1,34 @@
1
+ /** Error with a JSON-RPC code, for hosts to map onto error responses. */
2
+ export class ServerError extends Error {
3
+ code;
4
+ data;
5
+ constructor(code, message, data) {
6
+ super(message);
7
+ this.code = code;
8
+ this.data = data;
9
+ this.name = "ServerError";
10
+ }
11
+ }
12
+ export function notification(method, params, subscriptionId) {
13
+ return {
14
+ jsonrpc: "2.0",
15
+ method,
16
+ params: subscriptionId === undefined
17
+ ? params
18
+ : { ...params, _meta: { "io.modelcontextprotocol/subscriptionId": subscriptionId } },
19
+ };
20
+ }
21
+ export function object(x) {
22
+ return typeof x === "object" && x !== null && !Array.isArray(x);
23
+ }
24
+ /** Deterministic key for name+arguments subscription identity. */
25
+ export function streamKey(name, args) {
26
+ const stable = (v) => {
27
+ if (Array.isArray(v))
28
+ return v.map(stable);
29
+ if (object(v))
30
+ return Object.fromEntries(Object.keys(v).sort().map((k) => [k, stable(v[k])]));
31
+ return v;
32
+ };
33
+ return JSON.stringify([name, stable(args)]);
34
+ }
@@ -0,0 +1,20 @@
1
+ export interface ResourceAuthContext {
2
+ readonly contextId: string;
3
+ readonly scopes?: readonly string[];
4
+ }
5
+ /** Resource-side bearer check; return undefined to reject with 401. */
6
+ export interface BearerAuthenticator {
7
+ authenticate(authorization: string | undefined): Promise<ResourceAuthContext | undefined> | ResourceAuthContext | undefined;
8
+ }
9
+ export declare class StaticBearerAuth implements BearerAuthenticator {
10
+ #private;
11
+ constructor(token: string, contextId?: string);
12
+ authenticate(authorization: string | undefined): ResourceAuthContext | undefined;
13
+ }
14
+ /** RFC 9728 Protected Resource Metadata document for hosts to serve. */
15
+ export declare function buildProtectedResourceMetadata(input: {
16
+ readonly resource: string;
17
+ readonly authorizationServers: readonly string[];
18
+ readonly scopesSupported?: readonly string[];
19
+ }): Record<string, unknown>;
20
+ export declare function bearerChallenge(resourceMetadataUrl: string, scope?: string): string;
@@ -0,0 +1,29 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ export class StaticBearerAuth {
3
+ #token;
4
+ #contextId;
5
+ constructor(token, contextId = "static") {
6
+ this.#token = token;
7
+ this.#contextId = contextId;
8
+ }
9
+ authenticate(authorization) {
10
+ if (authorization !== `Bearer ${this.#token}`)
11
+ return undefined;
12
+ const a = Buffer.from(authorization);
13
+ const b = Buffer.from(`Bearer ${this.#token}`);
14
+ if (a.length !== b.length || !timingSafeEqual(a, b))
15
+ return undefined;
16
+ return { contextId: this.#contextId };
17
+ }
18
+ }
19
+ /** RFC 9728 Protected Resource Metadata document for hosts to serve. */
20
+ export function buildProtectedResourceMetadata(input) {
21
+ return {
22
+ resource: input.resource,
23
+ authorization_servers: [...input.authorizationServers],
24
+ ...(input.scopesSupported !== undefined ? { scopes_supported: [...input.scopesSupported] } : {}),
25
+ };
26
+ }
27
+ export function bearerChallenge(resourceMetadataUrl, scope) {
28
+ return `Bearer resource_metadata="${resourceMetadataUrl}"${scope !== undefined ? `, scope="${scope}"` : ""}`;
29
+ }
@@ -0,0 +1,17 @@
1
+ import type { JsonRpcErrorResponse, JsonRpcNotification, JsonRpcResponse, RequestId } from "../core/index.js";
2
+ import { type Obj, type PushChannel } from "../server-events/index.js";
3
+ export declare function resultResponse(id: RequestId, result: Obj): JsonRpcResponse;
4
+ export declare function errorResponse(id: RequestId, error: unknown): JsonRpcErrorResponse;
5
+ /** Host channel: fanout notifications and one final result, with close cleanup. */
6
+ export declare class HostChannel implements PushChannel {
7
+ #private;
8
+ readonly id: RequestId;
9
+ private readonly sendNotification;
10
+ private readonly sendResult;
11
+ closed: boolean;
12
+ constructor(id: RequestId, sendNotification: (notification: JsonRpcNotification) => void, sendResult: (result: Obj) => void);
13
+ notify(notification: JsonRpcNotification): void;
14
+ finish(result: Obj): void;
15
+ onClose(fn: () => void): void;
16
+ close(): void;
17
+ }
@@ -0,0 +1,47 @@
1
+ import { ServerError } from "../server-events/index.js";
2
+ export function resultResponse(id, result) {
3
+ return { jsonrpc: "2.0", id, result };
4
+ }
5
+ export function errorResponse(id, error) {
6
+ if (error instanceof ServerError) {
7
+ return {
8
+ jsonrpc: "2.0",
9
+ id,
10
+ error: { code: error.code, message: error.message, ...(error.data !== undefined ? { data: error.data } : {}) },
11
+ };
12
+ }
13
+ return { jsonrpc: "2.0", id, error: { code: -32603, message: error instanceof Error ? error.message : String(error) } };
14
+ }
15
+ /** Host channel: fanout notifications and one final result, with close cleanup. */
16
+ export class HostChannel {
17
+ id;
18
+ sendNotification;
19
+ sendResult;
20
+ #closers = [];
21
+ closed = false;
22
+ constructor(id, sendNotification, sendResult) {
23
+ this.id = id;
24
+ this.sendNotification = sendNotification;
25
+ this.sendResult = sendResult;
26
+ }
27
+ notify(notification) {
28
+ if (!this.closed)
29
+ this.sendNotification(notification);
30
+ }
31
+ finish(result) {
32
+ if (this.closed)
33
+ return;
34
+ this.sendResult(result);
35
+ this.close();
36
+ }
37
+ onClose(fn) {
38
+ this.#closers.push(fn);
39
+ }
40
+ close() {
41
+ if (this.closed)
42
+ return;
43
+ this.closed = true;
44
+ for (const fn of this.#closers)
45
+ fn();
46
+ }
47
+ }
@@ -0,0 +1,19 @@
1
+ import { type IncomingMessage, type Server, type ServerResponse } from "node:http";
2
+ import type { McpServer } from "../server/index.js";
3
+ import { type BearerAuthenticator } from "./auth.js";
4
+ export interface HttpServerHostOptions {
5
+ readonly server: McpServer;
6
+ readonly path?: string;
7
+ readonly auth?: BearerAuthenticator;
8
+ readonly resourceMetadataUrl?: string;
9
+ /** Allowed Origin values; default loopback origins only (plus no Origin). */
10
+ readonly allowedOrigins?: readonly string[] | ((origin: string) => boolean);
11
+ readonly maxBodyBytes?: number;
12
+ }
13
+ /** Streamable HTTP host: POST-only, header enforcement, SSE streams, bearer auth. */
14
+ export declare class HttpServerHost {
15
+ #private;
16
+ constructor(options: HttpServerHostOptions);
17
+ createServer(): Server;
18
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
19
+ }
@@ -0,0 +1,209 @@
1
+ import { createServer } from "node:http";
2
+ import { ServerError } from "../server-events/index.js";
3
+ import { encodeHeaderValue, extractAtPath, validateXmcpHeaderSchema } from "../transport-http/index.js";
4
+ import { bearerChallenge } from "./auth.js";
5
+ import { errorResponse, HostChannel, resultResponse } from "./channel.js";
6
+ function decodeHeaderValue(value) {
7
+ const match = /^=\?base64\?(.+)\?=$/u.exec(value);
8
+ return match ? Buffer.from(match[1], "base64").toString("utf8") : value;
9
+ }
10
+ function isLoopbackOrigin(origin) {
11
+ try {
12
+ return ["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname);
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ /** Streamable HTTP host: POST-only, header enforcement, SSE streams, bearer auth. */
19
+ export class HttpServerHost {
20
+ #options;
21
+ #path;
22
+ constructor(options) {
23
+ this.#options = options;
24
+ this.#path = options.path ?? "/mcp";
25
+ }
26
+ createServer() {
27
+ return createServer((req, res) => {
28
+ void this.handle(req, res).catch((error) => {
29
+ if (!res.headersSent) {
30
+ res.writeHead(500, { "Content-Type": "application/json" });
31
+ res.end(JSON.stringify(errorResponse(0, error)));
32
+ }
33
+ else if (!res.writableEnded)
34
+ res.end();
35
+ });
36
+ });
37
+ }
38
+ async handle(req, res) {
39
+ const url = new URL(req.url ?? "/", "http://localhost");
40
+ if (req.method === "GET" && url.pathname === "/healthz") {
41
+ this.#json(res, 200, { ok: true });
42
+ return;
43
+ }
44
+ if (url.pathname !== this.#path) {
45
+ this.#json(res, 404, errorResponse(0, new ServerError(-32601, "not found")));
46
+ return;
47
+ }
48
+ if (req.method !== "POST") {
49
+ res.writeHead(405, { Allow: "POST", "Content-Type": "application/json" });
50
+ res.end(JSON.stringify(errorResponse(0, new ServerError(-32601, "method not allowed"))));
51
+ return;
52
+ }
53
+ const origin = req.headers.origin;
54
+ if (origin !== undefined && !this.#originAllowed(origin)) {
55
+ this.#json(res, 403, errorResponse(0, new ServerError(-32602, "forbidden origin")));
56
+ return;
57
+ }
58
+ const accept = req.headers.accept ?? "";
59
+ if (!accept.includes("application/json") || !accept.includes("text/event-stream")) {
60
+ this.#json(res, 406, errorResponse(0, new ServerError(-32602, "Accept must include application/json and text/event-stream")));
61
+ return;
62
+ }
63
+ let msg;
64
+ try {
65
+ const text = await this.#body(req);
66
+ const parsed = JSON.parse(text);
67
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
68
+ throw new Error("single JSON-RPC message required");
69
+ msg = parsed;
70
+ }
71
+ catch (error) {
72
+ this.#json(res, 400, errorResponse(0, new ServerError(-32700, error instanceof Error ? error.message : "parse error")));
73
+ return;
74
+ }
75
+ const id = "id" in msg ? msg.id : undefined;
76
+ const params = (msg.params ?? {});
77
+ const meta = (params._meta ?? {});
78
+ const version = req.headers["mcp-protocol-version"];
79
+ const methodHeader = req.headers["mcp-method"];
80
+ if (version !== meta["io.modelcontextprotocol/protocolVersion"] || methodHeader !== msg.method) {
81
+ this.#json(res, 400, errorResponse(id ?? 0, new ServerError(-32020, "header mismatch")));
82
+ return;
83
+ }
84
+ if (typeof params.name === "string") {
85
+ const nameHeader = req.headers["mcp-name"];
86
+ if (typeof nameHeader !== "string" || decodeHeaderValue(nameHeader) !== params.name) {
87
+ this.#json(res, 400, errorResponse(id ?? 0, new ServerError(-32020, "Mcp-Name mismatch")));
88
+ return;
89
+ }
90
+ }
91
+ if (this.#options.auth) {
92
+ const context = await this.#options.auth.authenticate(req.headers.authorization);
93
+ if (!context) {
94
+ const metadata = this.#options.resourceMetadataUrl ?? `http://${req.headers.host ?? "localhost"}/.well-known/oauth-protected-resource${this.#path}`;
95
+ res.writeHead(401, { "WWW-Authenticate": bearerChallenge(metadata), "Content-Type": "application/json" });
96
+ res.end(JSON.stringify(errorResponse(id ?? 0, new ServerError(-32602, "unauthorized"))));
97
+ return;
98
+ }
99
+ }
100
+ if (id === undefined) {
101
+ this.#options.server.handleNotification(msg);
102
+ res.writeHead(202).end();
103
+ return;
104
+ }
105
+ const request = msg;
106
+ if (request.method === "tools/call") {
107
+ const mismatch = this.#paramMismatch(request, req);
108
+ if (mismatch) {
109
+ this.#json(res, 400, errorResponse(id, new ServerError(-32020, mismatch)));
110
+ return;
111
+ }
112
+ }
113
+ if (request.method === "subscriptions/listen" || request.method === "events/stream") {
114
+ this.#openStream(request, res);
115
+ return;
116
+ }
117
+ try {
118
+ const result = await this.#options.server.handleRequest(request);
119
+ if (this.#options.server.wasCancelled(id)) {
120
+ res.writeHead(202).end();
121
+ return;
122
+ }
123
+ this.#json(res, 200, resultResponse(id, result));
124
+ }
125
+ catch (error) {
126
+ if (this.#options.server.wasCancelled(id)) {
127
+ res.writeHead(202).end();
128
+ return;
129
+ }
130
+ const status = error instanceof ServerError && [-32602, -32020, -32022].includes(error.code) ? 400 : 200;
131
+ this.#json(res, status, errorResponse(id, error));
132
+ }
133
+ }
134
+ #paramMismatch(request, req) {
135
+ const params = (request.params ?? {});
136
+ const schema = this.#options.server.toolSchema(String(params.name));
137
+ if (!schema)
138
+ return undefined;
139
+ const validation = validateXmcpHeaderSchema(schema.inputSchema);
140
+ if (!validation.valid)
141
+ return `server tool has invalid x-mcp-header annotations: ${validation.violations[0]}`;
142
+ for (const param of validation.params) {
143
+ const headerName = `mcp-param-${param.headerName.toLowerCase()}`;
144
+ const header = req.headers[headerName];
145
+ const value = extractAtPath(params.arguments, param.path);
146
+ if (value === undefined || value === null) {
147
+ if (header !== undefined)
148
+ return `Mcp-Param-${param.headerName} must be omitted`;
149
+ continue;
150
+ }
151
+ const expected = encodeHeaderValue(value);
152
+ if (header !== expected)
153
+ return `Mcp-Param-${param.headerName} does not match the request body`;
154
+ }
155
+ return undefined;
156
+ }
157
+ #openStream(request, res) {
158
+ res.writeHead(200, {
159
+ "Content-Type": "text/event-stream",
160
+ "Cache-Control": "no-cache",
161
+ Connection: "keep-alive",
162
+ });
163
+ res.write(": mcp-stream-open\n\n");
164
+ const channel = new HostChannel(request.id, (notification) => res.write(`data: ${JSON.stringify(notification)}\n\n`), (result) => {
165
+ res.write(`data: ${JSON.stringify(resultResponse(request.id, result))}\n\n`, () => res.end());
166
+ });
167
+ res.on("close", () => channel.close());
168
+ try {
169
+ if (request.method === "subscriptions/listen") {
170
+ const subscriptions = this.#options.server.subscriptions;
171
+ if (!subscriptions)
172
+ throw new ServerError(-32601, "subscriptions unavailable");
173
+ subscriptions.listen(channel, (request.params ?? {}));
174
+ this.#options.server.tasks?.attach(channel);
175
+ }
176
+ else {
177
+ const events = this.#options.server.events;
178
+ if (!events)
179
+ throw new ServerError(-32601, "events unavailable");
180
+ events.stream(channel, (request.params ?? {}));
181
+ }
182
+ }
183
+ catch (error) {
184
+ res.write(`data: ${JSON.stringify(errorResponse(request.id, error))}\n\n`, () => res.end());
185
+ }
186
+ }
187
+ #originAllowed(origin) {
188
+ const allowed = this.#options.allowedOrigins;
189
+ if (allowed === undefined)
190
+ return isLoopbackOrigin(origin);
191
+ if (typeof allowed === "function")
192
+ return allowed(origin);
193
+ return allowed.includes(origin) || isLoopbackOrigin(origin);
194
+ }
195
+ async #body(req) {
196
+ const max = this.#options.maxBodyBytes ?? 1024 * 1024;
197
+ let text = "";
198
+ for await (const chunk of req) {
199
+ text += chunk;
200
+ if (text.length > max)
201
+ throw new Error("request body too large");
202
+ }
203
+ return text;
204
+ }
205
+ #json(res, status, body) {
206
+ res.writeHead(status, { "Content-Type": "application/json", "Cache-Control": "no-store" });
207
+ res.end(JSON.stringify(body));
208
+ }
209
+ }
@@ -0,0 +1,4 @@
1
+ export * from "./channel.js";
2
+ export * from "./auth.js";
3
+ export * from "./stdio.js";
4
+ export * from "./http.js";
@@ -0,0 +1,4 @@
1
+ export * from "./channel.js";
2
+ export * from "./auth.js";
3
+ export * from "./stdio.js";
4
+ export * from "./http.js";
@@ -0,0 +1,16 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ import type { McpServer } from "../server/index.js";
3
+ export interface StdioServerHostOptions {
4
+ readonly server: McpServer;
5
+ readonly input?: Readable;
6
+ readonly output?: Writable;
7
+ }
8
+ /**
9
+ * Newline-delimited JSON-RPC stdio host. stdout carries only protocol messages;
10
+ * requests, notifications/cancelled, subscriptions/listen, and events/stream.
11
+ */
12
+ export declare class StdioServerHost {
13
+ #private;
14
+ constructor(opts: StdioServerHostOptions);
15
+ listen(): Promise<void>;
16
+ }
@@ -0,0 +1,83 @@
1
+ import { createInterface } from "node:readline";
2
+ import { errorResponse, HostChannel, resultResponse } from "./channel.js";
3
+ /**
4
+ * Newline-delimited JSON-RPC stdio host. stdout carries only protocol messages;
5
+ * requests, notifications/cancelled, subscriptions/listen, and events/stream.
6
+ */
7
+ export class StdioServerHost {
8
+ #server;
9
+ #input;
10
+ #output;
11
+ #channels = new Map();
12
+ constructor(opts) {
13
+ this.#server = opts.server;
14
+ this.#input = opts.input ?? process.stdin;
15
+ this.#output = opts.output ?? process.stdout;
16
+ }
17
+ #write(message) {
18
+ this.#output.write(`${JSON.stringify(message)}\n`);
19
+ }
20
+ async listen() {
21
+ const rl = createInterface({ input: this.#input });
22
+ for await (const line of rl) {
23
+ if (line.trim() === "")
24
+ continue;
25
+ let msg;
26
+ try {
27
+ msg = JSON.parse(line);
28
+ }
29
+ catch {
30
+ continue; // malformed input is not a protocol message
31
+ }
32
+ if (Array.isArray(msg) || typeof msg !== "object" || msg === null)
33
+ continue;
34
+ if (!("id" in msg)) {
35
+ this.#server.handleNotification(msg);
36
+ continue;
37
+ }
38
+ const request = msg;
39
+ if (request.method === "subscriptions/listen" || request.method === "events/stream") {
40
+ this.#openStream(request);
41
+ continue;
42
+ }
43
+ try {
44
+ const result = await this.#server.handleRequest(request);
45
+ if (!this.#server.wasCancelled(request.id))
46
+ this.#write(resultResponse(request.id, result));
47
+ }
48
+ catch (error) {
49
+ if (!this.#server.wasCancelled(request.id))
50
+ this.#write(errorResponse(request.id, error));
51
+ }
52
+ }
53
+ for (const channel of this.#channels.values())
54
+ channel.close();
55
+ this.#channels.clear();
56
+ }
57
+ #openStream(request) {
58
+ const channel = new HostChannel(request.id, (notification) => this.#write(notification), (result) => {
59
+ this.#write(resultResponse(request.id, result));
60
+ this.#channels.delete(request.id);
61
+ });
62
+ this.#channels.set(request.id, channel);
63
+ try {
64
+ if (request.method === "subscriptions/listen") {
65
+ const subscriptions = this.#server.subscriptions;
66
+ if (!subscriptions)
67
+ throw new Error("subscriptions unavailable");
68
+ subscriptions.listen(channel, (request.params ?? {}));
69
+ this.#server.tasks?.attach(channel);
70
+ }
71
+ else {
72
+ const events = this.#server.events;
73
+ if (!events)
74
+ throw new Error("events unavailable");
75
+ events.stream(channel, (request.params ?? {}));
76
+ }
77
+ }
78
+ catch (error) {
79
+ this.#channels.delete(request.id);
80
+ this.#write(errorResponse(request.id, error));
81
+ }
82
+ }
83
+ }