@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,177 @@
1
+ /**
2
+ * Cancellation and timeout semantics (S1.1, IMPLEMENTATION_PLAN.md §5.4; WIRE-CANCEL-*, WIRE-TO-*).
3
+ *
4
+ * Core does not write notifications/cancelled itself: that is binding behavior (stdio sends it,
5
+ * Streamable HTTP closes the stream). Core guarantees that an abort settles the request locally
6
+ * even when the transport does not react, that a response observed after the local settle is
7
+ * ignored and counted (WIRE-CANCEL-3), that a cancel after settle is a no-op (WIRE-CANCEL-1),
8
+ * and that interrupted non-read-only calls classify as uncertain-write (WIRE-CANCEL-5, N14).
9
+ */
10
+ /**
11
+ * Methods treated as read-only by default. A read-only call that is cancelled or times out is a
12
+ * clean `cancelled` / `transport-failure`; anything else is `uncertain-write`.
13
+ * prompts/get is listed as a host-overridable default only (STDIO-RECOVER-1); the spec does not
14
+ * declare it idempotent.
15
+ */
16
+ export const DEFAULT_READ_ONLY_METHODS = Object.freeze([
17
+ "server/discover",
18
+ "tools/list",
19
+ "prompts/list",
20
+ "prompts/get",
21
+ "resources/list",
22
+ "resources/templates/list",
23
+ "resources/read",
24
+ "completion/complete",
25
+ "subscriptions/listen",
26
+ ]);
27
+ export function createReadOnlyPredicate(methods = DEFAULT_READ_ONLY_METHODS) {
28
+ const set = new Set(methods);
29
+ return (method) => set.has(method);
30
+ }
31
+ export const isReadOnlyMethod = createReadOnlyPredicate();
32
+ /**
33
+ * Races `work` against `signal`; rejects on abort with `onAbort()` (or `signal.reason` if omitted).
34
+ */
35
+ export function withAbort(work, signal, onAbort) {
36
+ const abortReason = () => {
37
+ if (!onAbort)
38
+ return signal.reason;
39
+ try {
40
+ return onAbort();
41
+ }
42
+ catch (err) {
43
+ return err;
44
+ }
45
+ };
46
+ if (signal.aborted) {
47
+ Promise.resolve(work).then(() => { }, () => { });
48
+ return Promise.reject(abortReason());
49
+ }
50
+ return new Promise((resolve, reject) => {
51
+ let settled = false;
52
+ const abort = () => {
53
+ if (settled)
54
+ return;
55
+ settled = true;
56
+ signal.removeEventListener("abort", abort);
57
+ reject(abortReason());
58
+ };
59
+ signal.addEventListener("abort", abort, { once: true });
60
+ Promise.resolve(work).then((value) => {
61
+ if (settled)
62
+ return;
63
+ settled = true;
64
+ signal.removeEventListener("abort", abort);
65
+ resolve(value);
66
+ }, (err) => {
67
+ if (settled)
68
+ return;
69
+ settled = true;
70
+ signal.removeEventListener("abort", abort);
71
+ reject(err);
72
+ });
73
+ });
74
+ }
75
+ /** Stable, non-cryptographic digest of call arguments for UncertainWrite records (no secrets stored). */
76
+ export function argsDigest(obj) {
77
+ const s = JSON.stringify(obj) ?? "";
78
+ let h = 2166136261;
79
+ for (let i = 0; i < s.length; i++) {
80
+ h ^= s.charCodeAt(i);
81
+ h = Math.imul(h, 16777619);
82
+ }
83
+ return `fnv1a-${(h >>> 0).toString(16).padStart(8, "0")}`;
84
+ }
85
+ /**
86
+ * Classification hook for an interrupted call (no response observed).
87
+ * - never sent: `cancelled` (abort/timeout) or `transport-failure` (safe to retry)
88
+ * - sent, read-only: `cancelled` or `transport-failure`
89
+ * - sent, not read-only: `uncertain-write`
90
+ */
91
+ export function classifyInterruptedCall(call) {
92
+ if (call.delivery === "not-sent") {
93
+ return call.cause === "cancelled" ? "cancelled" : "transport-failure";
94
+ }
95
+ if (!call.readOnly)
96
+ return "uncertain-write";
97
+ return call.cause === "cancelled" ? "cancelled" : "transport-failure";
98
+ }
99
+ export function uncertainEvidence(call) {
100
+ if (call.cause === "cancelled")
101
+ return "cancelled";
102
+ if (call.cause === "timeout")
103
+ return "timeout";
104
+ if (call.failure?.kind === "process-exit")
105
+ return "process-exit";
106
+ if (call.failure?.kind === "http-status")
107
+ return "status-5xx";
108
+ return "stream-broken";
109
+ }
110
+ export function buildUncertainWrite(input) {
111
+ const name = input.params["name"];
112
+ return {
113
+ requestId: input.requestId,
114
+ method: input.method,
115
+ ...(typeof name === "string" ? { name } : {}),
116
+ argsDigest: argsDigest(input.params),
117
+ sentAt: input.sentAt,
118
+ binding: input.binding,
119
+ evidence: input.evidence,
120
+ };
121
+ }
122
+ /** Number of microtask turns an abort waits so a transport that settles on abort wins the race. */
123
+ const ABORT_SETTLE_TURNS = 4;
124
+ /**
125
+ * Wraps an exchange's completion so that exactly one end is observed.
126
+ * When `settleOnAbort` is set, an abort settles locally with a `maybe-delivered` failure if the
127
+ * transport has not settled by itself within a few microtask turns.
128
+ */
129
+ export function guardExchangeDone(inner, signal, opts, hooks = {}) {
130
+ let settled = false;
131
+ let resolveDone;
132
+ const done = new Promise((resolve) => {
133
+ resolveDone = resolve;
134
+ });
135
+ const onAbort = () => {
136
+ let p = Promise.resolve();
137
+ for (let i = 0; i < ABORT_SETTLE_TURNS; i++)
138
+ p = p.then(() => undefined);
139
+ void p.then(() => {
140
+ if (settled)
141
+ return;
142
+ const reason = signal.reason;
143
+ settle({
144
+ kind: "failure",
145
+ failure: {
146
+ kind: reason === "timeout" ? "timeout" : "closed",
147
+ message: "request aborted locally",
148
+ },
149
+ delivery: inner.abortDelivery?.() ?? "maybe-delivered",
150
+ }, "abort");
151
+ });
152
+ };
153
+ const settle = (end, source) => {
154
+ if (settled) {
155
+ if (source === "transport")
156
+ hooks.onLate?.(end);
157
+ return;
158
+ }
159
+ settled = true;
160
+ signal.removeEventListener("abort", onAbort);
161
+ hooks.onSettle?.(end, source);
162
+ resolveDone(end);
163
+ };
164
+ inner.done.then((end) => settle(end, "transport"), (err) => settle({
165
+ kind: "failure",
166
+ failure: {
167
+ kind: "stream-broken",
168
+ message: err instanceof Error ? err.message : String(err),
169
+ cause: err,
170
+ },
171
+ delivery: "maybe-delivered",
172
+ }, "transport"));
173
+ if (opts.settleOnAbort && !signal.aborted) {
174
+ signal.addEventListener("abort", onAbort, { once: true });
175
+ }
176
+ return { done, settled: () => settled };
177
+ }
@@ -0,0 +1,33 @@
1
+ import type { JsonRpcNotification, JsonRpcRequest } from "./jsonrpc.js";
2
+ import type { Outcome } from "./outcome.js";
3
+ export interface Disposable {
4
+ dispose(): void;
5
+ }
6
+ export interface ExtensionCapabilities {
7
+ readonly [namespace: string]: Record<string, unknown>;
8
+ }
9
+ export type ExtensionNotificationHandler = (notification: JsonRpcNotification) => void;
10
+ export type ExtensionRequestHandler = (request: JsonRpcRequest) => unknown;
11
+ export interface ExtensionHost {
12
+ registerResultType(resultType: string, handler: (result: Record<string, unknown>) => Outcome<unknown>): Disposable;
13
+ onNotification?(method: string, handler: ExtensionNotificationHandler): Disposable;
14
+ onRequest?(method: string, handler: ExtensionRequestHandler): Disposable;
15
+ }
16
+ export interface Extension {
17
+ readonly id: string;
18
+ readonly version?: string;
19
+ capabilities?(isWorking: boolean): ExtensionCapabilities;
20
+ attach?(host: ExtensionHost): Disposable;
21
+ }
22
+ export declare class ExtensionRegistry {
23
+ private readonly extensions;
24
+ private readonly resultTypes;
25
+ private readonly notificationHandlers;
26
+ private readonly requestHandlers;
27
+ register(ext: Extension): Disposable;
28
+ capabilities(): Record<string, unknown>;
29
+ resolveResultType(resultType: string): ((result: Record<string, unknown>) => Outcome<unknown>) | undefined;
30
+ dispatchNotification(notification: JsonRpcNotification, onError?: (err: unknown) => void): void;
31
+ resolveRequestHandler(method: string): ExtensionRequestHandler | undefined;
32
+ closeAllReverse(): void;
33
+ }
@@ -0,0 +1,145 @@
1
+ export class ExtensionRegistry {
2
+ extensions = new Map();
3
+ resultTypes = new Map();
4
+ notificationHandlers = new Map();
5
+ requestHandlers = new Map();
6
+ register(ext) {
7
+ if (this.extensions.has(ext.id)) {
8
+ throw new Error(`Extension already registered: ${ext.id}`);
9
+ }
10
+ const ownedResultTypes = [];
11
+ const ownedNotifications = [];
12
+ const ownedRequests = [];
13
+ const cleanup = () => {
14
+ for (const rt of ownedResultTypes) {
15
+ this.resultTypes.delete(rt);
16
+ }
17
+ for (const { method, handler } of ownedNotifications) {
18
+ const set = this.notificationHandlers.get(method);
19
+ if (set) {
20
+ set.delete(handler);
21
+ if (set.size === 0)
22
+ this.notificationHandlers.delete(method);
23
+ }
24
+ }
25
+ for (const method of ownedRequests) {
26
+ this.requestHandlers.delete(method);
27
+ }
28
+ };
29
+ const host = {
30
+ registerResultType: (resultType, handler) => {
31
+ if (resultType === "complete" || resultType === "input_required") {
32
+ throw new Error(`Cannot override core resultType: ${resultType}`);
33
+ }
34
+ if (this.resultTypes.has(resultType)) {
35
+ throw new Error(`Duplicate extension resultType: ${resultType}`);
36
+ }
37
+ this.resultTypes.set(resultType, handler);
38
+ ownedResultTypes.push(resultType);
39
+ return {
40
+ dispose: () => {
41
+ if (this.resultTypes.get(resultType) === handler) {
42
+ this.resultTypes.delete(resultType);
43
+ }
44
+ },
45
+ };
46
+ },
47
+ onNotification: (method, handler) => {
48
+ let set = this.notificationHandlers.get(method);
49
+ if (!set) {
50
+ set = new Set();
51
+ this.notificationHandlers.set(method, set);
52
+ }
53
+ set.add(handler);
54
+ ownedNotifications.push({ method, handler });
55
+ return {
56
+ dispose: () => {
57
+ const cur = this.notificationHandlers.get(method);
58
+ if (!cur)
59
+ return;
60
+ cur.delete(handler);
61
+ if (cur.size === 0)
62
+ this.notificationHandlers.delete(method);
63
+ },
64
+ };
65
+ },
66
+ onRequest: (method, handler) => {
67
+ if (this.requestHandlers.has(method)) {
68
+ throw new Error(`Duplicate extension request handler: ${method}`);
69
+ }
70
+ this.requestHandlers.set(method, handler);
71
+ ownedRequests.push(method);
72
+ return {
73
+ dispose: () => {
74
+ if (this.requestHandlers.get(method) === handler) {
75
+ this.requestHandlers.delete(method);
76
+ }
77
+ },
78
+ };
79
+ },
80
+ };
81
+ let detacher;
82
+ try {
83
+ detacher = ext.attach ? ext.attach(host) : { dispose() { } };
84
+ }
85
+ catch (err) {
86
+ cleanup();
87
+ throw err;
88
+ }
89
+ this.extensions.set(ext.id, { ext, detacher, cleanup });
90
+ return {
91
+ dispose: () => {
92
+ const entry = this.extensions.get(ext.id);
93
+ if (!entry)
94
+ return;
95
+ this.extensions.delete(ext.id);
96
+ entry.cleanup();
97
+ entry.detacher.dispose();
98
+ },
99
+ };
100
+ }
101
+ capabilities() {
102
+ const merged = {};
103
+ for (const { ext } of this.extensions.values()) {
104
+ if (!ext.capabilities)
105
+ continue;
106
+ const caps = ext.capabilities(true);
107
+ const prev = merged.extensions;
108
+ Object.assign(merged, caps);
109
+ // The standard `extensions` namespace is a map keyed by extension ID: merge by subkey into a fresh object.
110
+ if (Object.prototype.hasOwnProperty.call(caps, "extensions")) {
111
+ merged.extensions = { ...prev, ...caps.extensions };
112
+ }
113
+ }
114
+ return merged;
115
+ }
116
+ resolveResultType(resultType) {
117
+ return this.resultTypes.get(resultType);
118
+ }
119
+ dispatchNotification(notification, onError) {
120
+ const set = this.notificationHandlers.get(notification.method);
121
+ if (!set || set.size === 0)
122
+ return;
123
+ for (const handler of [...set]) {
124
+ try {
125
+ handler(notification);
126
+ }
127
+ catch (err) {
128
+ onError?.(err);
129
+ }
130
+ }
131
+ }
132
+ resolveRequestHandler(method) {
133
+ return this.requestHandlers.get(method);
134
+ }
135
+ closeAllReverse() {
136
+ const entries = Array.from(this.extensions.values()).reverse();
137
+ this.extensions.clear();
138
+ this.resultTypes.clear();
139
+ this.notificationHandlers.clear();
140
+ this.requestHandlers.clear();
141
+ for (const { detacher } of entries) {
142
+ detacher.dispose();
143
+ }
144
+ }
145
+ }
@@ -0,0 +1,73 @@
1
+ import { type Disposable, type Extension } from "./extension.js";
2
+ import { type IdGenerator } from "./jsonrpc.js";
3
+ import { type EraState, type LifecyclePolicyOptions, type ProbeOptions } from "./lifecycle.js";
4
+ import type { PortRegistry, Transport } from "./ports.js";
5
+ import { type ClientRequest, type Limits, type NotifyOptions, type RequestOptions, type StreamHandle } from "./request.js";
6
+ import type { DiscoverResult } from "./schema/index.js";
7
+ export * as McpSchema from "./schema/index.js";
8
+ export type { DiscoverResult } from "./schema/index.js";
9
+ export * from "./jsonrpc.js";
10
+ export * from "./outcome.js";
11
+ export * from "./ports.js";
12
+ export * from "./telemetry.js";
13
+ export * from "./auth-types.js";
14
+ export * from "./bearer-challenge.js";
15
+ export * from "./extension.js";
16
+ export * from "./request.js";
17
+ export * from "./lifecycle.js";
18
+ export * from "./cancel.js";
19
+ export * from "./progress.js";
20
+ export interface ServerRef {
21
+ readonly key: string;
22
+ readonly label?: string;
23
+ }
24
+ export interface McpClientOptions {
25
+ readonly transport: Transport;
26
+ readonly server: ServerRef;
27
+ readonly clientInfo?: {
28
+ readonly name: string;
29
+ readonly version: string;
30
+ readonly title?: string;
31
+ } | false;
32
+ readonly ports?: Partial<PortRegistry>;
33
+ readonly extensions?: readonly Extension[];
34
+ readonly idGenerator?: IdGenerator;
35
+ readonly supportedVersions?: readonly string[];
36
+ readonly defaults?: {
37
+ readonly timeoutMs?: number;
38
+ readonly mrtr?: "auto" | "manual";
39
+ readonly limits?: Partial<Limits>;
40
+ };
41
+ readonly lifecycle?: LifecyclePolicyOptions;
42
+ }
43
+ export declare class McpClient {
44
+ readonly server: ServerRef;
45
+ private readonly transport;
46
+ private readonly extensions;
47
+ private readonly manager;
48
+ private readonly eraCache;
49
+ private readonly hooks;
50
+ private readonly ctx;
51
+ constructor(opts: McpClientOptions);
52
+ request<T = Record<string, unknown>>(method: string, params?: Record<string, unknown>, opts?: RequestOptions): ClientRequest<T>;
53
+ notify(method: string, params?: Record<string, unknown>, opts?: NotifyOptions): Promise<void>;
54
+ /**
55
+ * Open a long-lived request stream (subscriptions/listen, events/stream).
56
+ * Uses the same per-request metadata, id allocation, and lifecycle handling
57
+ * as request(); no default request timeout applies to streams.
58
+ */
59
+ openStream(method: string, params?: Record<string, unknown>, opts?: RequestOptions): StreamHandle;
60
+ discover(opts?: RequestOptions): ClientRequest<DiscoverResult>;
61
+ /**
62
+ * Probes the server era with server/discover once per server key and caches the verdict in
63
+ * memory (VER-5, VER-CACHE-1, VER-DIAG-1). Never sends initialize. Local cancels and transport
64
+ * faults yield `unknown` and are not cached.
65
+ */
66
+ probe(opts?: ProbeOptions): Promise<EraState>;
67
+ /** Cached era verdict for this server, if any. */
68
+ era(): EraState | undefined;
69
+ use(ext: Extension): Disposable;
70
+ close(opts?: {
71
+ readonly graceMs?: number;
72
+ }): Promise<void>;
73
+ }
@@ -0,0 +1,129 @@
1
+ import { ExtensionRegistry } from "./extension.js";
2
+ import { SUPPORTED_PROTOCOL_VERSION } from "./jsonrpc.js";
3
+ import { defaultLifecycleHooks, DISCOVER_PROBE_TIMEOUT_MS, EraCache, } from "./lifecycle.js";
4
+ import { RequestManager, } from "./request.js";
5
+ import { NotificationQueue } from "./progress.js";
6
+ export * as McpSchema from "./schema/index.js";
7
+ export * from "./jsonrpc.js";
8
+ export * from "./outcome.js";
9
+ export * from "./ports.js";
10
+ export * from "./telemetry.js";
11
+ export * from "./auth-types.js";
12
+ export * from "./bearer-challenge.js";
13
+ export * from "./extension.js";
14
+ export * from "./request.js";
15
+ export * from "./lifecycle.js";
16
+ export * from "./cancel.js";
17
+ export * from "./progress.js";
18
+ export class McpClient {
19
+ server;
20
+ transport;
21
+ extensions = new ExtensionRegistry();
22
+ manager;
23
+ eraCache;
24
+ hooks;
25
+ ctx;
26
+ constructor(opts) {
27
+ this.server = opts.server;
28
+ this.transport = opts.transport;
29
+ const lc = opts.lifecycle ?? {};
30
+ this.hooks = { ...defaultLifecycleHooks, ...lc.hooks };
31
+ this.eraCache = lc.eraCache ?? new EraCache();
32
+ this.ctx = {
33
+ binding: opts.transport.binding,
34
+ endpointOrCommand: opts.server.label ?? opts.server.key,
35
+ supportedVersions: opts.supportedVersions ?? [SUPPORTED_PROTOCOL_VERSION],
36
+ };
37
+ if (opts.extensions) {
38
+ for (const ext of opts.extensions) {
39
+ this.extensions.register(ext);
40
+ }
41
+ }
42
+ this.manager = new RequestManager({
43
+ transport: opts.transport,
44
+ serverLabel: opts.server.label ?? opts.server.key,
45
+ ...(opts.ports ? { ports: opts.ports } : {}),
46
+ ...(opts.clientInfo !== undefined ? { clientInfo: opts.clientInfo } : {}),
47
+ extensions: this.extensions,
48
+ ...(opts.idGenerator ? { idGenerator: opts.idGenerator } : {}),
49
+ ...(opts.supportedVersions ? { supportedVersions: opts.supportedVersions } : {}),
50
+ ...(opts.lifecycle ? { lifecycle: opts.lifecycle } : {}),
51
+ ...(opts.defaults?.limits || opts.defaults?.timeoutMs !== undefined
52
+ ? {
53
+ limits: {
54
+ ...opts.defaults?.limits,
55
+ ...(opts.defaults?.timeoutMs !== undefined ? { defaultTimeoutMs: opts.defaults.timeoutMs } : {}),
56
+ },
57
+ }
58
+ : {}),
59
+ });
60
+ }
61
+ request(method, params = {}, opts) {
62
+ return this.manager.request(method, params, opts);
63
+ }
64
+ notify(method, params = {}, opts) {
65
+ return this.manager.notify(method, params, opts);
66
+ }
67
+ /**
68
+ * Open a long-lived request stream (subscriptions/listen, events/stream).
69
+ * Uses the same per-request metadata, id allocation, and lifecycle handling
70
+ * as request(); no default request timeout applies to streams.
71
+ */
72
+ openStream(method, params = {}, opts = {}) {
73
+ const req = this.manager.request(method, params, {
74
+ ...opts,
75
+ stream: true,
76
+ idempotent: opts.idempotent ?? true,
77
+ });
78
+ // Stdio routes subscription notifications to subscriptions/listen by default;
79
+ // events/stream and other long-lived streams need an explicit listener.
80
+ const transport = this.transport;
81
+ const routed = typeof transport.registerSubscription === "function"
82
+ ? new NotificationQueue()
83
+ : undefined;
84
+ const detach = routed
85
+ ? transport.registerSubscription(req.id, (n) => routed.push(n))
86
+ : undefined;
87
+ const notifications = routed ?? req.notifications;
88
+ const cleanup = () => {
89
+ detach?.();
90
+ routed?.close();
91
+ };
92
+ return {
93
+ id: req.id,
94
+ close: () => {
95
+ cleanup();
96
+ req.cancel();
97
+ },
98
+ done: Promise.resolve(req).finally(cleanup),
99
+ [Symbol.asyncIterator]: () => notifications[Symbol.asyncIterator](),
100
+ };
101
+ }
102
+ discover(opts) {
103
+ return this.manager.request("server/discover", {}, { ...opts, idempotent: true });
104
+ }
105
+ /**
106
+ * Probes the server era with server/discover once per server key and caches the verdict in
107
+ * memory (VER-5, VER-CACHE-1, VER-DIAG-1). Never sends initialize. Local cancels and transport
108
+ * faults yield `unknown` and are not cached.
109
+ */
110
+ probe(opts = {}) {
111
+ return this.eraCache.resolve(this.server.key, async () => {
112
+ const outcome = await this.discover({
113
+ timeoutMs: opts.timeoutMs ?? DISCOVER_PROBE_TIMEOUT_MS,
114
+ ...(opts.signal ? { signal: opts.signal } : {}),
115
+ });
116
+ return this.hooks.classifyDiscover(outcome, this.ctx);
117
+ });
118
+ }
119
+ /** Cached era verdict for this server, if any. */
120
+ era() {
121
+ return this.eraCache.get(this.server.key);
122
+ }
123
+ use(ext) {
124
+ return this.extensions.register(ext);
125
+ }
126
+ async close(opts) {
127
+ await this.manager.close(opts);
128
+ }
129
+ }
@@ -0,0 +1,49 @@
1
+ import type { RequestId } from "./schema/index.js";
2
+ export type { RequestId };
3
+ export declare const JSONRPC_VERSION: "2.0";
4
+ export declare const SUPPORTED_PROTOCOL_VERSION: "2026-07-28";
5
+ export interface JsonRpcRequest {
6
+ readonly jsonrpc: "2.0";
7
+ readonly id: RequestId;
8
+ readonly method: string;
9
+ readonly params?: Record<string, unknown>;
10
+ }
11
+ export interface JsonRpcNotification {
12
+ readonly jsonrpc: "2.0";
13
+ readonly method: string;
14
+ readonly params?: Record<string, unknown>;
15
+ }
16
+ export interface JsonRpcResponse {
17
+ readonly jsonrpc: "2.0";
18
+ readonly id: RequestId;
19
+ readonly result: Record<string, unknown>;
20
+ }
21
+ export interface JsonRpcErrorBody {
22
+ readonly code: number;
23
+ readonly message: string;
24
+ readonly data?: unknown;
25
+ }
26
+ export interface JsonRpcErrorResponse {
27
+ readonly jsonrpc: "2.0";
28
+ readonly id: RequestId | null;
29
+ readonly error: JsonRpcErrorBody;
30
+ }
31
+ export type JsonRpcInbound = JsonRpcResponse | JsonRpcErrorResponse | JsonRpcNotification | JsonRpcRequest;
32
+ export type IdGenerator = () => RequestId;
33
+ /**
34
+ * Per-client monotonic integer id generator keeping all values strictly < 2^53 (EDGE-12).
35
+ */
36
+ export declare function createMonotonicIdGenerator(start?: number): IdGenerator;
37
+ export declare function isValidRequestId(id: unknown): id is RequestId;
38
+ /**
39
+ * Validates that an outbound object is a JSON-RPC request (never a response envelope, WIRE-DIR-1).
40
+ */
41
+ export declare function assertOutboundRequest(msg: unknown): asserts msg is JsonRpcRequest;
42
+ export interface ParsedInbound {
43
+ readonly kind: "response" | "error" | "notification" | "server-request";
44
+ readonly message: JsonRpcInbound;
45
+ readonly diagnostics: readonly string[];
46
+ }
47
+ export declare function parseInboundMessage(raw: unknown): ParsedInbound | {
48
+ readonly error: string;
49
+ };
@@ -0,0 +1,80 @@
1
+ export const JSONRPC_VERSION = "2.0";
2
+ export const SUPPORTED_PROTOCOL_VERSION = "2026-07-28";
3
+ /**
4
+ * Per-client monotonic integer id generator keeping all values strictly < 2^53 (EDGE-12).
5
+ */
6
+ export function createMonotonicIdGenerator(start = 1) {
7
+ let next = start;
8
+ return () => {
9
+ if (!Number.isSafeInteger(next) || next >= Number.MAX_SAFE_INTEGER) {
10
+ throw new RangeError("RequestId exhausted safe integer range");
11
+ }
12
+ const id = next;
13
+ next += 1;
14
+ return id;
15
+ };
16
+ }
17
+ export function isValidRequestId(id) {
18
+ if (typeof id === "string")
19
+ return id.length > 0;
20
+ if (typeof id === "number")
21
+ return Number.isFinite(id) && Number.isInteger(id);
22
+ return false;
23
+ }
24
+ /**
25
+ * Validates that an outbound object is a JSON-RPC request (never a response envelope, WIRE-DIR-1).
26
+ */
27
+ export function assertOutboundRequest(msg) {
28
+ if (typeof msg !== "object" || msg === null) {
29
+ throw new TypeError("Outbound JSON-RPC request must be an object");
30
+ }
31
+ const rec = msg;
32
+ if ("result" in rec || "error" in rec) {
33
+ throw new TypeError("Clients MUST NOT send JSON-RPC response envelopes (WIRE-DIR-1)");
34
+ }
35
+ if (rec["jsonrpc"] !== JSONRPC_VERSION) {
36
+ throw new TypeError("Outbound request jsonrpc must be '2.0'");
37
+ }
38
+ if (!isValidRequestId(rec["id"])) {
39
+ throw new TypeError("Outbound request id must be non-empty string or integer, never null (WIRE-ID-1)");
40
+ }
41
+ if (typeof rec["method"] !== "string" || rec["method"].length === 0) {
42
+ throw new TypeError("Outbound request method must be a non-empty string");
43
+ }
44
+ }
45
+ export function parseInboundMessage(raw) {
46
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
47
+ return { error: "JSON-RPC message must be a JSON object" };
48
+ }
49
+ const obj = raw;
50
+ if (obj["jsonrpc"] !== JSONRPC_VERSION) {
51
+ return { error: "jsonrpc must equal '2.0'" };
52
+ }
53
+ const diagnostics = [];
54
+ if ("id" in obj) {
55
+ const id = obj["id"];
56
+ if (typeof id === "number" && !Number.isSafeInteger(id)) {
57
+ diagnostics.push(`unsafe-integer-id:${String(id)}`);
58
+ }
59
+ if (typeof obj["method"] === "string") {
60
+ return { kind: "server-request", message: obj, diagnostics };
61
+ }
62
+ if ("error" in obj && typeof obj["error"] === "object" && obj["error"] !== null) {
63
+ if (id === null) {
64
+ diagnostics.push("error-response-null-id");
65
+ }
66
+ return { kind: "error", message: obj, diagnostics };
67
+ }
68
+ if ("result" in obj && typeof obj["result"] === "object" && obj["result"] !== null) {
69
+ if (!isValidRequestId(id)) {
70
+ return { error: "Response id must be string or integer" };
71
+ }
72
+ return { kind: "response", message: obj, diagnostics };
73
+ }
74
+ return { error: "Invalid JSON-RPC message with id" };
75
+ }
76
+ if (typeof obj["method"] === "string") {
77
+ return { kind: "notification", message: obj, diagnostics };
78
+ }
79
+ return { error: "Notification missing string method" };
80
+ }