@jangmanj/mcp 0.0.0-stage → 0.12.3

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +337 -2
  3. package/adapters/pi/HOST-NOTES.md +65 -0
  4. package/adapters/pi/bridge.ts +721 -0
  5. package/adapters/pi/config.ts +364 -0
  6. package/adapters/pi/content-offloaded.ts +53 -0
  7. package/adapters/pi/content.ts +78 -0
  8. package/adapters/pi/diagnostics.ts +26 -0
  9. package/adapters/pi/elicitation.ts +133 -0
  10. package/adapters/pi/index.ts +210 -0
  11. package/adapters/pi/oauth.ts +219 -0
  12. package/adapters/pi/pi-api.ts +133 -0
  13. package/adapters/pi/resources.ts +177 -0
  14. package/adapters/pi/result-files.ts +32 -0
  15. package/adapters/pi/tasks.ts +49 -0
  16. package/dist/auth/client-credentials.d.ts +65 -0
  17. package/dist/auth/client-credentials.js +388 -0
  18. package/dist/auth/discovery.d.ts +28 -0
  19. package/dist/auth/discovery.js +125 -0
  20. package/dist/auth/index.d.ts +9 -0
  21. package/dist/auth/index.js +5 -0
  22. package/dist/auth/node-ports.d.ts +8 -0
  23. package/dist/auth/node-ports.js +67 -0
  24. package/dist/auth/protocol.d.ts +12 -0
  25. package/dist/auth/protocol.js +39 -0
  26. package/dist/auth/provider.d.ts +114 -0
  27. package/dist/auth/provider.js +407 -0
  28. package/dist/auth/safe-fetch.d.ts +14 -0
  29. package/dist/auth/safe-fetch.js +130 -0
  30. package/dist/client/events.d.ts +33 -0
  31. package/dist/client/events.js +84 -0
  32. package/dist/client/index.d.ts +65 -0
  33. package/dist/client/index.js +128 -0
  34. package/dist/core/auth-types.d.ts +36 -0
  35. package/dist/core/auth-types.js +11 -0
  36. package/dist/core/bearer-challenge.d.ts +3 -0
  37. package/dist/core/bearer-challenge.js +63 -0
  38. package/dist/core/cancel.d.ts +70 -0
  39. package/dist/core/cancel.js +177 -0
  40. package/dist/core/extension.d.ts +33 -0
  41. package/dist/core/extension.js +145 -0
  42. package/dist/core/index.d.ts +73 -0
  43. package/dist/core/index.js +129 -0
  44. package/dist/core/jsonrpc.d.ts +49 -0
  45. package/dist/core/jsonrpc.js +80 -0
  46. package/dist/core/lifecycle.d.ts +128 -0
  47. package/dist/core/lifecycle.js +251 -0
  48. package/dist/core/outcome.d.ts +98 -0
  49. package/dist/core/outcome.js +32 -0
  50. package/dist/core/ports.d.ts +144 -0
  51. package/dist/core/ports.js +67 -0
  52. package/dist/core/progress.d.ts +81 -0
  53. package/dist/core/progress.js +205 -0
  54. package/dist/core/request.d.ts +108 -0
  55. package/dist/core/request.js +578 -0
  56. package/dist/core/schema/index.d.ts +1 -0
  57. package/dist/core/schema/index.js +1 -0
  58. package/dist/core/schema/types.d.ts +4154 -0
  59. package/dist/core/schema/types.js +6 -0
  60. package/dist/core/telemetry.d.ts +25 -0
  61. package/dist/core/telemetry.js +37 -0
  62. package/dist/ext-events/index.d.ts +79 -0
  63. package/dist/ext-events/index.js +218 -0
  64. package/dist/ext-events/model.d.ts +10 -0
  65. package/dist/ext-events/model.js +6 -0
  66. package/dist/ext-events/push.d.ts +18 -0
  67. package/dist/ext-events/push.js +101 -0
  68. package/dist/ext-events/stream.d.ts +6 -0
  69. package/dist/ext-events/stream.js +60 -0
  70. package/dist/ext-server-cards/index.d.ts +107 -0
  71. package/dist/ext-server-cards/index.js +249 -0
  72. package/dist/ext-skills/cache.d.ts +20 -0
  73. package/dist/ext-skills/cache.js +101 -0
  74. package/dist/ext-skills/client.d.ts +82 -0
  75. package/dist/ext-skills/client.js +292 -0
  76. package/dist/ext-skills/extension.d.ts +16 -0
  77. package/dist/ext-skills/extension.js +29 -0
  78. package/dist/ext-skills/index.d.ts +4 -0
  79. package/dist/ext-skills/index.js +4 -0
  80. package/dist/ext-skills/verify.d.ts +57 -0
  81. package/dist/ext-skills/verify.js +168 -0
  82. package/dist/index.d.ts +1 -0
  83. package/dist/index.js +1 -0
  84. package/dist/mrtr-cache/cache.d.ts +51 -0
  85. package/dist/mrtr-cache/cache.js +295 -0
  86. package/dist/mrtr-cache/client.d.ts +24 -0
  87. package/dist/mrtr-cache/client.js +44 -0
  88. package/dist/mrtr-cache/common.d.ts +10 -0
  89. package/dist/mrtr-cache/common.js +9 -0
  90. package/dist/mrtr-cache/elicitation.d.ts +42 -0
  91. package/dist/mrtr-cache/elicitation.js +221 -0
  92. package/dist/mrtr-cache/index.d.ts +9 -0
  93. package/dist/mrtr-cache/index.js +8 -0
  94. package/dist/mrtr-cache/mrtr.d.ts +37 -0
  95. package/dist/mrtr-cache/mrtr.js +250 -0
  96. package/dist/mrtr-cache/refresh.d.ts +8 -0
  97. package/dist/mrtr-cache/refresh.js +30 -0
  98. package/dist/mrtr-cache/stream.d.ts +5 -0
  99. package/dist/mrtr-cache/stream.js +18 -0
  100. package/dist/mrtr-cache/subscriptions.d.ts +96 -0
  101. package/dist/mrtr-cache/subscriptions.js +288 -0
  102. package/dist/mrtr-cache/tasks.d.ts +103 -0
  103. package/dist/mrtr-cache/tasks.js +444 -0
  104. package/dist/ops/common.d.ts +18 -0
  105. package/dist/ops/common.js +39 -0
  106. package/dist/ops/completion.d.ts +44 -0
  107. package/dist/ops/completion.js +65 -0
  108. package/dist/ops/content.d.ts +40 -0
  109. package/dist/ops/content.js +117 -0
  110. package/dist/ops/icons.d.ts +29 -0
  111. package/dist/ops/icons.js +82 -0
  112. package/dist/ops/index.d.ts +30 -0
  113. package/dist/ops/index.js +28 -0
  114. package/dist/ops/pagination.d.ts +32 -0
  115. package/dist/ops/pagination.js +65 -0
  116. package/dist/ops/prompts.d.ts +32 -0
  117. package/dist/ops/prompts.js +68 -0
  118. package/dist/ops/resources.d.ts +42 -0
  119. package/dist/ops/resources.js +104 -0
  120. package/dist/ops/schema.d.ts +39 -0
  121. package/dist/ops/schema.js +163 -0
  122. package/dist/ops/tools.d.ts +88 -0
  123. package/dist/ops/tools.js +169 -0
  124. package/dist/ops/uri-template.d.ts +3 -0
  125. package/dist/ops/uri-template.js +101 -0
  126. package/dist/server/index.d.ts +5 -0
  127. package/dist/server/index.js +5 -0
  128. package/dist/server/mrtr.d.ts +38 -0
  129. package/dist/server/mrtr.js +99 -0
  130. package/dist/server/protocol.d.ts +21 -0
  131. package/dist/server/protocol.js +49 -0
  132. package/dist/server/server.d.ts +105 -0
  133. package/dist/server/server.js +383 -0
  134. package/dist/server/skills.d.ts +45 -0
  135. package/dist/server/skills.js +73 -0
  136. package/dist/server/uri.d.ts +2 -0
  137. package/dist/server/uri.js +27 -0
  138. package/dist/server-events/bus.d.ts +40 -0
  139. package/dist/server-events/bus.js +84 -0
  140. package/dist/server-events/events.d.ts +36 -0
  141. package/dist/server-events/events.js +108 -0
  142. package/dist/server-events/index.d.ts +6 -0
  143. package/dist/server-events/index.js +6 -0
  144. package/dist/server-events/notices.d.ts +24 -0
  145. package/dist/server-events/notices.js +31 -0
  146. package/dist/server-events/subscriptions.d.ts +33 -0
  147. package/dist/server-events/subscriptions.js +77 -0
  148. package/dist/server-events/tasks.d.ts +43 -0
  149. package/dist/server-events/tasks.js +101 -0
  150. package/dist/server-events/types.d.ts +25 -0
  151. package/dist/server-events/types.js +34 -0
  152. package/dist/server-transport/auth.d.ts +20 -0
  153. package/dist/server-transport/auth.js +29 -0
  154. package/dist/server-transport/channel.d.ts +17 -0
  155. package/dist/server-transport/channel.js +47 -0
  156. package/dist/server-transport/http.d.ts +19 -0
  157. package/dist/server-transport/http.js +209 -0
  158. package/dist/server-transport/index.d.ts +4 -0
  159. package/dist/server-transport/index.js +4 -0
  160. package/dist/server-transport/stdio.d.ts +16 -0
  161. package/dist/server-transport/stdio.js +83 -0
  162. package/dist/telemetry-otel/index.d.ts +64 -0
  163. package/dist/telemetry-otel/index.js +196 -0
  164. package/dist/testing/index.d.ts +36 -0
  165. package/dist/testing/index.js +140 -0
  166. package/dist/transport-http/headers.d.ts +24 -0
  167. package/dist/transport-http/headers.js +140 -0
  168. package/dist/transport-http/index.d.ts +3 -0
  169. package/dist/transport-http/index.js +3 -0
  170. package/dist/transport-http/sse.d.ts +33 -0
  171. package/dist/transport-http/sse.js +152 -0
  172. package/dist/transport-http/transport.d.ts +66 -0
  173. package/dist/transport-http/transport.js +854 -0
  174. package/dist/transport-stdio/framing.d.ts +50 -0
  175. package/dist/transport-stdio/framing.js +154 -0
  176. package/dist/transport-stdio/index.d.ts +4 -0
  177. package/dist/transport-stdio/index.js +4 -0
  178. package/dist/transport-stdio/stderr-ring.d.ts +27 -0
  179. package/dist/transport-stdio/stderr-ring.js +105 -0
  180. package/dist/transport-stdio/transport.d.ts +142 -0
  181. package/dist/transport-stdio/transport.js +743 -0
  182. package/dist/transport-stdio/write-queue.d.ts +48 -0
  183. package/dist/transport-stdio/write-queue.js +147 -0
  184. package/package.json +134 -4
@@ -0,0 +1,64 @@
1
+ import type { TelemetryPort, TelemetrySpan, Transport, W3cTraceContext } from "../core/index.js";
2
+ export declare const OtelSpanKind: {
3
+ readonly INTERNAL: 0;
4
+ readonly SERVER: 1;
5
+ readonly CLIENT: 2;
6
+ readonly PRODUCER: 3;
7
+ readonly CONSUMER: 4;
8
+ };
9
+ export type OtelSpanKindValue = (typeof OtelSpanKind)[keyof typeof OtelSpanKind];
10
+ export declare const OtelSpanStatusCode: {
11
+ readonly UNSET: 0;
12
+ readonly OK: 1;
13
+ readonly ERROR: 2;
14
+ };
15
+ export type OtelSpanStatusCodeValue = (typeof OtelSpanStatusCode)[keyof typeof OtelSpanStatusCode];
16
+ export type OtelAttributeValue = string | number | boolean;
17
+ export interface OtelSpanContext {
18
+ readonly traceId: string;
19
+ readonly spanId: string;
20
+ readonly traceFlags: number;
21
+ readonly traceState?: string;
22
+ }
23
+ export interface OtelSpan {
24
+ setAttribute(key: string, value: OtelAttributeValue): void;
25
+ recordException(exception: unknown): void;
26
+ setStatus(status: {
27
+ readonly code: OtelSpanStatusCodeValue;
28
+ readonly message?: string;
29
+ }): void;
30
+ end(): void;
31
+ }
32
+ export interface OtelTracer {
33
+ startSpan(name: string, options?: {
34
+ readonly kind?: OtelSpanKindValue;
35
+ readonly attributes?: Record<string, OtelAttributeValue>;
36
+ }): OtelSpan;
37
+ }
38
+ export interface OtelContextSource {
39
+ activeSpanContext(): OtelSpanContext | undefined;
40
+ activeBaggage?(): string | undefined;
41
+ }
42
+ export declare function sanitizeSecretString(value: string): string;
43
+ export declare function mapNetworkTransport(binding: string): "pipe" | "tcp" | string;
44
+ export interface OtelTelemetryOptions {
45
+ readonly tracer: OtelTracer;
46
+ readonly contextSource?: OtelContextSource;
47
+ readonly captureContent?: boolean;
48
+ readonly onDiagnostic?: (diagnostic: string) => void;
49
+ }
50
+ export declare class OtelTelemetryPort implements TelemetryPort {
51
+ private readonly tracer;
52
+ private readonly contextSource;
53
+ readonly captureContent: boolean;
54
+ private readonly onDiagnostic;
55
+ constructor(opts: OtelTelemetryOptions);
56
+ activeContext(): W3cTraceContext | undefined;
57
+ startClientSpan(name: string, attrs: Record<string, OtelAttributeValue>): TelemetrySpan;
58
+ }
59
+ export declare function createOtelTelemetry(opts: OtelTelemetryOptions): OtelTelemetryPort;
60
+ export interface InstrumentOptions {
61
+ readonly protocolVersion?: string;
62
+ readonly spanName?: (method: string) => string;
63
+ }
64
+ export declare function instrumentTransport(transport: Transport, telemetry: TelemetryPort, opts?: InstrumentOptions): Transport;
@@ -0,0 +1,196 @@
1
+ import { validateTraceContext } from "../core/index.js";
2
+ export const OtelSpanKind = {
3
+ INTERNAL: 0,
4
+ SERVER: 1,
5
+ CLIENT: 2,
6
+ PRODUCER: 3,
7
+ CONSUMER: 4,
8
+ };
9
+ export const OtelSpanStatusCode = {
10
+ UNSET: 0,
11
+ OK: 1,
12
+ ERROR: 2,
13
+ };
14
+ const SECRET_KEY_RE = /(?:^|\.)(?:token|access_token|refresh_token|id_token|client_secret|secret|password|passwd|assertion|client_assertion|authorization|auth|cookie|set-cookie|api_key|apikey)$/i;
15
+ const CONTENT_KEY_RE = /(?:^|\.)(?:arguments|args|input|inputs|params|result|results|output|outputs|content|requestState|request_state|body|payload|text|prompt|completion|messages)$/i;
16
+ const CREDENTIAL_URL_RE = /\b[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@/g;
17
+ const QUERY_SECRET_RE = /([?&](?:access_token|refresh_token|id_token|client_secret|assertion|client_assertion|token|secret|password)=)[^&\s#]+/gi;
18
+ const BEARER_RE = /\b(Bearer|Basic|DPoP)\s+[A-Za-z0-9\-._~+/]+=*/gi;
19
+ export function sanitizeSecretString(value) {
20
+ return value
21
+ .replace(CREDENTIAL_URL_RE, (m) => m.replace(/:\/\/[^@]+@/, "://[REDACTED]@"))
22
+ .replace(QUERY_SECRET_RE, "$1[REDACTED]")
23
+ .replace(BEARER_RE, "$1 [REDACTED]");
24
+ }
25
+ function isBlockedAttributeKey(key, captureContent) {
26
+ if (key === "mcp.session.id")
27
+ return true;
28
+ if (SECRET_KEY_RE.test(key))
29
+ return true;
30
+ if (!captureContent && CONTENT_KEY_RE.test(key))
31
+ return true;
32
+ return false;
33
+ }
34
+ function sanitizeAttributeValue(key, value, captureContent) {
35
+ if (isBlockedAttributeKey(key, captureContent))
36
+ return undefined;
37
+ if (typeof value !== "string")
38
+ return value;
39
+ const sanitized = sanitizeSecretString(value);
40
+ if (!captureContent && /(?:requestState|authorization|client_secret|access_token|assertion)/i.test(sanitized)) {
41
+ return "[REDACTED]";
42
+ }
43
+ return sanitized;
44
+ }
45
+ function sanitizeException(err, captureContent) {
46
+ const raw = err instanceof Error ? err.message : String(err);
47
+ let msg = sanitizeSecretString(raw);
48
+ if (!captureContent) {
49
+ msg = msg.replace(/(?:arguments|result|requestState|authorization|token|secret|assertion)\s*[:=]\s*\S+/gi, "[REDACTED]");
50
+ }
51
+ const out = new Error(msg);
52
+ if (err instanceof Error)
53
+ out.name = err.name;
54
+ return out;
55
+ }
56
+ export function mapNetworkTransport(binding) {
57
+ if (binding === "stdio")
58
+ return "pipe";
59
+ if (binding === "streamable-http")
60
+ return "tcp";
61
+ return binding;
62
+ }
63
+ function countListMembers(value) {
64
+ return value.split(",").filter((part) => part.trim().length > 0).length;
65
+ }
66
+ function utf8ByteLength(value) {
67
+ return Buffer.byteLength(value, "utf8");
68
+ }
69
+ export class OtelTelemetryPort {
70
+ tracer;
71
+ contextSource;
72
+ captureContent;
73
+ onDiagnostic;
74
+ constructor(opts) {
75
+ this.tracer = opts.tracer;
76
+ this.contextSource = opts.contextSource;
77
+ this.captureContent = opts.captureContent === true;
78
+ this.onDiagnostic = opts.onDiagnostic;
79
+ }
80
+ activeContext() {
81
+ const spanCtx = this.contextSource?.activeSpanContext();
82
+ if (!spanCtx)
83
+ return undefined;
84
+ const flagsHex = (spanCtx.traceFlags & 0xff).toString(16).padStart(2, "0");
85
+ const traceparent = `00-${spanCtx.traceId}-${spanCtx.spanId}-${flagsHex}`;
86
+ let tracestate = spanCtx.traceState;
87
+ if (tracestate !== undefined) {
88
+ if (tracestate.length > 512 || countListMembers(tracestate) > 32) {
89
+ this.onDiagnostic?.("tracestate-truncated-or-dropped");
90
+ tracestate = undefined;
91
+ }
92
+ }
93
+ let baggage = this.contextSource?.activeBaggage?.();
94
+ if (baggage !== undefined) {
95
+ if (utf8ByteLength(baggage) > 8192 || countListMembers(baggage) > 64) {
96
+ this.onDiagnostic?.("baggage-dropped");
97
+ baggage = undefined;
98
+ }
99
+ }
100
+ const candidate = {
101
+ traceparent,
102
+ ...(tracestate !== undefined ? { tracestate } : {}),
103
+ ...(baggage !== undefined ? { baggage } : {}),
104
+ };
105
+ const checked = validateTraceContext(candidate);
106
+ for (const d of checked.diagnostics) {
107
+ this.onDiagnostic?.(d);
108
+ }
109
+ return checked.valid;
110
+ }
111
+ startClientSpan(name, attrs) {
112
+ const filtered = {};
113
+ for (const [k, v] of Object.entries(attrs)) {
114
+ const sv = sanitizeAttributeValue(k, v, this.captureContent);
115
+ if (sv !== undefined)
116
+ filtered[k] = sv;
117
+ }
118
+ const otelSpan = this.tracer.startSpan(name, {
119
+ kind: OtelSpanKind.CLIENT,
120
+ attributes: filtered,
121
+ });
122
+ const captureContent = this.captureContent;
123
+ return {
124
+ setAttribute(key, value) {
125
+ const sv = sanitizeAttributeValue(key, value, captureContent);
126
+ if (sv !== undefined)
127
+ otelSpan.setAttribute(key, sv);
128
+ },
129
+ recordException(err) {
130
+ otelSpan.recordException(sanitizeException(err, captureContent));
131
+ },
132
+ end(status) {
133
+ otelSpan.setStatus(status.ok
134
+ ? { code: OtelSpanStatusCode.OK }
135
+ : {
136
+ code: OtelSpanStatusCode.ERROR,
137
+ ...(status.errorKind !== undefined ? { message: status.errorKind } : {}),
138
+ });
139
+ otelSpan.end();
140
+ },
141
+ };
142
+ }
143
+ }
144
+ export function createOtelTelemetry(opts) {
145
+ return new OtelTelemetryPort(opts);
146
+ }
147
+ export function instrumentTransport(transport, telemetry, opts) {
148
+ return {
149
+ binding: transport.binding,
150
+ diagnostics: transport.diagnostics,
151
+ notify(msg, ctx) {
152
+ return transport.notify(msg, ctx);
153
+ },
154
+ close(closeOpts) {
155
+ return transport.close(closeOpts);
156
+ },
157
+ start(msg, ctx) {
158
+ const spanName = opts?.spanName ? opts.spanName(msg.method) : `mcp.client ${msg.method}`;
159
+ const attrs = {
160
+ "mcp.method.name": msg.method,
161
+ "network.transport": mapNetworkTransport(transport.binding),
162
+ ...(opts?.protocolVersion !== undefined ? { "mcp.protocol.version": opts.protocolVersion } : {}),
163
+ };
164
+ const span = telemetry.startClientSpan(spanName, attrs);
165
+ const inner = transport.start(msg, ctx);
166
+ const done = inner.done.then((end) => {
167
+ if (end.kind === "response") {
168
+ if ("error" in end.message) {
169
+ span.setAttribute("mcp.outcome.kind", "jsonrpc-error");
170
+ span.end({ ok: false, errorKind: "jsonrpc-error" });
171
+ }
172
+ else {
173
+ span.setAttribute("mcp.outcome.kind", "ok");
174
+ span.end({ ok: true });
175
+ }
176
+ }
177
+ else {
178
+ span.setAttribute("mcp.outcome.kind", end.failure.kind);
179
+ span.recordException(new Error(end.failure.message));
180
+ span.end({ ok: false, errorKind: end.failure.kind });
181
+ }
182
+ return end;
183
+ }, (err) => {
184
+ span.setAttribute("mcp.outcome.kind", "transport-error");
185
+ span.recordException(err);
186
+ span.end({ ok: false, errorKind: "transport-error" });
187
+ throw err;
188
+ });
189
+ return {
190
+ ...(inner.abortDelivery ? { abortDelivery: () => inner.abortDelivery() } : {}),
191
+ notifications: inner.notifications,
192
+ done,
193
+ };
194
+ },
195
+ };
196
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Consumer test utilities: an in-memory Transport and a tiny scriptable MCP
3
+ * tool server. No processes, sockets, or fixtures required.
4
+ *
5
+ * const transport = createToolServer({
6
+ * echo: { handler: (args) => ({ content: [{ type: "text", text: String(args.message) }] }) },
7
+ * });
8
+ * const connection = await connect({ transport });
9
+ */
10
+ import { type Exchange, type JsonRpcNotification, type JsonRpcRequest, type RequestId, type Transport, type TransportCall, type TransportDiagnostic } from "../core/index.js";
11
+ /** Throw from a handler to return a JSON-RPC error instead of a result. */
12
+ export declare class FakeJsonRpcError extends Error {
13
+ readonly code: number;
14
+ readonly data?: unknown;
15
+ constructor(code: number, message: string, data?: unknown);
16
+ }
17
+ export type InMemoryHandler = (msg: JsonRpcRequest) => unknown | Promise<unknown>;
18
+ export declare class InMemoryTransport implements Transport {
19
+ #private;
20
+ readonly binding = "in-memory";
21
+ constructor(handler: InMemoryHandler);
22
+ /** Push a notification into one active request stream (or all of them). */
23
+ push(notification: JsonRpcNotification, id?: RequestId): boolean;
24
+ start(msg: JsonRpcRequest, ctx: TransportCall): Exchange;
25
+ notify(_msg: JsonRpcNotification, _ctx: TransportCall): Promise<void>;
26
+ close(): Promise<void>;
27
+ get diagnostics(): AsyncIterable<TransportDiagnostic>;
28
+ }
29
+ export interface FakeTool {
30
+ readonly description?: string;
31
+ readonly inputSchema?: Record<string, unknown>;
32
+ /** Return a CallToolResult-shaped object, or any value to wrap as text content. */
33
+ readonly handler: (args: unknown) => unknown | Promise<unknown>;
34
+ }
35
+ /** A minimal MCP server exposing only tools, suitable for consumer unit tests. */
36
+ export declare function createToolServer(tools: Record<string, FakeTool>): InMemoryTransport;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Consumer test utilities: an in-memory Transport and a tiny scriptable MCP
3
+ * tool server. No processes, sockets, or fixtures required.
4
+ *
5
+ * const transport = createToolServer({
6
+ * echo: { handler: (args) => ({ content: [{ type: "text", text: String(args.message) }] }) },
7
+ * });
8
+ * const connection = await connect({ transport });
9
+ */
10
+ import { NotificationQueue, } from "../core/index.js";
11
+ /** Throw from a handler to return a JSON-RPC error instead of a result. */
12
+ export class FakeJsonRpcError extends Error {
13
+ code;
14
+ data;
15
+ constructor(code, message, data) {
16
+ super(message);
17
+ this.code = code;
18
+ this.data = data;
19
+ this.name = "FakeJsonRpcError";
20
+ }
21
+ }
22
+ async function* emptyDiagnostics() {
23
+ // no diagnostics in the in-memory transport
24
+ }
25
+ export class InMemoryTransport {
26
+ binding = "in-memory";
27
+ #handler;
28
+ #streams = new Map();
29
+ #closers = new Map();
30
+ constructor(handler) {
31
+ this.#handler = handler;
32
+ }
33
+ /** Push a notification into one active request stream (or all of them). */
34
+ push(notification, id) {
35
+ if (id !== undefined)
36
+ return this.#streams.get(id)?.push(notification) ?? false;
37
+ let delivered = false;
38
+ for (const queue of this.#streams.values())
39
+ delivered = queue.push(notification) || delivered;
40
+ return delivered;
41
+ }
42
+ start(msg, ctx) {
43
+ const notifications = new NotificationQueue();
44
+ this.#streams.set(msg.id, notifications);
45
+ const aborted = () => ({
46
+ kind: "failure",
47
+ failure: { kind: "closed", message: "aborted" },
48
+ delivery: "delivered-no-response",
49
+ });
50
+ const onAbort = new Promise((resolve) => {
51
+ const finish = () => resolve(aborted());
52
+ this.#closers.set(msg.id, finish);
53
+ if (ctx.signal.aborted)
54
+ finish();
55
+ else
56
+ ctx.signal.addEventListener("abort", finish, { once: true });
57
+ });
58
+ const work = (async () => {
59
+ try {
60
+ const result = await this.#handler(msg);
61
+ return {
62
+ kind: "response",
63
+ message: { jsonrpc: "2.0", id: msg.id, result: result },
64
+ };
65
+ }
66
+ catch (error) {
67
+ if (error instanceof FakeJsonRpcError) {
68
+ return {
69
+ kind: "response",
70
+ message: {
71
+ jsonrpc: "2.0",
72
+ id: msg.id,
73
+ error: { code: error.code, message: error.message, ...(error.data !== undefined ? { data: error.data } : {}) },
74
+ },
75
+ };
76
+ }
77
+ return {
78
+ kind: "failure",
79
+ failure: {
80
+ kind: "stream-broken",
81
+ message: error instanceof Error ? error.message : String(error),
82
+ },
83
+ delivery: "delivered-no-response",
84
+ };
85
+ }
86
+ })();
87
+ const done = Promise.race([work, onAbort]).finally(() => {
88
+ this.#streams.delete(msg.id);
89
+ this.#closers.delete(msg.id);
90
+ notifications.close();
91
+ });
92
+ return { notifications, done };
93
+ }
94
+ async notify(_msg, _ctx) {
95
+ // notifications are accepted and ignored
96
+ }
97
+ async close() {
98
+ for (const finish of [...this.#closers.values()])
99
+ finish();
100
+ }
101
+ get diagnostics() {
102
+ return emptyDiagnostics();
103
+ }
104
+ }
105
+ /** A minimal MCP server exposing only tools, suitable for consumer unit tests. */
106
+ export function createToolServer(tools) {
107
+ return new InMemoryTransport(async (msg) => {
108
+ switch (msg.method) {
109
+ case "server/discover":
110
+ return {
111
+ cacheScope: "public",
112
+ capabilities: { tools: {} },
113
+ supportedVersions: ["2026-07-28"],
114
+ serverInfo: { name: "in-memory", version: "0.0.0" },
115
+ };
116
+ case "tools/list":
117
+ return {
118
+ tools: Object.entries(tools).map(([name, tool]) => ({
119
+ name,
120
+ description: tool.description ?? "",
121
+ inputSchema: tool.inputSchema ?? { type: "object", properties: {} },
122
+ })),
123
+ };
124
+ case "tools/call": {
125
+ const params = (msg.params ?? {});
126
+ const tool = params.name !== undefined ? tools[params.name] : undefined;
127
+ if (!tool)
128
+ throw new FakeJsonRpcError(-32602, `unknown tool: ${String(params.name)}`);
129
+ const result = await tool.handler(params.arguments);
130
+ if (typeof result === "object" && result !== null && "content" in result)
131
+ return result;
132
+ return {
133
+ content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }],
134
+ };
135
+ }
136
+ default:
137
+ throw new FakeJsonRpcError(-32601, `method not found: ${msg.method}`);
138
+ }
139
+ });
140
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Header value encoding and `x-mcp-header` validation (IMPLEMENTATION_PLAN §7.2/§7.3).
3
+ * No Node-only APIs: base64 is encoded from UTF-8 bytes by hand.
4
+ */
5
+ export declare function base64EncodeUtf8(text: string): string;
6
+ /** True when the plain value may be sent as-is (§7.2). */
7
+ export declare function isPlainHeaderSafe(value: string): boolean;
8
+ export declare function encodeHeaderValue(value: string | number | boolean): string;
9
+ /** Case-insensitive lookup in a plain header record (HTTP-CASE-1). Values stay case-sensitive. */
10
+ export declare function getHeaderCaseInsensitive(headers: Readonly<Record<string, string>> | Headers, name: string): string | undefined;
11
+ export interface AnnotatedParam {
12
+ readonly path: readonly string[];
13
+ readonly headerName: string;
14
+ readonly type: "string" | "integer" | "boolean";
15
+ }
16
+ export interface XmcpValidation {
17
+ readonly valid: boolean;
18
+ readonly violations: readonly string[];
19
+ readonly params: readonly AnnotatedParam[];
20
+ }
21
+ export declare function validateXmcpHeaderSchema(inputSchema: unknown): XmcpValidation;
22
+ /** Extract a value at an exact property path; undefined when absent. */
23
+ export declare function extractAtPath(args: unknown, path: readonly string[]): unknown;
24
+ export { isReadOnlyMethod } from "../core/index.js";
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Header value encoding and `x-mcp-header` validation (IMPLEMENTATION_PLAN §7.2/§7.3).
3
+ * No Node-only APIs: base64 is encoded from UTF-8 bytes by hand.
4
+ */
5
+ const SENTINEL_RE = /^=\?base64\?.*\?=$/;
6
+ const TCHAR_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
7
+ export function base64EncodeUtf8(text) {
8
+ const bytes = new TextEncoder().encode(text);
9
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
10
+ let out = "";
11
+ for (let i = 0; i < bytes.length; i += 3) {
12
+ const b0 = bytes[i];
13
+ const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
14
+ const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
15
+ out += alphabet[b0 >> 2];
16
+ out += alphabet[((b0 & 0x03) << 4) | (b1 >> 4)];
17
+ out += i + 1 < bytes.length ? alphabet[((b1 & 0x0f) << 2) | (b2 >> 6)] : "=";
18
+ out += i + 2 < bytes.length ? alphabet[b2 & 0x3f] : "=";
19
+ }
20
+ return out;
21
+ }
22
+ /** True when the plain value may be sent as-is (§7.2). */
23
+ export function isPlainHeaderSafe(value) {
24
+ if (SENTINEL_RE.test(value))
25
+ return false;
26
+ if (value.length > 0 && (value.startsWith(" ") || value.startsWith("\t") || value.endsWith(" ") || value.endsWith("\t"))) {
27
+ return false;
28
+ }
29
+ for (const ch of value) {
30
+ const code = ch.codePointAt(0);
31
+ const visible = code >= 0x21 && code <= 0x7e;
32
+ if (!visible && ch !== " " && ch !== "\t")
33
+ return false;
34
+ }
35
+ return true;
36
+ }
37
+ export function encodeHeaderValue(value) {
38
+ const text = typeof value === "string" ? value : typeof value === "boolean" ? (value ? "true" : "false") : String(value);
39
+ const encoded = isPlainHeaderSafe(text) ? text : `=?base64?${base64EncodeUtf8(text)}?=`;
40
+ if (encoded.includes("\r") || encoded.includes("\n")) {
41
+ throw new TypeError("Encoded header value must not contain CR/LF");
42
+ }
43
+ return encoded;
44
+ }
45
+ /** Case-insensitive lookup in a plain header record (HTTP-CASE-1). Values stay case-sensitive. */
46
+ export function getHeaderCaseInsensitive(headers, name) {
47
+ if (typeof Headers !== "undefined" && headers instanceof Headers)
48
+ return headers.get(name) ?? undefined;
49
+ const wanted = name.toLowerCase();
50
+ for (const [k, v] of Object.entries(headers)) {
51
+ if (k.toLowerCase() === wanted)
52
+ return v;
53
+ }
54
+ return undefined;
55
+ }
56
+ function isRecord(v) {
57
+ return typeof v === "object" && v !== null && !Array.isArray(v);
58
+ }
59
+ /**
60
+ * Collect x-mcp-header annotations. Reachability follows only `properties`
61
+ * chains; annotations under items/composition/conditionals/$ref are found
62
+ * with reachable=false so the owning tool is rejected, never dereferenced.
63
+ */
64
+ function collect(node, path, reachable, viaRef, out) {
65
+ if (!isRecord(node))
66
+ return;
67
+ const nodeViaRef = viaRef || "$ref" in node;
68
+ if ("x-mcp-header" in node) {
69
+ out.push({ path, headerValue: node["x-mcp-header"], schema: node, reachable, viaRef: nodeViaRef });
70
+ }
71
+ for (const [key, value] of Object.entries(node)) {
72
+ if (key === "properties" && isRecord(value)) {
73
+ for (const [prop, sub] of Object.entries(value)) {
74
+ collect(sub, [...path, prop], reachable, nodeViaRef, out);
75
+ }
76
+ }
77
+ else if (key === "propertyNames" || key === "additionalProperties") {
78
+ collect(value, path, false, nodeViaRef, out);
79
+ }
80
+ else if (isRecord(value) || Array.isArray(value)) {
81
+ // Any other nesting (items, oneOf/anyOf/allOf/not, if/then/else, $defs, ...) is not a properties chain.
82
+ const items = Array.isArray(value) ? value : [value];
83
+ for (const item of items)
84
+ collect(item, path, false, nodeViaRef, out);
85
+ }
86
+ }
87
+ }
88
+ export function validateXmcpHeaderSchema(inputSchema) {
89
+ const violations = [];
90
+ const params = [];
91
+ if (!isRecord(inputSchema)) {
92
+ return { valid: true, violations, params };
93
+ }
94
+ const found = [];
95
+ collect(inputSchema, [], true, false, found);
96
+ const seen = new Map();
97
+ for (const f of found) {
98
+ const label = f.path.join(".") || "(root)";
99
+ if (!f.reachable) {
100
+ violations.push(`x-mcp-header at '${label}' is not reachable through a properties chain`);
101
+ continue;
102
+ }
103
+ if (f.viaRef) {
104
+ violations.push(`x-mcp-header at '${label}' is reached through $ref`);
105
+ continue;
106
+ }
107
+ if (typeof f.headerValue !== "string" || f.headerValue.length === 0) {
108
+ violations.push(`x-mcp-header at '${label}' must be a non-empty string`);
109
+ continue;
110
+ }
111
+ if (!TCHAR_RE.test(f.headerValue)) {
112
+ violations.push(`x-mcp-header at '${label}' is not a valid 1*tchar token`);
113
+ continue;
114
+ }
115
+ const lower = f.headerValue.toLowerCase();
116
+ if (seen.has(lower)) {
117
+ violations.push(`x-mcp-header '${f.headerValue}' at '${label}' duplicates '${seen.get(lower)}' case-insensitively`);
118
+ continue;
119
+ }
120
+ seen.set(lower, f.headerValue);
121
+ const type = f.schema["type"];
122
+ if (type !== "string" && type !== "integer" && type !== "boolean") {
123
+ violations.push(`x-mcp-header at '${label}' applies only to string/integer/boolean properties`);
124
+ continue;
125
+ }
126
+ params.push({ path: f.path, headerName: f.headerValue, type });
127
+ }
128
+ return { valid: violations.length === 0, violations, params };
129
+ }
130
+ /** Extract a value at an exact property path; undefined when absent. */
131
+ export function extractAtPath(args, path) {
132
+ let cur = args;
133
+ for (const key of path) {
134
+ if (!isRecord(cur))
135
+ return undefined;
136
+ cur = cur[key];
137
+ }
138
+ return cur;
139
+ }
140
+ export { isReadOnlyMethod } from "../core/index.js";
@@ -0,0 +1,3 @@
1
+ export * from "./transport.js";
2
+ export * from "./sse.js";
3
+ export * from "./headers.js";
@@ -0,0 +1,3 @@
1
+ export * from "./transport.js";
2
+ export * from "./sse.js";
3
+ export * from "./headers.js";
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Incremental WHATWG Server-Sent Events parser (§7.5).
3
+ * Chunk-boundary invariant: for any byte stream and any split into chunks,
4
+ * push(chunk) sequences yield exactly the same dispatched events.
5
+ */
6
+ export interface SseEvent {
7
+ readonly event: string;
8
+ readonly data: string;
9
+ readonly id?: string;
10
+ readonly retry?: number;
11
+ }
12
+ export declare const DEFAULT_MAX_SSE_EVENT_BYTES: number;
13
+ export declare class SseEventTooLargeError extends Error {
14
+ readonly observed: number;
15
+ readonly max: number;
16
+ constructor(observed: number, max: number);
17
+ }
18
+ export declare class SseParser {
19
+ private readonly decoder;
20
+ private readonly maxEventBytes;
21
+ private lineBuffer;
22
+ private dataBuffer;
23
+ private eventType;
24
+ private lastId;
25
+ private lastRetry;
26
+ private started;
27
+ constructor(maxEventBytes?: number);
28
+ push(chunk: Uint8Array | string): SseEvent[];
29
+ /** Flush the decoder. A pending unterminated line is processed; no event is dispatched without a blank line. */
30
+ end(): SseEvent[];
31
+ private takeLine;
32
+ private processLine;
33
+ }