@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.
- package/LICENSE +21 -0
- package/README.md +337 -2
- package/adapters/pi/bridge.ts +721 -0
- package/adapters/pi/config.ts +364 -0
- package/adapters/pi/content-offloaded.ts +53 -0
- package/adapters/pi/content.ts +78 -0
- package/adapters/pi/diagnostics.ts +26 -0
- package/adapters/pi/elicitation.ts +133 -0
- package/adapters/pi/index.ts +210 -0
- package/adapters/pi/oauth.ts +219 -0
- package/adapters/pi/pi-api.ts +133 -0
- package/adapters/pi/resources.ts +177 -0
- package/adapters/pi/result-files.ts +32 -0
- package/adapters/pi/tasks.ts +49 -0
- package/dist/auth/client-credentials.d.ts +65 -0
- package/dist/auth/client-credentials.js +388 -0
- package/dist/auth/discovery.d.ts +28 -0
- package/dist/auth/discovery.js +125 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.js +5 -0
- package/dist/auth/node-ports.d.ts +8 -0
- package/dist/auth/node-ports.js +67 -0
- package/dist/auth/protocol.d.ts +12 -0
- package/dist/auth/protocol.js +39 -0
- package/dist/auth/provider.d.ts +114 -0
- package/dist/auth/provider.js +407 -0
- package/dist/auth/safe-fetch.d.ts +14 -0
- package/dist/auth/safe-fetch.js +130 -0
- package/dist/client/events.d.ts +33 -0
- package/dist/client/events.js +84 -0
- package/dist/client/index.d.ts +65 -0
- package/dist/client/index.js +128 -0
- package/dist/core/auth-types.d.ts +36 -0
- package/dist/core/auth-types.js +11 -0
- package/dist/core/bearer-challenge.d.ts +3 -0
- package/dist/core/bearer-challenge.js +63 -0
- package/dist/core/cancel.d.ts +70 -0
- package/dist/core/cancel.js +177 -0
- package/dist/core/extension.d.ts +33 -0
- package/dist/core/extension.js +145 -0
- package/dist/core/index.d.ts +73 -0
- package/dist/core/index.js +129 -0
- package/dist/core/jsonrpc.d.ts +49 -0
- package/dist/core/jsonrpc.js +80 -0
- package/dist/core/lifecycle.d.ts +128 -0
- package/dist/core/lifecycle.js +251 -0
- package/dist/core/outcome.d.ts +98 -0
- package/dist/core/outcome.js +32 -0
- package/dist/core/ports.d.ts +144 -0
- package/dist/core/ports.js +67 -0
- package/dist/core/progress.d.ts +81 -0
- package/dist/core/progress.js +205 -0
- package/dist/core/request.d.ts +108 -0
- package/dist/core/request.js +578 -0
- package/dist/core/schema/index.d.ts +1 -0
- package/dist/core/schema/index.js +1 -0
- package/dist/core/schema/types.d.ts +4154 -0
- package/dist/core/schema/types.js +6 -0
- package/dist/core/telemetry.d.ts +25 -0
- package/dist/core/telemetry.js +37 -0
- package/dist/ext-events/index.d.ts +79 -0
- package/dist/ext-events/index.js +218 -0
- package/dist/ext-events/model.d.ts +10 -0
- package/dist/ext-events/model.js +6 -0
- package/dist/ext-events/push.d.ts +18 -0
- package/dist/ext-events/push.js +101 -0
- package/dist/ext-events/stream.d.ts +6 -0
- package/dist/ext-events/stream.js +60 -0
- package/dist/ext-server-cards/index.d.ts +107 -0
- package/dist/ext-server-cards/index.js +249 -0
- package/dist/ext-skills/cache.d.ts +20 -0
- package/dist/ext-skills/cache.js +101 -0
- package/dist/ext-skills/client.d.ts +82 -0
- package/dist/ext-skills/client.js +292 -0
- package/dist/ext-skills/extension.d.ts +16 -0
- package/dist/ext-skills/extension.js +29 -0
- package/dist/ext-skills/index.d.ts +4 -0
- package/dist/ext-skills/index.js +4 -0
- package/dist/ext-skills/verify.d.ts +57 -0
- package/dist/ext-skills/verify.js +168 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mrtr-cache/cache.d.ts +51 -0
- package/dist/mrtr-cache/cache.js +295 -0
- package/dist/mrtr-cache/client.d.ts +24 -0
- package/dist/mrtr-cache/client.js +44 -0
- package/dist/mrtr-cache/common.d.ts +10 -0
- package/dist/mrtr-cache/common.js +9 -0
- package/dist/mrtr-cache/elicitation.d.ts +42 -0
- package/dist/mrtr-cache/elicitation.js +221 -0
- package/dist/mrtr-cache/index.d.ts +9 -0
- package/dist/mrtr-cache/index.js +8 -0
- package/dist/mrtr-cache/mrtr.d.ts +37 -0
- package/dist/mrtr-cache/mrtr.js +250 -0
- package/dist/mrtr-cache/refresh.d.ts +8 -0
- package/dist/mrtr-cache/refresh.js +30 -0
- package/dist/mrtr-cache/stream.d.ts +5 -0
- package/dist/mrtr-cache/stream.js +18 -0
- package/dist/mrtr-cache/subscriptions.d.ts +96 -0
- package/dist/mrtr-cache/subscriptions.js +288 -0
- package/dist/mrtr-cache/tasks.d.ts +103 -0
- package/dist/mrtr-cache/tasks.js +444 -0
- package/dist/ops/common.d.ts +18 -0
- package/dist/ops/common.js +39 -0
- package/dist/ops/completion.d.ts +44 -0
- package/dist/ops/completion.js +65 -0
- package/dist/ops/content.d.ts +40 -0
- package/dist/ops/content.js +117 -0
- package/dist/ops/icons.d.ts +29 -0
- package/dist/ops/icons.js +82 -0
- package/dist/ops/index.d.ts +30 -0
- package/dist/ops/index.js +28 -0
- package/dist/ops/pagination.d.ts +32 -0
- package/dist/ops/pagination.js +65 -0
- package/dist/ops/prompts.d.ts +32 -0
- package/dist/ops/prompts.js +68 -0
- package/dist/ops/resources.d.ts +42 -0
- package/dist/ops/resources.js +104 -0
- package/dist/ops/schema.d.ts +39 -0
- package/dist/ops/schema.js +163 -0
- package/dist/ops/tools.d.ts +88 -0
- package/dist/ops/tools.js +169 -0
- package/dist/ops/uri-template.d.ts +3 -0
- package/dist/ops/uri-template.js +101 -0
- package/dist/server/index.d.ts +5 -0
- package/dist/server/index.js +5 -0
- package/dist/server/mrtr.d.ts +38 -0
- package/dist/server/mrtr.js +99 -0
- package/dist/server/protocol.d.ts +21 -0
- package/dist/server/protocol.js +49 -0
- package/dist/server/server.d.ts +105 -0
- package/dist/server/server.js +383 -0
- package/dist/server/skills.d.ts +45 -0
- package/dist/server/skills.js +73 -0
- package/dist/server/uri.d.ts +2 -0
- package/dist/server/uri.js +27 -0
- package/dist/server-events/bus.d.ts +40 -0
- package/dist/server-events/bus.js +84 -0
- package/dist/server-events/events.d.ts +36 -0
- package/dist/server-events/events.js +108 -0
- package/dist/server-events/index.d.ts +6 -0
- package/dist/server-events/index.js +6 -0
- package/dist/server-events/notices.d.ts +24 -0
- package/dist/server-events/notices.js +31 -0
- package/dist/server-events/subscriptions.d.ts +33 -0
- package/dist/server-events/subscriptions.js +77 -0
- package/dist/server-events/tasks.d.ts +43 -0
- package/dist/server-events/tasks.js +101 -0
- package/dist/server-events/types.d.ts +25 -0
- package/dist/server-events/types.js +34 -0
- package/dist/server-transport/auth.d.ts +20 -0
- package/dist/server-transport/auth.js +29 -0
- package/dist/server-transport/channel.d.ts +17 -0
- package/dist/server-transport/channel.js +47 -0
- package/dist/server-transport/http.d.ts +19 -0
- package/dist/server-transport/http.js +209 -0
- package/dist/server-transport/index.d.ts +4 -0
- package/dist/server-transport/index.js +4 -0
- package/dist/server-transport/stdio.d.ts +16 -0
- package/dist/server-transport/stdio.js +83 -0
- package/dist/telemetry-otel/index.d.ts +64 -0
- package/dist/telemetry-otel/index.js +196 -0
- package/dist/testing/index.d.ts +36 -0
- package/dist/testing/index.js +140 -0
- package/dist/transport-http/headers.d.ts +24 -0
- package/dist/transport-http/headers.js +140 -0
- package/dist/transport-http/index.d.ts +3 -0
- package/dist/transport-http/index.js +3 -0
- package/dist/transport-http/sse.d.ts +33 -0
- package/dist/transport-http/sse.js +152 -0
- package/dist/transport-http/transport.d.ts +66 -0
- package/dist/transport-http/transport.js +854 -0
- package/dist/transport-stdio/framing.d.ts +50 -0
- package/dist/transport-stdio/framing.js +154 -0
- package/dist/transport-stdio/index.d.ts +4 -0
- package/dist/transport-stdio/index.js +4 -0
- package/dist/transport-stdio/stderr-ring.d.ts +27 -0
- package/dist/transport-stdio/stderr-ring.js +105 -0
- package/dist/transport-stdio/transport.d.ts +142 -0
- package/dist/transport-stdio/transport.js +743 -0
- package/dist/transport-stdio/write-queue.d.ts +48 -0
- package/dist/transport-stdio/write-queue.js +147 -0
- package/package.json +134 -4
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { lookup } from 'node:dns/promises';
|
|
2
|
+
import { request as http } from 'node:http';
|
|
3
|
+
import { request as https } from 'node:https';
|
|
4
|
+
import { BlockList, isIP } from 'node:net';
|
|
5
|
+
import { AuthError, fail, secureUrl } from './protocol.js';
|
|
6
|
+
const blocked = new BlockList();
|
|
7
|
+
for (const [ip, bits] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.0.0.0', 24], ['192.168.0.0', 16], ['198.18.0.0', 15], ['224.0.0.0', 3]]) {
|
|
8
|
+
blocked.addSubnet(ip, bits, 'ipv4');
|
|
9
|
+
}
|
|
10
|
+
blocked.addSubnet('::ffff:0:0', 96, 'ipv6');
|
|
11
|
+
const globalV6 = new BlockList();
|
|
12
|
+
globalV6.addSubnet('2000::', 3, 'ipv6');
|
|
13
|
+
for (const [ip, bits] of [['2001::', 32], ['2001:db8::', 32], ['2002::', 16], ['3fff::', 20]])
|
|
14
|
+
blocked.addSubnet(ip, bits, 'ipv6');
|
|
15
|
+
export class SafeFetch {
|
|
16
|
+
options;
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
this.options = options;
|
|
19
|
+
}
|
|
20
|
+
async fetch(input, init = {}) {
|
|
21
|
+
const timeout = AbortSignal.timeout(this.options.timeoutMs ?? 10_000);
|
|
22
|
+
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
|
23
|
+
const method = init.method ?? 'GET';
|
|
24
|
+
if (method !== 'GET' && method !== 'POST')
|
|
25
|
+
fail('fetch-method');
|
|
26
|
+
if (method === 'POST' && typeof init.body !== 'string')
|
|
27
|
+
fail('fetch-body');
|
|
28
|
+
try {
|
|
29
|
+
let url = secureUrl(input, this.options.allowInsecureDev);
|
|
30
|
+
const headers = new Headers(init.headers);
|
|
31
|
+
const auth = method === 'POST' ? headers.get('authorization') : null;
|
|
32
|
+
const contentType = method === 'POST' ? safeContentType(headers.get('content-type')) : null;
|
|
33
|
+
for (let hop = 0;; hop++) {
|
|
34
|
+
const response = await this.send(url, method, init.body, auth, contentType, signal);
|
|
35
|
+
if (![301, 302, 303, 307, 308].includes(response.status))
|
|
36
|
+
return response;
|
|
37
|
+
const location = response.headers.get('location');
|
|
38
|
+
if (method !== 'GET' || init.redirect === 'error' || hop >= 3 || !location)
|
|
39
|
+
fail('fetch-redirect');
|
|
40
|
+
// Validate the raw Location before URL resolution can normalize suspicious characters.
|
|
41
|
+
if (/[\s\\<>"'`|{}^]/u.test(location))
|
|
42
|
+
fail('fetch-redirect');
|
|
43
|
+
const next = secureUrl(new URL(location, url).href, this.options.allowInsecureDev);
|
|
44
|
+
if (url.protocol === 'https:' && next.protocol !== 'https:')
|
|
45
|
+
fail('fetch-redirect');
|
|
46
|
+
url = next;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
// Never surface Node/DNS error text or the peer's response body.
|
|
51
|
+
if (signal.aborted)
|
|
52
|
+
fail('fetch-timeout-or-aborted');
|
|
53
|
+
if (error instanceof AuthError)
|
|
54
|
+
throw error;
|
|
55
|
+
return fail('fetch-network');
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async send(url, method, body, auth, contentType, signal) {
|
|
59
|
+
signal.throwIfAborted();
|
|
60
|
+
const hostname = url.hostname.replace(/^\[|\]$/gu, '');
|
|
61
|
+
const literal = isIP(hostname);
|
|
62
|
+
const addresses = literal ? [{ address: hostname, family: literal }] : await new Promise((res, rej) => {
|
|
63
|
+
const abort = () => rej(new Error('aborted'));
|
|
64
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
65
|
+
void resolve(hostname).then(res, rej).finally(() => signal.removeEventListener('abort', abort));
|
|
66
|
+
});
|
|
67
|
+
if (addresses.length === 0)
|
|
68
|
+
fail('fetch-network');
|
|
69
|
+
for (const { address, family } of addresses) {
|
|
70
|
+
const denied = family === 4 ? blocked.check(address, 'ipv4') :
|
|
71
|
+
family !== 6 || !globalV6.check(address, 'ipv6') || blocked.check(address, 'ipv6');
|
|
72
|
+
if (denied && !this.options.allowAddress?.(hostname, address))
|
|
73
|
+
fail('fetch-address-blocked');
|
|
74
|
+
}
|
|
75
|
+
const { address, family } = addresses[0];
|
|
76
|
+
const maxBytes = this.options.maxBytes ?? 1024 * 1024;
|
|
77
|
+
return await new Promise((resolve, reject) => {
|
|
78
|
+
const send = url.protocol === 'https:' ? https : http;
|
|
79
|
+
const req = send(url, {
|
|
80
|
+
method, signal, agent: false, family,
|
|
81
|
+
// Keep the URL hostname for HTTP Host and TLS verification. Pin the socket lookup.
|
|
82
|
+
lookup: (_host, _opts, callback) => callback(null, address, family),
|
|
83
|
+
...(url.protocol === 'https:' ? { rejectUnauthorized: true } : {}),
|
|
84
|
+
headers: { accept: 'application/json', ...(method === 'POST' ? {
|
|
85
|
+
'content-type': contentType, 'content-length': Buffer.byteLength(body),
|
|
86
|
+
...(auth ? { authorization: auth } : {}),
|
|
87
|
+
} : {}) },
|
|
88
|
+
}, (res) => {
|
|
89
|
+
const code = res.statusCode ?? 502;
|
|
90
|
+
const headers = new Headers();
|
|
91
|
+
for (const [key, value] of Object.entries(res.headers)) {
|
|
92
|
+
if (typeof value === 'string')
|
|
93
|
+
headers.set(key, value);
|
|
94
|
+
}
|
|
95
|
+
res.on('error', reject);
|
|
96
|
+
const chunks = [];
|
|
97
|
+
let size = 0;
|
|
98
|
+
res.on('data', (chunk) => {
|
|
99
|
+
size += chunk.length;
|
|
100
|
+
if (size > maxBytes) {
|
|
101
|
+
reject(new AuthError('auth-failure', 'fetch-response-too-large'));
|
|
102
|
+
req.destroy();
|
|
103
|
+
}
|
|
104
|
+
else
|
|
105
|
+
chunks.push(chunk);
|
|
106
|
+
});
|
|
107
|
+
res.on('end', () => {
|
|
108
|
+
try {
|
|
109
|
+
resolve(new Response([204, 205, 304].includes(code) ? null : new Uint8Array(Buffer.concat(chunks)), { status: code, headers }));
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
reject(error);
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
});
|
|
116
|
+
req.on('error', reject);
|
|
117
|
+
req.end(method === 'POST' ? body : undefined);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const resolve = (host) => lookup(host, { all: true });
|
|
122
|
+
/** Allow only the token-endpoint default or an RFC 7591 JSON body; compare media types, ignoring parameters. */
|
|
123
|
+
function safeContentType(raw) {
|
|
124
|
+
if (raw === null)
|
|
125
|
+
return 'application/x-www-form-urlencoded';
|
|
126
|
+
const mediaType = raw.split(';', 1)[0].trim().toLowerCase();
|
|
127
|
+
if (mediaType !== 'application/x-www-form-urlencoded' && mediaType !== 'application/json')
|
|
128
|
+
fail('fetch-content-type');
|
|
129
|
+
return mediaType;
|
|
130
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push-first events facade over @mcp-client/ext-events.
|
|
3
|
+
*
|
|
4
|
+
* subscribe() returns an AsyncIterable of occurrences backed by the live
|
|
5
|
+
* events/stream (with heartbeat + reconnect); poll() is available explicitly
|
|
6
|
+
* for servers or callers that prefer pull.
|
|
7
|
+
*/
|
|
8
|
+
import { type McpClient } from "../core/index.js";
|
|
9
|
+
import { EventsClient, type Obj, type Occurrence } from "../ext-events/index.js";
|
|
10
|
+
export type EventsPollResult = Awaited<ReturnType<EventsClient["poll"]>>;
|
|
11
|
+
export interface EventSubscription extends AsyncIterable<Occurrence> {
|
|
12
|
+
readonly name: string;
|
|
13
|
+
/** Explicit pull; the async iterable itself is push-based. */
|
|
14
|
+
poll(): Promise<EventsPollResult>;
|
|
15
|
+
close(): Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export interface Events {
|
|
18
|
+
/** List event streams offered by the server. */
|
|
19
|
+
list(): Promise<Obj>;
|
|
20
|
+
/** Subscribe to a named event stream; iterate to receive pushed occurrences. */
|
|
21
|
+
subscribe(name: string, args?: Obj): Promise<EventSubscription>;
|
|
22
|
+
}
|
|
23
|
+
export declare class EventsFacade implements Events {
|
|
24
|
+
#private;
|
|
25
|
+
private readonly connection;
|
|
26
|
+
constructor(connection: {
|
|
27
|
+
readonly client: McpClient;
|
|
28
|
+
});
|
|
29
|
+
setCapabilities(capabilities: unknown): void;
|
|
30
|
+
list(): Promise<Obj>;
|
|
31
|
+
subscribe(name: string, args?: Obj): Promise<EventSubscription>;
|
|
32
|
+
dispose(): void;
|
|
33
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Push-first events facade over @mcp-client/ext-events.
|
|
3
|
+
*
|
|
4
|
+
* subscribe() returns an AsyncIterable of occurrences backed by the live
|
|
5
|
+
* events/stream (with heartbeat + reconnect); poll() is available explicitly
|
|
6
|
+
* for servers or callers that prefer pull.
|
|
7
|
+
*/
|
|
8
|
+
import { NotificationQueue } from "../core/index.js";
|
|
9
|
+
import { createEventsExtension, EventsClient, } from "../ext-events/index.js";
|
|
10
|
+
class EventSubscriptionImpl {
|
|
11
|
+
events;
|
|
12
|
+
id;
|
|
13
|
+
name;
|
|
14
|
+
#queue = new NotificationQueue();
|
|
15
|
+
#handle;
|
|
16
|
+
#closed = false;
|
|
17
|
+
constructor(events, id, name) {
|
|
18
|
+
this.events = events;
|
|
19
|
+
this.id = id;
|
|
20
|
+
this.name = name;
|
|
21
|
+
}
|
|
22
|
+
poll() {
|
|
23
|
+
return this.events.poll(this.id);
|
|
24
|
+
}
|
|
25
|
+
#start() {
|
|
26
|
+
if (this.#handle || this.#closed)
|
|
27
|
+
return;
|
|
28
|
+
this.#handle = this.events.push(this.id, (message) => {
|
|
29
|
+
if (message.type === "event")
|
|
30
|
+
this.#queue.push(message.event);
|
|
31
|
+
else if (message.type === "terminated" || message.type === "error")
|
|
32
|
+
this.#queue.close();
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
[Symbol.asyncIterator]() {
|
|
36
|
+
this.#start();
|
|
37
|
+
return this.#queue[Symbol.asyncIterator]();
|
|
38
|
+
}
|
|
39
|
+
async close() {
|
|
40
|
+
if (this.#closed)
|
|
41
|
+
return;
|
|
42
|
+
this.#closed = true;
|
|
43
|
+
this.#handle?.close();
|
|
44
|
+
this.events.forget(this.id);
|
|
45
|
+
this.#queue.close();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export class EventsFacade {
|
|
49
|
+
connection;
|
|
50
|
+
#events;
|
|
51
|
+
#capabilities;
|
|
52
|
+
constructor(connection) {
|
|
53
|
+
this.connection = connection;
|
|
54
|
+
}
|
|
55
|
+
setCapabilities(capabilities) {
|
|
56
|
+
this.#capabilities = capabilities;
|
|
57
|
+
}
|
|
58
|
+
async #ensure() {
|
|
59
|
+
if (this.#events)
|
|
60
|
+
return this.#events;
|
|
61
|
+
if (this.#capabilities === undefined) {
|
|
62
|
+
const discovered = await this.connection.client.discover();
|
|
63
|
+
this.#capabilities = discovered.kind === "ok" ? discovered.value.capabilities : null;
|
|
64
|
+
}
|
|
65
|
+
this.#events = new EventsClient({
|
|
66
|
+
extension: createEventsExtension({ enabled: true }),
|
|
67
|
+
peerCapabilities: () => this.#capabilities,
|
|
68
|
+
request: (method, params, opts) => this.connection.client.request(method, params, opts),
|
|
69
|
+
openStream: (method, params, opts) => this.connection.client.openStream(method, params, opts),
|
|
70
|
+
});
|
|
71
|
+
return this.#events;
|
|
72
|
+
}
|
|
73
|
+
async list() {
|
|
74
|
+
return (await this.#ensure()).list();
|
|
75
|
+
}
|
|
76
|
+
async subscribe(name, args = {}) {
|
|
77
|
+
const events = await this.#ensure();
|
|
78
|
+
return new EventSubscriptionImpl(events, events.subscription(name, args), name);
|
|
79
|
+
}
|
|
80
|
+
dispose() {
|
|
81
|
+
this.#events?.dispose();
|
|
82
|
+
this.#events = undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* High-level consumer API: connect to an MCP server and call tools without
|
|
3
|
+
* assembling McpClient/ops/transports or matching on Outcome for every call.
|
|
4
|
+
*
|
|
5
|
+
* Simple mode (this module): list()/call() return values or throw
|
|
6
|
+
* McpOutcomeError. Full mode: use `connection.ops` directly and match on
|
|
7
|
+
* Outcome kinds (mrtr-interim, task-handle, uncertain-write, ...).
|
|
8
|
+
*/
|
|
9
|
+
import { McpClient, type McpClientOptions, type ServerRef, type Transport } from "../core/index.js";
|
|
10
|
+
import { type Ops, type ToolCallOptions, type ToolCallResult, type ToolEntry } from "../ops/index.js";
|
|
11
|
+
import { type HttpTransportOptions } from "../transport-http/index.js";
|
|
12
|
+
import { type StdioTransportOptions } from "../transport-stdio/index.js";
|
|
13
|
+
import { type ListenFilter, type Subscription } from "../mrtr-cache/index.js";
|
|
14
|
+
import { type Events } from "./events.js";
|
|
15
|
+
export interface ConnectBaseOptions {
|
|
16
|
+
/** Server identity; defaults to the command or URL. */
|
|
17
|
+
readonly server?: ServerRef;
|
|
18
|
+
readonly clientInfo?: McpClientOptions["clientInfo"];
|
|
19
|
+
/** Per-request timeout; defaults to the library default. */
|
|
20
|
+
readonly timeoutMs?: number;
|
|
21
|
+
/** Probe server/discover during connect and throw on failure. Default false. */
|
|
22
|
+
readonly discover?: boolean;
|
|
23
|
+
/** Declare the events extension and expose connection.events. Default true. */
|
|
24
|
+
readonly events?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Rebuild the connection and retry once after a dropped connection
|
|
27
|
+
* (connect/closed/stream-broken/process-exit). Requires a transport factory
|
|
28
|
+
* or stdio/http options; a bare Transport instance cannot be rebuilt.
|
|
29
|
+
*/
|
|
30
|
+
readonly reconnectOnDrop?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export type ConnectOptions = ConnectBaseOptions & ({
|
|
33
|
+
readonly transport: Transport | (() => Transport);
|
|
34
|
+
} | {
|
|
35
|
+
readonly stdio: StdioTransportOptions;
|
|
36
|
+
} | {
|
|
37
|
+
readonly http: HttpTransportOptions;
|
|
38
|
+
});
|
|
39
|
+
export interface SimpleTools {
|
|
40
|
+
/** All tools, following pagination. Throws McpOutcomeError on failure. */
|
|
41
|
+
list(): Promise<ToolEntry[]>;
|
|
42
|
+
/** Call a tool. Throws McpOutcomeError on protocol/transport failure or isError. */
|
|
43
|
+
call(name: string, args?: unknown, opts?: ToolCallOptions): Promise<ToolCallResult>;
|
|
44
|
+
}
|
|
45
|
+
export interface Connection {
|
|
46
|
+
readonly client: McpClient;
|
|
47
|
+
readonly ops: Ops;
|
|
48
|
+
readonly tools: SimpleTools;
|
|
49
|
+
/** Push-based event subscriptions (events extension). */
|
|
50
|
+
readonly events: Events;
|
|
51
|
+
/** Standard MCP subscriptions/listen (list_changed, resource updates). */
|
|
52
|
+
listen(filter: ListenFilter): Subscription;
|
|
53
|
+
/** Tear down and rebuild the underlying client (new transport). */
|
|
54
|
+
reconnect(): Promise<void>;
|
|
55
|
+
close(opts?: {
|
|
56
|
+
readonly graceMs?: number;
|
|
57
|
+
}): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
/** Connect to an MCP server over stdio, streamable HTTP, or a custom transport. */
|
|
60
|
+
export declare function connect(options: ConnectOptions): Promise<Connection>;
|
|
61
|
+
export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
|
|
62
|
+
export type { ToolCallOptions, ToolCallResult, ToolEntry } from "../ops/index.js";
|
|
63
|
+
export type { Events, EventSubscription, EventsPollResult } from "./events.js";
|
|
64
|
+
export type { Occurrence } from "../ext-events/index.js";
|
|
65
|
+
export type { ListenFilter, Subscription, ChangeEvent, Acknowledgment } from "../mrtr-cache/index.js";
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* High-level consumer API: connect to an MCP server and call tools without
|
|
3
|
+
* assembling McpClient/ops/transports or matching on Outcome for every call.
|
|
4
|
+
*
|
|
5
|
+
* Simple mode (this module): list()/call() return values or throw
|
|
6
|
+
* McpOutcomeError. Full mode: use `connection.ops` directly and match on
|
|
7
|
+
* Outcome kinds (mrtr-interim, task-handle, uncertain-write, ...).
|
|
8
|
+
*/
|
|
9
|
+
import { McpClient, unwrapOutcome, } from "../core/index.js";
|
|
10
|
+
import { createOps, } from "../ops/index.js";
|
|
11
|
+
import { HttpTransport } from "../transport-http/index.js";
|
|
12
|
+
import { StdioTransport } from "../transport-stdio/index.js";
|
|
13
|
+
import { createEventsExtension } from "../ext-events/index.js";
|
|
14
|
+
import { SubscriptionManager, } from "../mrtr-cache/index.js";
|
|
15
|
+
import { EventsFacade } from "./events.js";
|
|
16
|
+
const RETRY_KINDS = new Set(["connect", "closed", "stream-broken", "process-exit"]);
|
|
17
|
+
class ConnectionImpl {
|
|
18
|
+
#current;
|
|
19
|
+
#options;
|
|
20
|
+
events;
|
|
21
|
+
#binding = "http";
|
|
22
|
+
#manager;
|
|
23
|
+
#subscriptions = new Set();
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.#options = options;
|
|
26
|
+
this.#current = this.#build();
|
|
27
|
+
this.events = new EventsFacade(this);
|
|
28
|
+
}
|
|
29
|
+
get client() {
|
|
30
|
+
return this.#current.client;
|
|
31
|
+
}
|
|
32
|
+
get ops() {
|
|
33
|
+
return this.#current.ops;
|
|
34
|
+
}
|
|
35
|
+
#transport() {
|
|
36
|
+
if ("transport" in this.#options) {
|
|
37
|
+
const t = this.#options.transport;
|
|
38
|
+
return typeof t === "function" ? t() : t;
|
|
39
|
+
}
|
|
40
|
+
if ("stdio" in this.#options)
|
|
41
|
+
return new StdioTransport(this.#options.stdio);
|
|
42
|
+
return new HttpTransport(this.#options.http);
|
|
43
|
+
}
|
|
44
|
+
listen(filter) {
|
|
45
|
+
this.#manager ??= new SubscriptionManager({
|
|
46
|
+
open: (method, params) => this.client.openStream(method, params),
|
|
47
|
+
binding: this.#binding,
|
|
48
|
+
serverRef: this.client.server.key,
|
|
49
|
+
reconnect: "on-abrupt",
|
|
50
|
+
});
|
|
51
|
+
const subscription = this.#manager.listen(filter);
|
|
52
|
+
this.#subscriptions.add(subscription);
|
|
53
|
+
return subscription;
|
|
54
|
+
}
|
|
55
|
+
#build() {
|
|
56
|
+
const transport = this.#transport();
|
|
57
|
+
this.#binding = transport.binding === "stdio" ? "stdio" : "http";
|
|
58
|
+
const server = this.#options.server ??
|
|
59
|
+
("stdio" in this.#options
|
|
60
|
+
? { key: this.#options.stdio.command }
|
|
61
|
+
: "http" in this.#options
|
|
62
|
+
? { key: this.#options.http.url }
|
|
63
|
+
: { key: "mcp" });
|
|
64
|
+
const client = new McpClient({
|
|
65
|
+
transport,
|
|
66
|
+
server,
|
|
67
|
+
...(this.#options.events === false
|
|
68
|
+
? {}
|
|
69
|
+
: { extensions: [createEventsExtension({ enabled: true })] }),
|
|
70
|
+
...(this.#options.clientInfo !== undefined ? { clientInfo: this.#options.clientInfo } : {}),
|
|
71
|
+
...(this.#options.timeoutMs !== undefined
|
|
72
|
+
? { defaults: { timeoutMs: this.#options.timeoutMs } }
|
|
73
|
+
: {}),
|
|
74
|
+
});
|
|
75
|
+
return { client, ops: createOps(client) };
|
|
76
|
+
}
|
|
77
|
+
async reconnect() {
|
|
78
|
+
const previous = this.#current;
|
|
79
|
+
this.#current = this.#build();
|
|
80
|
+
this.#manager?.reconnected();
|
|
81
|
+
try {
|
|
82
|
+
await previous.client.close({ graceMs: 500 });
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
// best-effort close of the dropped connection
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async close(opts) {
|
|
89
|
+
this.events.dispose();
|
|
90
|
+
for (const subscription of this.#subscriptions)
|
|
91
|
+
subscription.close();
|
|
92
|
+
this.#subscriptions.clear();
|
|
93
|
+
await this.#current.client.close(opts);
|
|
94
|
+
}
|
|
95
|
+
tools = {
|
|
96
|
+
list: async () => {
|
|
97
|
+
const outcome = await this.ops.tools.listAll();
|
|
98
|
+
return unwrapOutcome(outcome).items;
|
|
99
|
+
},
|
|
100
|
+
call: async (name, args, opts) => {
|
|
101
|
+
let outcome = await this.ops.tools.call(name, args, opts);
|
|
102
|
+
if (this.#options.reconnectOnDrop &&
|
|
103
|
+
outcome.kind === "transport-failure" &&
|
|
104
|
+
RETRY_KINDS.has(outcome.failure.kind) &&
|
|
105
|
+
!(opts?.signal?.aborted ?? false)) {
|
|
106
|
+
await this.reconnect();
|
|
107
|
+
outcome = await this.ops.tools.call(name, args, opts);
|
|
108
|
+
}
|
|
109
|
+
return unwrapOutcome(outcome);
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/** Connect to an MCP server over stdio, streamable HTTP, or a custom transport. */
|
|
114
|
+
export async function connect(options) {
|
|
115
|
+
const connection = new ConnectionImpl(options);
|
|
116
|
+
if (options.discover) {
|
|
117
|
+
try {
|
|
118
|
+
const discovered = unwrapOutcome(await connection.client.discover());
|
|
119
|
+
connection.events.setCapabilities(discovered.capabilities);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
await connection.close().catch(() => { });
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return connection;
|
|
127
|
+
}
|
|
128
|
+
export { McpOutcomeError, unwrapOutcome } from "../core/index.js";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { ConsentPort } from "./ports.js";
|
|
2
|
+
export interface AuthRequestContext {
|
|
3
|
+
readonly signal: AbortSignal;
|
|
4
|
+
readonly consent?: ConsentPort;
|
|
5
|
+
readonly serverLabel?: string;
|
|
6
|
+
}
|
|
7
|
+
/** A provider's structured, non-secret failure; never include peer or credential text in reason. */
|
|
8
|
+
export declare class AuthError extends Error {
|
|
9
|
+
readonly kind: "auth-failure" | "auth-unavailable";
|
|
10
|
+
readonly reason: string;
|
|
11
|
+
constructor(kind: "auth-failure" | "auth-unavailable", reason: string);
|
|
12
|
+
}
|
|
13
|
+
export interface AuthHeaderResult {
|
|
14
|
+
readonly authorization: string;
|
|
15
|
+
readonly contextId: string;
|
|
16
|
+
/** Opaque identity of the credential used on the wire, unrelated to the cache partition. */
|
|
17
|
+
readonly credentialVersion?: object;
|
|
18
|
+
}
|
|
19
|
+
export interface AuthChallenge {
|
|
20
|
+
readonly status: 401 | 403;
|
|
21
|
+
readonly wwwAuthenticate?: string;
|
|
22
|
+
readonly resource?: string;
|
|
23
|
+
readonly operation?: string;
|
|
24
|
+
/** Null means no Authorization header was sent; undefined means no version was reported. */
|
|
25
|
+
readonly credentialVersion?: object | null;
|
|
26
|
+
}
|
|
27
|
+
export interface AuthProvider {
|
|
28
|
+
/** Stable identifier for the current grant/credential context (never raw token). */
|
|
29
|
+
contextId(): string;
|
|
30
|
+
/** Produce bearer header for a request without leaking raw token outside headers. */
|
|
31
|
+
headerFor(url: string, operation?: string, context?: AuthRequestContext): Promise<AuthHeaderResult | undefined>;
|
|
32
|
+
/** Maximum 403 replays in one exchange. Defaults to three. */
|
|
33
|
+
readonly stepUpLimit?: number;
|
|
34
|
+
/** Handle 401/403 challenge; returns true if credentials refreshed/stepped up and retry is warranted. */
|
|
35
|
+
onChallenge?(challenge: AuthChallenge, signal: AbortSignal, context?: AuthRequestContext): Promise<boolean>;
|
|
36
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** A provider's structured, non-secret failure; never include peer or credential text in reason. */
|
|
2
|
+
export class AuthError extends Error {
|
|
3
|
+
kind;
|
|
4
|
+
reason;
|
|
5
|
+
constructor(kind, reason) {
|
|
6
|
+
super(`${kind}/${reason}`);
|
|
7
|
+
this.kind = kind;
|
|
8
|
+
this.reason = reason;
|
|
9
|
+
this.name = "AuthError";
|
|
10
|
+
}
|
|
11
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export type BearerChallenge = Readonly<Partial<Record<'resource_metadata' | 'scope' | 'error' | 'error_description' | 'error_uri', string>>>;
|
|
2
|
+
/** Parse each field independently; a malformed field cannot supply a partial challenge. */
|
|
3
|
+
export declare function parseBearerChallenges(input: string | readonly string[]): BearerChallenge[];
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
const token = "[!#$%&'*+.^_`|~0-9A-Za-z-]+";
|
|
2
|
+
const quotedString = String.raw `"(?:[^"\\\x00-\x1f\x7f]|\\[\x20-\x7e])*"`;
|
|
3
|
+
const param = new RegExp(`^(${token})[ \\t]*=[ \\t]*(${token}|${quotedString})$`, 'u');
|
|
4
|
+
const scheme = new RegExp(`^(${token})(?:[ \\t]+(.+))?$`, 'u');
|
|
5
|
+
/** Parse each field independently; a malformed field cannot supply a partial challenge. */
|
|
6
|
+
export function parseBearerChallenges(input) {
|
|
7
|
+
return (typeof input === 'string' ? [input] : input).flatMap((line) => {
|
|
8
|
+
const pieces = [];
|
|
9
|
+
let quote = false, escape = false, start = 0;
|
|
10
|
+
for (let i = 0; i < line.length; i++) {
|
|
11
|
+
const ch = line[i];
|
|
12
|
+
if (escape) {
|
|
13
|
+
escape = false;
|
|
14
|
+
continue;
|
|
15
|
+
}
|
|
16
|
+
if (quote && ch === '\\')
|
|
17
|
+
escape = true;
|
|
18
|
+
else if (ch === '"')
|
|
19
|
+
quote = !quote;
|
|
20
|
+
else if (!quote && ch === ',') {
|
|
21
|
+
pieces.push(line.slice(start, i));
|
|
22
|
+
start = i + 1;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
if (quote)
|
|
26
|
+
return [];
|
|
27
|
+
pieces.push(line.slice(start));
|
|
28
|
+
const result = [];
|
|
29
|
+
let entry, bearer = false, acceptsParams = false;
|
|
30
|
+
for (const raw of pieces) {
|
|
31
|
+
const piece = raw.trim();
|
|
32
|
+
if (!piece)
|
|
33
|
+
continue;
|
|
34
|
+
let match = param.exec(piece);
|
|
35
|
+
if (!match) {
|
|
36
|
+
const next = scheme.exec(piece);
|
|
37
|
+
if (!next)
|
|
38
|
+
return [];
|
|
39
|
+
entry = Object.create(null);
|
|
40
|
+
bearer = next[1]?.toLowerCase() === 'bearer';
|
|
41
|
+
if (bearer)
|
|
42
|
+
result.push(entry);
|
|
43
|
+
acceptsParams = false;
|
|
44
|
+
if (next[2] === undefined)
|
|
45
|
+
continue;
|
|
46
|
+
match = param.exec(next[2]);
|
|
47
|
+
if (!match) {
|
|
48
|
+
if (!bearer && /^[a-z\d._~+/=-]+$/iu.test(next[2]))
|
|
49
|
+
continue;
|
|
50
|
+
return [];
|
|
51
|
+
}
|
|
52
|
+
acceptsParams = true;
|
|
53
|
+
}
|
|
54
|
+
if (!entry || !acceptsParams)
|
|
55
|
+
return [];
|
|
56
|
+
const key = match[1].toLowerCase(), value = match[2];
|
|
57
|
+
if (Object.hasOwn(entry, key))
|
|
58
|
+
return [];
|
|
59
|
+
entry[key] = value.startsWith('"') ? value.slice(1, -1).replace(/\\(.)/gu, '$1') : value;
|
|
60
|
+
}
|
|
61
|
+
return result.map(({ resource_metadata, scope, error, error_description, error_uri }) => Object.fromEntries(Object.entries({ resource_metadata, scope, error, error_description, error_uri }).filter(([, v]) => v !== undefined)));
|
|
62
|
+
});
|
|
63
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { TransportFailure, UncertainWrite } from "./outcome.js";
|
|
2
|
+
import type { Exchange, ExchangeEnd } from "./ports.js";
|
|
3
|
+
import type { RequestId } from "./jsonrpc.js";
|
|
4
|
+
/**
|
|
5
|
+
* Cancellation and timeout semantics (S1.1, IMPLEMENTATION_PLAN.md §5.4; WIRE-CANCEL-*, WIRE-TO-*).
|
|
6
|
+
*
|
|
7
|
+
* Core does not write notifications/cancelled itself: that is binding behavior (stdio sends it,
|
|
8
|
+
* Streamable HTTP closes the stream). Core guarantees that an abort settles the request locally
|
|
9
|
+
* even when the transport does not react, that a response observed after the local settle is
|
|
10
|
+
* ignored and counted (WIRE-CANCEL-3), that a cancel after settle is a no-op (WIRE-CANCEL-1),
|
|
11
|
+
* and that interrupted non-read-only calls classify as uncertain-write (WIRE-CANCEL-5, N14).
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Methods treated as read-only by default. A read-only call that is cancelled or times out is a
|
|
15
|
+
* clean `cancelled` / `transport-failure`; anything else is `uncertain-write`.
|
|
16
|
+
* prompts/get is listed as a host-overridable default only (STDIO-RECOVER-1); the spec does not
|
|
17
|
+
* declare it idempotent.
|
|
18
|
+
*/
|
|
19
|
+
export declare const DEFAULT_READ_ONLY_METHODS: readonly string[];
|
|
20
|
+
export declare function createReadOnlyPredicate(methods?: readonly string[]): (method: string) => boolean;
|
|
21
|
+
export declare const isReadOnlyMethod: (method: string) => boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Races `work` against `signal`; rejects on abort with `onAbort()` (or `signal.reason` if omitted).
|
|
24
|
+
*/
|
|
25
|
+
export declare function withAbort<T>(work: PromiseLike<T>, signal: AbortSignal, onAbort?: () => unknown): Promise<T>;
|
|
26
|
+
/** Stable, non-cryptographic digest of call arguments for UncertainWrite records (no secrets stored). */
|
|
27
|
+
export declare function argsDigest(obj: unknown): string;
|
|
28
|
+
export type InterruptCause = "cancelled" | "timeout" | "failure";
|
|
29
|
+
export interface InterruptedCall {
|
|
30
|
+
readonly method: string;
|
|
31
|
+
readonly readOnly: boolean;
|
|
32
|
+
readonly cause: InterruptCause;
|
|
33
|
+
readonly delivery: "not-sent" | "maybe-delivered" | "delivered-no-response";
|
|
34
|
+
readonly failure?: TransportFailure;
|
|
35
|
+
}
|
|
36
|
+
export type InterruptClass = "cancelled" | "uncertain-write" | "transport-failure";
|
|
37
|
+
/**
|
|
38
|
+
* Classification hook for an interrupted call (no response observed).
|
|
39
|
+
* - never sent: `cancelled` (abort/timeout) or `transport-failure` (safe to retry)
|
|
40
|
+
* - sent, read-only: `cancelled` or `transport-failure`
|
|
41
|
+
* - sent, not read-only: `uncertain-write`
|
|
42
|
+
*/
|
|
43
|
+
export declare function classifyInterruptedCall(call: InterruptedCall): InterruptClass;
|
|
44
|
+
export declare function uncertainEvidence(call: InterruptedCall): UncertainWrite["evidence"];
|
|
45
|
+
export declare function buildUncertainWrite(input: {
|
|
46
|
+
readonly requestId: RequestId;
|
|
47
|
+
readonly method: string;
|
|
48
|
+
readonly params: Record<string, unknown>;
|
|
49
|
+
readonly sentAt: number;
|
|
50
|
+
readonly binding: string;
|
|
51
|
+
readonly evidence: UncertainWrite["evidence"];
|
|
52
|
+
}): UncertainWrite;
|
|
53
|
+
export interface GuardHooks {
|
|
54
|
+
/** Called once when the exchange settles (by response, transport failure, or local abort). */
|
|
55
|
+
onSettle?(end: ExchangeEnd, source: "transport" | "abort"): void;
|
|
56
|
+
/** Called when the transport settles after the local settle already happened (WIRE-CANCEL-3). */
|
|
57
|
+
onLate?(end: ExchangeEnd): void;
|
|
58
|
+
}
|
|
59
|
+
export interface GuardedDone {
|
|
60
|
+
readonly done: Promise<ExchangeEnd>;
|
|
61
|
+
readonly settled: () => boolean;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Wraps an exchange's completion so that exactly one end is observed.
|
|
65
|
+
* When `settleOnAbort` is set, an abort settles locally with a `maybe-delivered` failure if the
|
|
66
|
+
* transport has not settled by itself within a few microtask turns.
|
|
67
|
+
*/
|
|
68
|
+
export declare function guardExchangeDone(inner: Exchange, signal: AbortSignal, opts: {
|
|
69
|
+
readonly settleOnAbort: boolean;
|
|
70
|
+
}, hooks?: GuardHooks): GuardedDone;
|