agents 0.33.0 → 0.34.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/README.md +1 -1
- package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
- package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
- package/dist/browser/ai.js +1 -1
- package/dist/browser/index.d.ts +7 -3
- package/dist/browser/index.js +2 -2
- package/dist/browser/tools/ai-sdk.d.ts +68 -3
- package/dist/browser/tools/pi.d.ts +2 -2
- package/dist/browser/tools/tanstack-ai.d.ts +2 -2
- package/dist/{browser-CI97khiJ.d.ts → browser-C9T74n4c.d.ts} +84 -5
- package/dist/{browser-tool-Cxtiwfua.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
- package/dist/capability-DBAKc6UZ.js.map +1 -1
- package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
- package/dist/chat/index.d.ts +37 -6
- package/dist/chat/index.js +39 -3
- package/dist/chat/index.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +3 -3
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +64 -63
- package/dist/client-CkT8voRY.js +3740 -0
- package/dist/client-CkT8voRY.js.map +1 -0
- package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
- package/dist/client.d.ts +1 -1
- package/dist/{connector-Dl098To-.js → connector-Bphz6wIw.js} +16 -4
- package/dist/connector-Bphz6wIw.js.map +1 -0
- package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
- package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
- package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
- package/dist/experimental/channels/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.d.ts +2 -2
- package/dist/experimental/channels/web/index.js +1 -1
- package/dist/experimental/webmcp.js +1 -1
- package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
- package/dist/harness/ai-sdk/index.d.ts +2 -2
- package/dist/harness/container/index.d.ts +2 -2
- package/dist/harness/container/index.js +1 -1
- package/dist/harness/container/index.js.map +1 -1
- package/dist/harness/opencode/index.d.ts +1 -1
- package/dist/harness/pi/index.d.ts +128 -12
- package/dist/harness/pi/index.js +128 -20
- package/dist/harness/pi/index.js.map +1 -1
- package/dist/harness/think/index.d.ts +2 -2
- package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
- package/dist/images-D4gtE06D.js.map +1 -0
- package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
- package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
- package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
- package/dist/index.d.ts +21 -21
- package/dist/index.js +2 -2
- package/dist/{input-schema-0uUu392-.js → input-schema-D6GilRXI.js} +2 -2
- package/dist/{input-schema-0uUu392-.js.map → input-schema-D6GilRXI.js.map} +1 -1
- package/dist/{input-schema-waggtYrH.js → input-schema-y8W5bOdM.js} +2 -2
- package/dist/{input-schema-waggtYrH.js.map → input-schema-y8W5bOdM.js.map} +1 -1
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +1 -1
- package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
- package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +45 -2
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +42 -36
- package/dist/mcp/client/index.js +2 -2
- package/dist/mcp/client/x402.d.ts +8 -8
- package/dist/mcp/index.d.ts +17 -17
- package/dist/mcp/index.js +5 -5
- package/dist/mcp/index.js.map +1 -1
- package/dist/models/ai-sdk/index.d.ts +9 -5
- package/dist/models/ai-sdk/index.js +1 -1
- package/dist/models/opencode/index.d.ts +3 -3
- package/dist/models/opencode/index.js +2 -2
- package/dist/models/opencode/index.js.map +1 -1
- package/dist/models/pi-ai/index.d.ts +4 -4
- package/dist/models/pi-ai/index.js +53 -29
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
- package/dist/queue/index.d.ts +1 -1
- package/dist/queue/index.js +1 -1
- package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
- package/dist/queue-B_wl6K0Z.js.map +1 -0
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
- package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
- package/dist/scheduler-DGNEmxQR.js.map +1 -0
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/session-CRY0bGiI.js.map +1 -1
- package/dist/sessions/index.d.ts +1 -1
- package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
- package/dist/settings-D2F_qONv.js.map +1 -0
- package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
- package/dist/src-BO1FdLK1.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
- package/dist/sub-routing.d.ts +12 -12
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
- package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
- package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
- package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
- package/dist/tool-CmAGY6Fo.js.map +1 -0
- package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
- package/dist/tool-Kxcj8_22.js.map +1 -0
- package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
- package/dist/voice/index.d.ts +2 -2
- package/dist/web/fetch/index.js +1 -1
- package/dist/web/fetch/tools/ai-sdk.js +2 -2
- package/dist/web/fetch/tools/pi.d.ts +5 -0
- package/dist/web/fetch/tools/pi.js +25 -2
- package/dist/web/fetch/tools/pi.js.map +1 -1
- package/dist/web/fetch/tools/tanstack-ai.js +2 -2
- package/dist/web/search/index.js +1 -1
- package/dist/web/search/tools/ai-sdk.js +2 -2
- package/dist/web/search/tools/pi.d.ts +4 -0
- package/dist/web/search/tools/pi.js +23 -2
- package/dist/web/search/tools/pi.js.map +1 -1
- package/dist/web/search/tools/tanstack-ai.js +2 -2
- package/dist/websockets/index.d.ts +2 -2
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
- package/dist/websockets-W4uhRg4-.js.map +1 -0
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/docs/agent-class.md +30 -4
- package/docs/browse-the-web.md +14 -0
- package/docs/chat-agents.md +13 -10
- package/docs/client-tools-continuation.md +1 -1
- package/docs/codemode.md +1 -1
- package/docs/configuration.md +6 -3
- package/docs/cross-domain-authentication.md +1 -1
- package/docs/fetch-the-web.md +20 -0
- package/docs/harnesses/pi.md +211 -22
- package/docs/harnesses/think.md +1 -1
- package/docs/http-websockets.md +40 -32
- package/docs/human-in-the-loop.md +2 -2
- package/docs/lifecycle.md +56 -0
- package/docs/mcp-client.md +104 -7
- package/docs/models-pi-ai.md +24 -10
- package/docs/models.md +42 -17
- package/docs/resumable-streaming.md +1 -1
- package/docs/retries.md +3 -6
- package/docs/search-the-web.md +10 -0
- package/docs/voice.md +1 -1
- package/package.json +13 -12
- package/dist/ai-sdk-CpuRsjP5.d.ts +0 -72
- package/dist/ai-sdk-Kon40i0q.js.map +0 -1
- package/dist/client-DMWujQJ1.js +0 -2325
- package/dist/client-DMWujQJ1.js.map +0 -1
- package/dist/connector-Dl098To-.js.map +0 -1
- package/dist/images-CfuRCjwq.js.map +0 -1
- package/dist/lifecycle-v1rKHV2C.js.map +0 -1
- package/dist/queue-CcIjVYTE.js.map +0 -1
- package/dist/scheduler-FIHv2-kJ.js.map +0 -1
- package/dist/settings-Dk2il2Hf.js.map +0 -1
- package/dist/src-DoGNJ4Ud.js.map +0 -1
- package/dist/tool-CxKsvxjm.js.map +0 -1
- package/dist/tool-DkT_DJBm.js.map +0 -1
- package/dist/websockets-C6SJtWCJ.js.map +0 -1
|
@@ -0,0 +1,3740 @@
|
|
|
1
|
+
import { getAgentByName } from "./agent-routing.js";
|
|
2
|
+
import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
|
|
3
|
+
import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
|
|
4
|
+
import { t as LifecycleCapability } from "./capability-DBAKc6UZ.js";
|
|
5
|
+
import { tryN } from "./retries.js";
|
|
6
|
+
import { DurableObjectOAuthClientProvider } from "./mcp/client/do-oauth-client-provider.js";
|
|
7
|
+
import { t as callV2Tool } from "./invoker-BC1SZ3q1.js";
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
import { nanoid } from "nanoid";
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
import { Client, OAuthError, RegistrationRejectedError, SSEClientTransport, SdkHttpError, StreamableHTTPClientTransport, UnauthorizedError } from "@modelcontextprotocol/client";
|
|
12
|
+
import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/client/validators/cf-worker";
|
|
13
|
+
//#region src/core/events.ts
|
|
14
|
+
function toDisposable(fn) {
|
|
15
|
+
return { dispose: fn };
|
|
16
|
+
}
|
|
17
|
+
var DisposableStore = class {
|
|
18
|
+
constructor() {
|
|
19
|
+
this._items = [];
|
|
20
|
+
}
|
|
21
|
+
add(d) {
|
|
22
|
+
this._items.push(d);
|
|
23
|
+
return d;
|
|
24
|
+
}
|
|
25
|
+
dispose() {
|
|
26
|
+
while (this._items.length) try {
|
|
27
|
+
this._items.pop().dispose();
|
|
28
|
+
} catch {}
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
var Emitter = class {
|
|
32
|
+
constructor() {
|
|
33
|
+
this._listeners = /* @__PURE__ */ new Set();
|
|
34
|
+
this.event = (listener) => {
|
|
35
|
+
this._listeners.add(listener);
|
|
36
|
+
return toDisposable(() => this._listeners.delete(listener));
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
fire(data) {
|
|
40
|
+
for (const listener of [...this._listeners]) try {
|
|
41
|
+
listener(data);
|
|
42
|
+
} catch (err) {
|
|
43
|
+
console.error("Emitter listener error:", err);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
dispose() {
|
|
47
|
+
this._listeners.clear();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/mcp/abort.ts
|
|
52
|
+
function abortError(signal) {
|
|
53
|
+
return signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason ?? "Aborted"));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Stop awaiting an operation when its owner aborts. The underlying operation
|
|
57
|
+
* remains responsible for observing the same signal and cancelling its work.
|
|
58
|
+
*/
|
|
59
|
+
async function raceWithSignal(promise, signal) {
|
|
60
|
+
if (!signal) return promise;
|
|
61
|
+
if (signal.aborted) throw abortError(signal);
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
const onAbort = () => reject(abortError(signal));
|
|
64
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
65
|
+
promise.then(resolve, reject).finally(() => {
|
|
66
|
+
signal.removeEventListener("abort", onAbort);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region src/mcp/rpc.ts
|
|
72
|
+
const RPC_DO_PREFIX = "rpc:";
|
|
73
|
+
/** Narrow an unknown runtime binding to an MCP Durable Object namespace. */
|
|
74
|
+
function isDurableObjectNamespace(namespace) {
|
|
75
|
+
return typeof namespace === "object" && namespace !== null && "newUniqueId" in namespace && typeof namespace.newUniqueId === "function" && "idFromName" in namespace && typeof namespace.idFromName === "function";
|
|
76
|
+
}
|
|
77
|
+
var RPCClientTransport = class {
|
|
78
|
+
constructor(options) {
|
|
79
|
+
this._started = false;
|
|
80
|
+
this._namespace = options.namespace;
|
|
81
|
+
this._name = options.name;
|
|
82
|
+
this._props = options.props;
|
|
83
|
+
}
|
|
84
|
+
setProtocolVersion(version) {
|
|
85
|
+
this._protocolVersion = version;
|
|
86
|
+
}
|
|
87
|
+
getProtocolVersion() {
|
|
88
|
+
return this._protocolVersion;
|
|
89
|
+
}
|
|
90
|
+
async start() {
|
|
91
|
+
if (this._started) throw new Error("Transport already started");
|
|
92
|
+
const doName = `${RPC_DO_PREFIX}${this._name}`;
|
|
93
|
+
this._stub = await getAgentByName(this._namespace, doName, { props: this._props });
|
|
94
|
+
this._started = true;
|
|
95
|
+
}
|
|
96
|
+
async close() {
|
|
97
|
+
this._started = false;
|
|
98
|
+
this._stub = void 0;
|
|
99
|
+
this.onclose?.();
|
|
100
|
+
}
|
|
101
|
+
async send(message, options) {
|
|
102
|
+
if (!this._started || !this._stub) throw new Error("Transport not started");
|
|
103
|
+
try {
|
|
104
|
+
const result = await raceWithSignal(this._stub.handleMcpMessage(message), options?.requestSignal);
|
|
105
|
+
if (!result || options?.requestSignal?.aborted) return;
|
|
106
|
+
const extra = void 0;
|
|
107
|
+
const messages = Array.isArray(result) ? result : [result];
|
|
108
|
+
for (const msg of messages) this.onmessage?.(msg, extra);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
this.onerror?.(error);
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/mcp/client/catalog.ts
|
|
117
|
+
async function fetchMcpTools(client, options) {
|
|
118
|
+
let aggregate = [];
|
|
119
|
+
let page = { tools: [] };
|
|
120
|
+
do {
|
|
121
|
+
const params = { cursor: page.nextCursor };
|
|
122
|
+
page = await (options.probing ? client.request({
|
|
123
|
+
method: "tools/list",
|
|
124
|
+
params
|
|
125
|
+
}) : client.listTools(params)).catch(options.onCapabilityError({ tools: [] }, "tools/list"));
|
|
126
|
+
aggregate = aggregate.concat(page.tools);
|
|
127
|
+
} while (page.nextCursor);
|
|
128
|
+
return aggregate;
|
|
129
|
+
}
|
|
130
|
+
async function fetchMcpResources(client, options) {
|
|
131
|
+
let aggregate = [];
|
|
132
|
+
let page = { resources: [] };
|
|
133
|
+
do {
|
|
134
|
+
const params = { cursor: page.nextCursor };
|
|
135
|
+
page = await (options.probing ? client.request({
|
|
136
|
+
method: "resources/list",
|
|
137
|
+
params
|
|
138
|
+
}) : client.listResources(params)).catch(options.onCapabilityError({ resources: [] }, "resources/list"));
|
|
139
|
+
aggregate = aggregate.concat(page.resources);
|
|
140
|
+
} while (page.nextCursor);
|
|
141
|
+
return aggregate;
|
|
142
|
+
}
|
|
143
|
+
async function fetchMcpPrompts(client, options) {
|
|
144
|
+
let aggregate = [];
|
|
145
|
+
let page = { prompts: [] };
|
|
146
|
+
do {
|
|
147
|
+
const params = { cursor: page.nextCursor };
|
|
148
|
+
page = await (options.probing ? client.request({
|
|
149
|
+
method: "prompts/list",
|
|
150
|
+
params
|
|
151
|
+
}) : client.listPrompts(params)).catch(options.onCapabilityError({ prompts: [] }, "prompts/list"));
|
|
152
|
+
aggregate = aggregate.concat(page.prompts);
|
|
153
|
+
} while (page.nextCursor);
|
|
154
|
+
return aggregate;
|
|
155
|
+
}
|
|
156
|
+
async function fetchMcpResourceTemplates(client, options) {
|
|
157
|
+
let aggregate = [];
|
|
158
|
+
let page = { resourceTemplates: [] };
|
|
159
|
+
do {
|
|
160
|
+
const params = { cursor: page.nextCursor };
|
|
161
|
+
page = await (options.probing ? client.request({
|
|
162
|
+
method: "resources/templates/list",
|
|
163
|
+
params
|
|
164
|
+
}) : client.listResourceTemplates(params)).catch(options.onCapabilityError({ resourceTemplates: [] }, "resources/templates/list"));
|
|
165
|
+
aggregate = aggregate.concat(page.resourceTemplates);
|
|
166
|
+
} while (page.nextCursor);
|
|
167
|
+
return aggregate;
|
|
168
|
+
}
|
|
169
|
+
/** One catalog of every given connection, each entry tagged with its server. */
|
|
170
|
+
function getNamespacedData(mcpClients, type) {
|
|
171
|
+
return Object.entries(mcpClients).flatMap(([serverId, conn]) => conn[type].map((item) => ({
|
|
172
|
+
...item,
|
|
173
|
+
serverId
|
|
174
|
+
})));
|
|
175
|
+
}
|
|
176
|
+
/** The connections a filter selects; every criterion must match. */
|
|
177
|
+
function filterConnections(connections, servers, filter) {
|
|
178
|
+
if (!filter) return connections;
|
|
179
|
+
const serverIds = asList(filter.serverId);
|
|
180
|
+
const serverNames = asList(filter.serverName);
|
|
181
|
+
const states = asList(filter.state);
|
|
182
|
+
const namedIds = serverNames ? new Set(servers().filter((server) => serverNames.includes(server.name)).map((server) => server.id)) : void 0;
|
|
183
|
+
return Object.fromEntries(Object.entries(connections).filter(([id, conn]) => (!serverIds || serverIds.includes(id)) && (!namedIds || namedIds.has(id)) && (!states || states.includes(conn.connectionState))));
|
|
184
|
+
}
|
|
185
|
+
function asList(value) {
|
|
186
|
+
if (!value) return void 0;
|
|
187
|
+
return Array.isArray(value) ? value : [value];
|
|
188
|
+
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/mcp/client/authorization-turns.ts
|
|
191
|
+
var _tail = /* @__PURE__ */ new WeakMap();
|
|
192
|
+
var _sentTokens = /* @__PURE__ */ new WeakMap();
|
|
193
|
+
var _warnedUnwrapped = /* @__PURE__ */ new WeakMap();
|
|
194
|
+
/**
|
|
195
|
+
* One OAuth flow at a time per connection.
|
|
196
|
+
*
|
|
197
|
+
* The SDK transport answers every `401` by calling its auth provider's
|
|
198
|
+
* `onUnauthorized`, which refreshes the token or registers a client and builds
|
|
199
|
+
* an authorization URL with a fresh state and code verifier. When several
|
|
200
|
+
* requests get a `401` together (catalog discovery lists tools, prompts and
|
|
201
|
+
* resources in parallel, alongside the listen stream), those flows interleave
|
|
202
|
+
* on one provider: each registers its own client, and the link the manager
|
|
203
|
+
* saves can belong to a different client than the verifier stored for it, so
|
|
204
|
+
* the link can never complete. Two refreshes racing on a rotating refresh
|
|
205
|
+
* token lose the same way.
|
|
206
|
+
*
|
|
207
|
+
* Requests still go out together. Each `401`'s authorization waits until the
|
|
208
|
+
* one before it has finished, whether it succeeded, built a link or failed,
|
|
209
|
+
* so it reuses the client and tokens the previous flow saved. When that flow
|
|
210
|
+
* already saved a newer access token, there is nothing left to authorize:
|
|
211
|
+
* the SDK retries the request with the new token.
|
|
212
|
+
*/
|
|
213
|
+
var AuthorizationTurns = class {
|
|
214
|
+
constructor() {
|
|
215
|
+
_classPrivateFieldInitSpec(this, _tail, Promise.resolve());
|
|
216
|
+
_classPrivateFieldInitSpec(this, _sentTokens, /* @__PURE__ */ new WeakMap());
|
|
217
|
+
_classPrivateFieldInitSpec(this, _warnedUnwrapped, false);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* A `fetch` for the transport that remembers which access token a request
|
|
221
|
+
* carried when it got a 401, so its authorization can tell whether a
|
|
222
|
+
* newer token already exists.
|
|
223
|
+
*/
|
|
224
|
+
wrapFetch(base) {
|
|
225
|
+
return async (input, init) => {
|
|
226
|
+
const response = await (base ?? fetch)(input, init);
|
|
227
|
+
if (response.status === 401) _classPrivateFieldGet2(_sentTokens, this).set(response, bearerToken(init?.headers));
|
|
228
|
+
return response;
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Take a transport's 401 handling in turns. The SDK keeps the adapted
|
|
233
|
+
* provider on the transport as `_authProvider`; when a later SDK moves it,
|
|
234
|
+
* this does nothing, and the integration tests that send concurrent 401s
|
|
235
|
+
* fail.
|
|
236
|
+
*/
|
|
237
|
+
wrapTransport(transport, provider) {
|
|
238
|
+
const adapted = transport._authProvider;
|
|
239
|
+
const onUnauthorized = adapted?.onUnauthorized?.bind(adapted);
|
|
240
|
+
if (!adapted || !onUnauthorized) {
|
|
241
|
+
if (!_classPrivateFieldGet2(_warnedUnwrapped, this)) {
|
|
242
|
+
_classPrivateFieldSet2(_warnedUnwrapped, this, true);
|
|
243
|
+
console.warn("[MCPClientManager] The MCP SDK transport no longer exposes its auth provider; concurrent 401s will not share one OAuth flow.");
|
|
244
|
+
}
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
adapted.onUnauthorized = async (context) => {
|
|
248
|
+
const response = responseOf(context);
|
|
249
|
+
const tokenSent = response && _classPrivateFieldGet2(_sentTokens, this).has(response) ? _classPrivateFieldGet2(_sentTokens, this).get(response) : await accessToken(provider);
|
|
250
|
+
await this.run(async () => {
|
|
251
|
+
const tokenNow = await accessToken(provider);
|
|
252
|
+
if (tokenNow && tokenNow !== tokenSent) return;
|
|
253
|
+
await onUnauthorized(context);
|
|
254
|
+
});
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Run `flow` once every flow started before it has finished, and hold
|
|
259
|
+
* later flows until it has. A callback's code exchange runs here too, so
|
|
260
|
+
* a refresh that started before it cannot save its older grant over the
|
|
261
|
+
* one the exchange saves.
|
|
262
|
+
*/
|
|
263
|
+
run(flow) {
|
|
264
|
+
const result = _classPrivateFieldGet2(_tail, this).then(flow);
|
|
265
|
+
_classPrivateFieldSet2(_tail, this, result.then(() => {}, () => {}));
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
async function accessToken(provider) {
|
|
270
|
+
try {
|
|
271
|
+
return (await provider.tokens())?.access_token;
|
|
272
|
+
} catch {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function bearerToken(headers) {
|
|
277
|
+
const value = new Headers(headers).get("authorization");
|
|
278
|
+
return value?.startsWith("Bearer ") ? value.slice(7) : void 0;
|
|
279
|
+
}
|
|
280
|
+
function responseOf(context) {
|
|
281
|
+
if (typeof context !== "object" || context === null) return void 0;
|
|
282
|
+
const { response } = context;
|
|
283
|
+
return response instanceof Response ? response : void 0;
|
|
284
|
+
}
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region src/mcp/client/runtime.ts
|
|
287
|
+
var CompatibleWorkerJsonSchemaValidator = class extends CfWorkerJsonSchemaValidator {
|
|
288
|
+
constructor(..._args) {
|
|
289
|
+
super(..._args);
|
|
290
|
+
this.legacy = new CfWorkerJsonSchemaValidator({ draft: "7" });
|
|
291
|
+
}
|
|
292
|
+
getValidator(schema) {
|
|
293
|
+
const dialect = schema.$schema;
|
|
294
|
+
return typeof dialect === "string" && /draft-0?7/i.test(dialect) ? this.legacy.getValidator(schema) : super.getValidator(schema);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
const DEFAULT_CLIENT_OPTIONS = {
|
|
298
|
+
jsonSchemaValidator: new CompatibleWorkerJsonSchemaValidator(),
|
|
299
|
+
versionNegotiation: { mode: "auto" },
|
|
300
|
+
inputRequired: { autoFulfill: true }
|
|
301
|
+
};
|
|
302
|
+
function normalizeMcpClientOptions(options) {
|
|
303
|
+
return {
|
|
304
|
+
...DEFAULT_CLIENT_OPTIONS,
|
|
305
|
+
...options,
|
|
306
|
+
versionNegotiation: {
|
|
307
|
+
...DEFAULT_CLIENT_OPTIONS.versionNegotiation,
|
|
308
|
+
...options?.versionNegotiation
|
|
309
|
+
},
|
|
310
|
+
inputRequired: {
|
|
311
|
+
...DEFAULT_CLIENT_OPTIONS.inputRequired,
|
|
312
|
+
...options?.inputRequired
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
function elicitationCapabilitiesFromHandlers(handlers) {
|
|
317
|
+
if (!handlers) return void 0;
|
|
318
|
+
const elicitation = {};
|
|
319
|
+
if (handlers.form) elicitation.form = {};
|
|
320
|
+
if (handlers.url) elicitation.url = {};
|
|
321
|
+
return elicitation.form || elicitation.url ? elicitation : void 0;
|
|
322
|
+
}
|
|
323
|
+
function listChangedHandlers(configured, callbacks) {
|
|
324
|
+
return {
|
|
325
|
+
tools: {
|
|
326
|
+
...configured?.tools,
|
|
327
|
+
onChanged: (error, tools) => {
|
|
328
|
+
callbacks.tools(error, tools);
|
|
329
|
+
configured?.tools?.onChanged(error, tools);
|
|
330
|
+
}
|
|
331
|
+
},
|
|
332
|
+
prompts: {
|
|
333
|
+
...configured?.prompts,
|
|
334
|
+
onChanged: (error, prompts) => {
|
|
335
|
+
callbacks.prompts(error, prompts);
|
|
336
|
+
configured?.prompts?.onChanged(error, prompts);
|
|
337
|
+
}
|
|
338
|
+
},
|
|
339
|
+
resources: {
|
|
340
|
+
...configured?.resources,
|
|
341
|
+
onChanged: (error, resources) => {
|
|
342
|
+
callbacks.resources(error, resources);
|
|
343
|
+
configured?.resources?.onChanged(error, resources);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* The elicitation capability a client built now would advertise: explicit
|
|
350
|
+
* client capabilities, else the handlers' modes, else the restore seed.
|
|
351
|
+
*/
|
|
352
|
+
function advertisedElicitation(options, capabilitySeed, handlerModes) {
|
|
353
|
+
return options.capabilities?.elicitation ?? elicitationCapabilitiesFromHandlers(handlerModes) ?? capabilitySeed?.elicitation;
|
|
354
|
+
}
|
|
355
|
+
function createMcpSdkClient(info, options, capabilitySeed, handlerModes, callbacks) {
|
|
356
|
+
const elicitation = advertisedElicitation(options, capabilitySeed, handlerModes);
|
|
357
|
+
return {
|
|
358
|
+
client: new Client(info, {
|
|
359
|
+
...options,
|
|
360
|
+
capabilities: {
|
|
361
|
+
...capabilitySeed,
|
|
362
|
+
...options.capabilities,
|
|
363
|
+
...elicitation ? { elicitation } : {}
|
|
364
|
+
},
|
|
365
|
+
listChanged: listChangedHandlers(options.listChanged, callbacks)
|
|
366
|
+
}),
|
|
367
|
+
elicitationEnabled: elicitation !== void 0
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
//#endregion
|
|
371
|
+
//#region src/mcp/client/errors.ts
|
|
372
|
+
/**
|
|
373
|
+
* Thrown by `MCPClientManager.callTool()` (and `readResource()` /
|
|
374
|
+
* `getPrompt()`) when a request on a ready connection needs the user to
|
|
375
|
+
* authorize again: a `403 insufficient_scope` step-up, or a `401` whose token
|
|
376
|
+
* refresh failed. The MCP SDK has already built a new authorization URL; the
|
|
377
|
+
* manager has moved the connection to `authenticating` and persisted
|
|
378
|
+
* `authUrl`, so sending the user to `authUrl` completes through the normal
|
|
379
|
+
* OAuth callback. Retry the request once the connection is `ready` again.
|
|
380
|
+
*
|
|
381
|
+
* Extends the SDK's `UnauthorizedError`, which these calls threw before, and
|
|
382
|
+
* keeps its `name`, so existing `instanceof UnauthorizedError` and
|
|
383
|
+
* `name === "UnauthorizedError"` checks keep matching. Use
|
|
384
|
+
* `instanceof MCPAuthorizationRequiredError` to read `authUrl`.
|
|
385
|
+
*/
|
|
386
|
+
var MCPAuthorizationRequiredError = class extends UnauthorizedError {
|
|
387
|
+
/**
|
|
388
|
+
* @param serverId - The MCP server that needs authorization.
|
|
389
|
+
* @param authUrl - The authorization URL the SDK built for the new flow.
|
|
390
|
+
* @param options - The OAuth client id and the original unauthorized error.
|
|
391
|
+
*/
|
|
392
|
+
constructor(serverId, authUrl, options = {}) {
|
|
393
|
+
super(`MCP server "${serverId}" requires authorization: ${toErrorMessage(options.cause ?? "Unauthorized")}`);
|
|
394
|
+
this._tag = "MCPAuthorizationRequiredError";
|
|
395
|
+
this.cause = options.cause;
|
|
396
|
+
this.serverId = serverId;
|
|
397
|
+
this.authUrl = authUrl;
|
|
398
|
+
this.clientId = options.clientId;
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
/**
|
|
402
|
+
* Thrown by `MCPClientManager.callTool()`, `readResource()` and `getPrompt()`
|
|
403
|
+
* when no connection exists for `serverId`: the id was never registered, the
|
|
404
|
+
* server was removed, or a restore has not created the connection yet.
|
|
405
|
+
*/
|
|
406
|
+
var MCPConnectionNotFoundError = class extends Error {
|
|
407
|
+
/**
|
|
408
|
+
* @param serverId - The server id that has no connection.
|
|
409
|
+
*/
|
|
410
|
+
constructor(serverId) {
|
|
411
|
+
super(`No MCP connection for server "${serverId}". It may not be registered yet, may have been removed, or may still be restoring.`);
|
|
412
|
+
this.serverId = serverId;
|
|
413
|
+
this._tag = "MCPConnectionNotFoundError";
|
|
414
|
+
this.name = "MCPConnectionNotFoundError";
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
/** Message of an unknown thrown value. */
|
|
418
|
+
function toErrorMessage(error) {
|
|
419
|
+
return error instanceof Error ? error.message : String(error);
|
|
420
|
+
}
|
|
421
|
+
function getErrorStatus(error) {
|
|
422
|
+
if (!error || typeof error !== "object") return void 0;
|
|
423
|
+
const record = error;
|
|
424
|
+
if (typeof record.code === "number") return record.code;
|
|
425
|
+
if (typeof record.status === "number") return record.status;
|
|
426
|
+
if (typeof record.data?.status === "number") return record.data.status;
|
|
427
|
+
}
|
|
428
|
+
function getErrorCause(error) {
|
|
429
|
+
if (!error || typeof error !== "object") return void 0;
|
|
430
|
+
return error.cause ?? error.data?.cause;
|
|
431
|
+
}
|
|
432
|
+
function isUnauthorized(error) {
|
|
433
|
+
if (getErrorStatus(error) === 401) return true;
|
|
434
|
+
const cause = getErrorCause(error);
|
|
435
|
+
if (cause && cause !== error && isUnauthorized(cause)) return true;
|
|
436
|
+
const msg = toErrorMessage(error);
|
|
437
|
+
return msg.includes("Unauthorized") || msg.includes("401");
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* OAuth error codes a retry can change: the authorization server's own
|
|
441
|
+
* trouble. Every other code (`invalid_target`, `invalid_scope`,
|
|
442
|
+
* `access_denied`, `unauthorized_client`, ...) refuses the request itself.
|
|
443
|
+
* The SDK already recovers `invalid_grant` and `invalid_client` once by
|
|
444
|
+
* starting a fresh authorization, so when they reach us that has failed too.
|
|
445
|
+
*/
|
|
446
|
+
const RETRYABLE_OAUTH_ERRORS = /* @__PURE__ */ new Set(["server_error", "temporarily_unavailable"]);
|
|
447
|
+
/**
|
|
448
|
+
* Whether an error means authorization was refused in a way retrying cannot
|
|
449
|
+
* change: the MCP server answered 403, the authorization server answered
|
|
450
|
+
* with an OAuth error other than a temporary one, or it rejected dynamic
|
|
451
|
+
* client registration with a 4xx other than 429.
|
|
452
|
+
*/
|
|
453
|
+
function isAuthorizationRefused(error, depth = 0) {
|
|
454
|
+
if (depth > 5 || !error || typeof error !== "object") return false;
|
|
455
|
+
if (OAuthError.isInstance(error)) return !RETRYABLE_OAUTH_ERRORS.has(error.code);
|
|
456
|
+
if (RegistrationRejectedError.isInstance(error)) return error.status >= 400 && error.status < 500 && error.status !== 429;
|
|
457
|
+
if (getErrorStatus(error) === 403) return true;
|
|
458
|
+
const cause = getErrorCause(error);
|
|
459
|
+
return cause !== error && isAuthorizationRefused(cause, depth + 1);
|
|
460
|
+
}
|
|
461
|
+
function isTransportNotImplemented(error) {
|
|
462
|
+
const status = getErrorStatus(error);
|
|
463
|
+
if (status === 404 || status === 405) return true;
|
|
464
|
+
const cause = getErrorCause(error);
|
|
465
|
+
if (cause && cause !== error && isTransportNotImplemented(cause)) return true;
|
|
466
|
+
const msg = toErrorMessage(error);
|
|
467
|
+
return msg.includes("404") || msg.includes("405") || msg.includes("Error POSTing to endpoint: Not Found") || msg.includes("Not Implemented") || msg.includes("not implemented");
|
|
468
|
+
}
|
|
469
|
+
//#endregion
|
|
470
|
+
//#region src/mcp/client/connection.ts
|
|
471
|
+
/**
|
|
472
|
+
* Connection state machine for MCP client connections.
|
|
473
|
+
*
|
|
474
|
+
* State transitions:
|
|
475
|
+
* - Non-OAuth: init() → CONNECTING → DISCOVERING → READY
|
|
476
|
+
* - OAuth: init() → AUTHENTICATING → (callback) → CONNECTING → DISCOVERING → READY
|
|
477
|
+
* - Any state can transition to FAILED on error
|
|
478
|
+
*/
|
|
479
|
+
const MCPConnectionState = {
|
|
480
|
+
/** Waiting for OAuth authorization to complete */
|
|
481
|
+
AUTHENTICATING: "authenticating",
|
|
482
|
+
/** Establishing transport connection to MCP server */
|
|
483
|
+
CONNECTING: "connecting",
|
|
484
|
+
/** Transport connection established */
|
|
485
|
+
CONNECTED: "connected",
|
|
486
|
+
/** Discovering server capabilities (tools, resources, prompts) */
|
|
487
|
+
DISCOVERING: "discovering",
|
|
488
|
+
/** Fully connected and ready to use */
|
|
489
|
+
READY: "ready",
|
|
490
|
+
/** Connection failed at some point */
|
|
491
|
+
FAILED: "failed"
|
|
492
|
+
};
|
|
493
|
+
/**
|
|
494
|
+
* Apply `headers` to an HTTP transport's options. The SDK transports only
|
|
495
|
+
* read `requestInit`, and the SSE stream only `eventSourceInit.fetch`.
|
|
496
|
+
* Headers already in `requestInit` win.
|
|
497
|
+
*/
|
|
498
|
+
function withStaticHeaders(options) {
|
|
499
|
+
const { headers } = options;
|
|
500
|
+
if (!headers) return options;
|
|
501
|
+
const merge = (overrides) => {
|
|
502
|
+
const merged = new Headers(headers);
|
|
503
|
+
new Headers(overrides).forEach((value, key) => merged.set(key, value));
|
|
504
|
+
return merged;
|
|
505
|
+
};
|
|
506
|
+
const sse = options;
|
|
507
|
+
const streamFetch = sse.eventSourceInit?.fetch ?? fetch;
|
|
508
|
+
return {
|
|
509
|
+
...options,
|
|
510
|
+
requestInit: {
|
|
511
|
+
...options.requestInit,
|
|
512
|
+
headers: merge(options.requestInit?.headers)
|
|
513
|
+
},
|
|
514
|
+
eventSourceInit: {
|
|
515
|
+
...sse.eventSourceInit,
|
|
516
|
+
fetch: (url, init) => streamFetch(url, {
|
|
517
|
+
...init,
|
|
518
|
+
headers: Object.fromEntries(merge(init.headers))
|
|
519
|
+
})
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
var MCPClientConnection = class {
|
|
524
|
+
constructor(url, _info, options = {
|
|
525
|
+
client: {},
|
|
526
|
+
transport: {}
|
|
527
|
+
}) {
|
|
528
|
+
this.url = url;
|
|
529
|
+
this._info = _info;
|
|
530
|
+
this.options = options;
|
|
531
|
+
this.connectionState = MCPConnectionState.CONNECTING;
|
|
532
|
+
this.connectionError = null;
|
|
533
|
+
this.tools = [];
|
|
534
|
+
this.accessRefused = false;
|
|
535
|
+
this._authorizationTurns = new AuthorizationTurns();
|
|
536
|
+
this.prompts = [];
|
|
537
|
+
this.resources = [];
|
|
538
|
+
this.resourceTemplates = [];
|
|
539
|
+
this._probingCapabilities = false;
|
|
540
|
+
this._connecting = false;
|
|
541
|
+
this._advertisedElicitation = "null";
|
|
542
|
+
this._onObservabilityEvent = new Emitter();
|
|
543
|
+
this.onObservabilityEvent = this._onObservabilityEvent.event;
|
|
544
|
+
this._onListChanged = new Emitter();
|
|
545
|
+
this.onListChanged = this._onListChanged.event;
|
|
546
|
+
this._elicitationEnabled = false;
|
|
547
|
+
this.options = {
|
|
548
|
+
...options,
|
|
549
|
+
client: normalizeMcpClientOptions(options.client)
|
|
550
|
+
};
|
|
551
|
+
this.client = this.createClient();
|
|
552
|
+
}
|
|
553
|
+
createClient() {
|
|
554
|
+
const created = createMcpSdkClient(this._info, this.options.client, this.options.capabilitySeed, this.options.elicitationHandlers, {
|
|
555
|
+
tools: (error, tools) => {
|
|
556
|
+
if (!error && tools) this.tools = tools;
|
|
557
|
+
this._onListChanged.fire();
|
|
558
|
+
},
|
|
559
|
+
prompts: (error, prompts) => {
|
|
560
|
+
if (!error && prompts) this.prompts = prompts;
|
|
561
|
+
this._onListChanged.fire();
|
|
562
|
+
},
|
|
563
|
+
resources: (error, resources) => {
|
|
564
|
+
if (!error && resources) this.resources = resources;
|
|
565
|
+
this._onListChanged.fire();
|
|
566
|
+
}
|
|
567
|
+
});
|
|
568
|
+
this._elicitationEnabled = created.elicitationEnabled;
|
|
569
|
+
this._advertisedElicitation = this.elicitationToAdvertise();
|
|
570
|
+
return created.client;
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Configure the handler used for server-initiated elicitation requests.
|
|
574
|
+
*
|
|
575
|
+
* If the connection has not been initialized yet, rebuild the SDK client so
|
|
576
|
+
* handler-driven elicitation capabilities are reflected in the initial
|
|
577
|
+
* handshake. A rebuild (rather than `Client.registerCapabilities`) is
|
|
578
|
+
* required because SDK capability registration is merge-only — it cannot
|
|
579
|
+
* un-advertise a mode when handlers are cleared before connecting. Active
|
|
580
|
+
* connections keep their negotiated capabilities until they reconnect.
|
|
581
|
+
*/
|
|
582
|
+
configureElicitationHandlers(handlers) {
|
|
583
|
+
this.options.elicitationHandlers = handlers;
|
|
584
|
+
this.options.capabilitySeed = void 0;
|
|
585
|
+
if (!this._transport && !this._connecting) this.client = this.createClient();
|
|
586
|
+
}
|
|
587
|
+
/** What a client built now would advertise for elicitation, as JSON. */
|
|
588
|
+
elicitationToAdvertise() {
|
|
589
|
+
return JSON.stringify(advertisedElicitation(this.options.client, this.options.capabilitySeed, this.options.elicitationHandlers) ?? null);
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* Connect, and connect again when the elicitation handlers changed during
|
|
593
|
+
* the handshake: apps configure them in `onStart`, while a restored
|
|
594
|
+
* server is already connecting.
|
|
595
|
+
*/
|
|
596
|
+
async connectWithCurrentHandlers(transportType) {
|
|
597
|
+
this._connecting = true;
|
|
598
|
+
try {
|
|
599
|
+
let res = await this.tryConnect(transportType);
|
|
600
|
+
for (let again = 0; again < 3; again++) {
|
|
601
|
+
if (this._advertisedElicitation === this.elicitationToAdvertise()) break;
|
|
602
|
+
if (res.state === MCPConnectionState.AUTHENTICATING) break;
|
|
603
|
+
this._transport = void 0;
|
|
604
|
+
await this.client.close().catch(() => {});
|
|
605
|
+
this.client = this.createClient();
|
|
606
|
+
if (res.state !== MCPConnectionState.CONNECTED) break;
|
|
607
|
+
res = await this.tryConnect(transportType);
|
|
608
|
+
}
|
|
609
|
+
return res;
|
|
610
|
+
} finally {
|
|
611
|
+
this._connecting = false;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Initialize a client connection, if authentication is required, the connection will be in the AUTHENTICATING state
|
|
616
|
+
* Sets connection state based on the result and emits observability events
|
|
617
|
+
*
|
|
618
|
+
* @returns Error message if connection failed, undefined otherwise
|
|
619
|
+
*/
|
|
620
|
+
async init() {
|
|
621
|
+
const transportType = this.options.transport.type;
|
|
622
|
+
if (!transportType) throw new Error("Transport type must be specified");
|
|
623
|
+
if (this._transport) {
|
|
624
|
+
this._transport = void 0;
|
|
625
|
+
try {
|
|
626
|
+
await this.client.close();
|
|
627
|
+
} catch {}
|
|
628
|
+
this.client = this.createClient();
|
|
629
|
+
}
|
|
630
|
+
const res = await this.connectWithCurrentHandlers(transportType);
|
|
631
|
+
this.connectionState = res.state;
|
|
632
|
+
this.accessRefused = res.state === MCPConnectionState.FAILED && isAuthorizationRefused(res.error);
|
|
633
|
+
if (res.state === MCPConnectionState.CONNECTED && res.transport) {
|
|
634
|
+
if (this._elicitationEnabled) this.client.setRequestHandler("elicitation/create", async (request, context) => await this.handleElicitationRequest(request, context.mcpReq.signal));
|
|
635
|
+
this.lastConnectedTransport = res.transport;
|
|
636
|
+
this._onObservabilityEvent.fire({
|
|
637
|
+
type: "mcp:client:connect",
|
|
638
|
+
payload: {
|
|
639
|
+
url: this.url.toString(),
|
|
640
|
+
transport: res.transport,
|
|
641
|
+
state: this.connectionState
|
|
642
|
+
},
|
|
643
|
+
timestamp: Date.now()
|
|
644
|
+
});
|
|
645
|
+
return;
|
|
646
|
+
} else if (res.state === MCPConnectionState.FAILED && res.error) {
|
|
647
|
+
const errorMessage = toErrorMessage(res.error);
|
|
648
|
+
this._onObservabilityEvent.fire({
|
|
649
|
+
type: "mcp:client:connect",
|
|
650
|
+
payload: {
|
|
651
|
+
url: this.url.toString(),
|
|
652
|
+
transport: transportType,
|
|
653
|
+
state: this.connectionState,
|
|
654
|
+
error: errorMessage
|
|
655
|
+
},
|
|
656
|
+
timestamp: Date.now()
|
|
657
|
+
});
|
|
658
|
+
return errorMessage;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Finish OAuth by probing transports based on configured type.
|
|
663
|
+
* - Explicit: finish on that transport
|
|
664
|
+
* - Auto: try streamable-http, then sse on 404/405/Not Implemented
|
|
665
|
+
*/
|
|
666
|
+
async finishAuthProbe(callbackParams) {
|
|
667
|
+
if (!this.options.transport.authProvider) throw new Error("No auth provider configured");
|
|
668
|
+
const configuredType = this.options.transport.type;
|
|
669
|
+
if (!configuredType) throw new Error("Transport type must be specified");
|
|
670
|
+
const finishAuth = async (base) => {
|
|
671
|
+
const transport = this.getTransport(base);
|
|
672
|
+
let completed = false;
|
|
673
|
+
try {
|
|
674
|
+
if ("finishAuth" in transport && typeof transport.finishAuth === "function") {
|
|
675
|
+
await transport.finishAuth(callbackParams);
|
|
676
|
+
completed = true;
|
|
677
|
+
}
|
|
678
|
+
} finally {
|
|
679
|
+
if (typeof transport.close === "function") await transport.close().catch(() => {});
|
|
680
|
+
}
|
|
681
|
+
if (completed) this.client = this.createClient();
|
|
682
|
+
};
|
|
683
|
+
if (configuredType === "rpc") throw new Error("RPC transport does not support authentication");
|
|
684
|
+
const authTransport = this._pendingAuthTransport ?? this._transport;
|
|
685
|
+
this._pendingAuthTransport = void 0;
|
|
686
|
+
if (authTransport && "finishAuth" in authTransport && typeof authTransport.finishAuth === "function") {
|
|
687
|
+
let completed = false;
|
|
688
|
+
try {
|
|
689
|
+
await authTransport.finishAuth(callbackParams);
|
|
690
|
+
completed = true;
|
|
691
|
+
} finally {
|
|
692
|
+
if (typeof authTransport.close === "function") await authTransport.close().catch(() => {});
|
|
693
|
+
if (this._transport === authTransport) this._transport = void 0;
|
|
694
|
+
}
|
|
695
|
+
if (completed) this.client = this.createClient();
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (configuredType === "sse" || configuredType === "streamable-http") {
|
|
699
|
+
await finishAuth(configuredType);
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
try {
|
|
703
|
+
await finishAuth("streamable-http");
|
|
704
|
+
} catch (e) {
|
|
705
|
+
if (isTransportNotImplemented(e)) {
|
|
706
|
+
await finishAuth("sse");
|
|
707
|
+
return;
|
|
708
|
+
}
|
|
709
|
+
throw e;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
/**
|
|
713
|
+
* Complete OAuth authorization
|
|
714
|
+
*/
|
|
715
|
+
async completeAuthorization(callback, options = {}) {
|
|
716
|
+
const expectedState = options.alreadyAccepted ? MCPConnectionState.CONNECTING : MCPConnectionState.AUTHENTICATING;
|
|
717
|
+
if (this.connectionState !== expectedState) throw new Error(`Connection must be in ${expectedState} state to complete authorization`);
|
|
718
|
+
if (!options.alreadyAccepted) this.connectionState = MCPConnectionState.CONNECTING;
|
|
719
|
+
try {
|
|
720
|
+
const callbackParams = typeof callback === "string" ? new URLSearchParams({ code: callback }) : callback;
|
|
721
|
+
await this._authorizationTurns.run(() => this.finishAuthProbe(callbackParams));
|
|
722
|
+
} catch (error) {
|
|
723
|
+
this.connectionState = MCPConnectionState.FAILED;
|
|
724
|
+
throw error;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
/**
|
|
728
|
+
* Discover server capabilities and register tools, resources, prompts, and templates.
|
|
729
|
+
* This method does the work but does not manage connection state - that's handled by discover().
|
|
730
|
+
*/
|
|
731
|
+
async discoverAndRegister() {
|
|
732
|
+
const discoveredCapabilities = this.client.getServerCapabilities();
|
|
733
|
+
const shouldProbeCapabilities = !discoveredCapabilities && this.isResumedStreamableHttpSession();
|
|
734
|
+
this.serverCapabilities = discoveredCapabilities;
|
|
735
|
+
this._probingCapabilities = shouldProbeCapabilities;
|
|
736
|
+
if (!discoveredCapabilities && !shouldProbeCapabilities) throw new Error("The MCP Server failed to return server capabilities");
|
|
737
|
+
const operations = [];
|
|
738
|
+
const operationNames = [];
|
|
739
|
+
operations.push(Promise.resolve(this.client.getInstructions()));
|
|
740
|
+
operationNames.push("instructions");
|
|
741
|
+
if (discoveredCapabilities?.tools || shouldProbeCapabilities) {
|
|
742
|
+
operations.push(this.registerTools());
|
|
743
|
+
operationNames.push("tools");
|
|
744
|
+
}
|
|
745
|
+
if (discoveredCapabilities?.resources || shouldProbeCapabilities) {
|
|
746
|
+
operations.push(this.registerResources());
|
|
747
|
+
operationNames.push("resources");
|
|
748
|
+
}
|
|
749
|
+
if (discoveredCapabilities?.prompts || shouldProbeCapabilities) {
|
|
750
|
+
operations.push(this.registerPrompts());
|
|
751
|
+
operationNames.push("prompts");
|
|
752
|
+
}
|
|
753
|
+
if (discoveredCapabilities?.resources || shouldProbeCapabilities) {
|
|
754
|
+
operations.push(this.registerResourceTemplates());
|
|
755
|
+
operationNames.push("resource templates");
|
|
756
|
+
}
|
|
757
|
+
try {
|
|
758
|
+
const results = await Promise.all(operations);
|
|
759
|
+
for (let i = 0; i < results.length; i++) {
|
|
760
|
+
const result = results[i];
|
|
761
|
+
switch (operationNames[i]) {
|
|
762
|
+
case "instructions":
|
|
763
|
+
this.instructions = result;
|
|
764
|
+
break;
|
|
765
|
+
case "tools":
|
|
766
|
+
this.tools = result;
|
|
767
|
+
break;
|
|
768
|
+
case "resources":
|
|
769
|
+
this.resources = result;
|
|
770
|
+
break;
|
|
771
|
+
case "prompts":
|
|
772
|
+
this.prompts = result;
|
|
773
|
+
break;
|
|
774
|
+
case "resource templates":
|
|
775
|
+
this.resourceTemplates = result;
|
|
776
|
+
break;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
} catch (error) {
|
|
780
|
+
this._onObservabilityEvent.fire({
|
|
781
|
+
type: "mcp:client:discover",
|
|
782
|
+
payload: {
|
|
783
|
+
url: this.url.toString(),
|
|
784
|
+
error: toErrorMessage(error)
|
|
785
|
+
},
|
|
786
|
+
timestamp: Date.now()
|
|
787
|
+
});
|
|
788
|
+
throw error;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
/**
|
|
792
|
+
* Discover server capabilities with timeout and cancellation support.
|
|
793
|
+
* If called while a previous discovery is in-flight, the previous discovery will be aborted.
|
|
794
|
+
*
|
|
795
|
+
* @param options Optional configuration
|
|
796
|
+
* @param options.timeoutMs Timeout in milliseconds (default: 15000)
|
|
797
|
+
* @returns Result indicating success/failure with optional error message
|
|
798
|
+
*/
|
|
799
|
+
async discover(options = {}) {
|
|
800
|
+
const { timeoutMs = 15e3 } = options;
|
|
801
|
+
if (this.connectionState !== MCPConnectionState.CONNECTED && this.connectionState !== MCPConnectionState.READY) {
|
|
802
|
+
this._onObservabilityEvent.fire({
|
|
803
|
+
type: "mcp:client:discover",
|
|
804
|
+
payload: {
|
|
805
|
+
url: this.url.toString(),
|
|
806
|
+
state: this.connectionState
|
|
807
|
+
},
|
|
808
|
+
timestamp: Date.now()
|
|
809
|
+
});
|
|
810
|
+
return {
|
|
811
|
+
success: false,
|
|
812
|
+
reason: "error",
|
|
813
|
+
error: `Discovery skipped - connection in ${this.connectionState} state`
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
if (this._discoveryAbortController) {
|
|
817
|
+
this._discoveryAbortController.abort();
|
|
818
|
+
this._discoveryAbortController = void 0;
|
|
819
|
+
}
|
|
820
|
+
const abortController = new AbortController();
|
|
821
|
+
this._discoveryAbortController = abortController;
|
|
822
|
+
this.connectionState = MCPConnectionState.DISCOVERING;
|
|
823
|
+
let timeoutId;
|
|
824
|
+
try {
|
|
825
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
826
|
+
timeoutId = setTimeout(() => reject(/* @__PURE__ */ new Error(`Discovery timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
827
|
+
});
|
|
828
|
+
if (abortController.signal.aborted) throw new Error("Discovery was cancelled");
|
|
829
|
+
const abortPromise = new Promise((_, reject) => {
|
|
830
|
+
abortController.signal.addEventListener("abort", () => {
|
|
831
|
+
reject(/* @__PURE__ */ new Error("Discovery was cancelled"));
|
|
832
|
+
});
|
|
833
|
+
});
|
|
834
|
+
await Promise.race([
|
|
835
|
+
this.discoverAndRegister(),
|
|
836
|
+
timeoutPromise,
|
|
837
|
+
abortPromise
|
|
838
|
+
]);
|
|
839
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
840
|
+
this.connectionState = MCPConnectionState.READY;
|
|
841
|
+
this._onObservabilityEvent.fire({
|
|
842
|
+
type: "mcp:client:discover",
|
|
843
|
+
payload: { url: this.url.toString() },
|
|
844
|
+
timestamp: Date.now()
|
|
845
|
+
});
|
|
846
|
+
return { success: true };
|
|
847
|
+
} catch (e) {
|
|
848
|
+
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
849
|
+
this.connectionState = isUnauthorized(e) ? MCPConnectionState.AUTHENTICATING : MCPConnectionState.CONNECTED;
|
|
850
|
+
this.accessRefused = isAuthorizationRefused(e);
|
|
851
|
+
const error = e instanceof Error ? e.message : String(e);
|
|
852
|
+
return {
|
|
853
|
+
success: false,
|
|
854
|
+
reason: this._probingCapabilities && e instanceof SdkHttpError && e.status === 404 ? "stale-session" : "error",
|
|
855
|
+
error
|
|
856
|
+
};
|
|
857
|
+
} finally {
|
|
858
|
+
this._discoveryAbortController = void 0;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Cancel any in-flight discovery operation.
|
|
863
|
+
* Called when closing the connection.
|
|
864
|
+
*/
|
|
865
|
+
cancelDiscovery() {
|
|
866
|
+
if (this._discoveryAbortController) {
|
|
867
|
+
this._discoveryAbortController.abort();
|
|
868
|
+
this._discoveryAbortController = void 0;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Notification handler registration for tools
|
|
873
|
+
* Should only be called if serverCapabilities.tools exists
|
|
874
|
+
*/
|
|
875
|
+
async registerTools() {
|
|
876
|
+
if (this._probingCapabilities) this.client.setNotificationHandler("notifications/tools/list_changed", async () => {
|
|
877
|
+
this.tools = await this.fetchTools();
|
|
878
|
+
this._onListChanged.fire();
|
|
879
|
+
});
|
|
880
|
+
return this.fetchTools();
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Notification handler registration for resources
|
|
884
|
+
* Should only be called if serverCapabilities.resources exists
|
|
885
|
+
*/
|
|
886
|
+
async registerResources() {
|
|
887
|
+
if (this._probingCapabilities) this.client.setNotificationHandler("notifications/resources/list_changed", async () => {
|
|
888
|
+
this.resources = await this.fetchResources();
|
|
889
|
+
this._onListChanged.fire();
|
|
890
|
+
});
|
|
891
|
+
return this.fetchResources();
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Notification handler registration for prompts
|
|
895
|
+
* Should only be called if serverCapabilities.prompts exists
|
|
896
|
+
*/
|
|
897
|
+
async registerPrompts() {
|
|
898
|
+
if (this._probingCapabilities) this.client.setNotificationHandler("notifications/prompts/list_changed", async () => {
|
|
899
|
+
this.prompts = await this.fetchPrompts();
|
|
900
|
+
this._onListChanged.fire();
|
|
901
|
+
});
|
|
902
|
+
return this.fetchPrompts();
|
|
903
|
+
}
|
|
904
|
+
async registerResourceTemplates() {
|
|
905
|
+
return this.fetchResourceTemplates();
|
|
906
|
+
}
|
|
907
|
+
catalogFetchOptions() {
|
|
908
|
+
return {
|
|
909
|
+
probing: this._probingCapabilities,
|
|
910
|
+
onCapabilityError: this._capabilityErrorHandler.bind(this)
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
async fetchTools() {
|
|
914
|
+
return fetchMcpTools(this.client, this.catalogFetchOptions());
|
|
915
|
+
}
|
|
916
|
+
async fetchResources() {
|
|
917
|
+
return fetchMcpResources(this.client, this.catalogFetchOptions());
|
|
918
|
+
}
|
|
919
|
+
async fetchPrompts() {
|
|
920
|
+
return fetchMcpPrompts(this.client, this.catalogFetchOptions());
|
|
921
|
+
}
|
|
922
|
+
async fetchResourceTemplates() {
|
|
923
|
+
return fetchMcpResourceTemplates(this.client, this.catalogFetchOptions());
|
|
924
|
+
}
|
|
925
|
+
/**
|
|
926
|
+
* Handle elicitation request from server.
|
|
927
|
+
*
|
|
928
|
+
* Delegates to the `elicitationHandlers` connection option when provided.
|
|
929
|
+
*
|
|
930
|
+
* @deprecated Overriding or instance-patching this method directly is
|
|
931
|
+
* deprecated — pass the `elicitationHandlers` connection option instead.
|
|
932
|
+
*/
|
|
933
|
+
async handleElicitationRequest(request, signal) {
|
|
934
|
+
const mode = request.params.mode === "url" ? "url" : "form";
|
|
935
|
+
const handler = this.options.elicitationHandlers?.[mode];
|
|
936
|
+
if (handler) return raceWithSignal(signal ? handler(request, signal) : handler(request), signal);
|
|
937
|
+
if (this.options.elicitationHandlers) throw new Error(`No MCP ${mode}-mode elicitation handler configured for this connection.`);
|
|
938
|
+
throw new Error("Elicitation handler must be implemented for your platform. Provide the MCPClientConnection elicitationHandlers option, or register handlers through the MCP client manager before connecting.");
|
|
939
|
+
}
|
|
940
|
+
isResumedStreamableHttpSession() {
|
|
941
|
+
return this._transport instanceof StreamableHTTPClientTransport && typeof this._transport.sessionId === "string";
|
|
942
|
+
}
|
|
943
|
+
/**
|
|
944
|
+
* @internal The transport of the open session, if any. Each connect opens
|
|
945
|
+
* a new one, and init() drops it before reconnecting.
|
|
946
|
+
*/
|
|
947
|
+
get session() {
|
|
948
|
+
return this._transport;
|
|
949
|
+
}
|
|
950
|
+
get sessionId() {
|
|
951
|
+
if (this._transport instanceof StreamableHTTPClientTransport) return this._transport.sessionId;
|
|
952
|
+
}
|
|
953
|
+
/** @internal Clear a restored session before reconnecting. */
|
|
954
|
+
clearResumedSession() {
|
|
955
|
+
if ("sessionId" in this.options.transport) delete this.options.transport.sessionId;
|
|
956
|
+
}
|
|
957
|
+
get protocolVersion() {
|
|
958
|
+
if (this._transport instanceof StreamableHTTPClientTransport) return this._transport.protocolVersion;
|
|
959
|
+
}
|
|
960
|
+
get discoverResult() {
|
|
961
|
+
return this.client.getDiscoverResult();
|
|
962
|
+
}
|
|
963
|
+
async openRestoredListSubscription() {
|
|
964
|
+
const capabilities = this.client.getServerCapabilities();
|
|
965
|
+
const filter = {
|
|
966
|
+
...capabilities?.tools?.listChanged && { toolsListChanged: true },
|
|
967
|
+
...capabilities?.prompts?.listChanged && { promptsListChanged: true },
|
|
968
|
+
...capabilities?.resources?.listChanged && { resourcesListChanged: true }
|
|
969
|
+
};
|
|
970
|
+
if (Object.keys(filter).length === 0) return;
|
|
971
|
+
try {
|
|
972
|
+
this._restoredListSubscription = await this.client.listen(filter);
|
|
973
|
+
} catch (error) {
|
|
974
|
+
this.client.onerror?.(error instanceof Error ? error : new Error(String(error)));
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
getTransportName(transport) {
|
|
978
|
+
if (transport instanceof StreamableHTTPClientTransport) return "streamable-http";
|
|
979
|
+
if (transport instanceof SSEClientTransport) return "sse";
|
|
980
|
+
if (transport instanceof RPCClientTransport) return "rpc";
|
|
981
|
+
return this.lastConnectedTransport;
|
|
982
|
+
}
|
|
983
|
+
async close() {
|
|
984
|
+
const transport = this._transport;
|
|
985
|
+
this._transport = void 0;
|
|
986
|
+
await this._restoredListSubscription?.close().catch(() => {});
|
|
987
|
+
this._restoredListSubscription = void 0;
|
|
988
|
+
const url = this.url.toString();
|
|
989
|
+
const transportName = this.getTransportName(transport);
|
|
990
|
+
if (transport instanceof StreamableHTTPClientTransport && transport.sessionId) try {
|
|
991
|
+
await transport.terminateSession();
|
|
992
|
+
} catch (error) {
|
|
993
|
+
this._onObservabilityEvent.fire({
|
|
994
|
+
type: "mcp:client:close",
|
|
995
|
+
payload: {
|
|
996
|
+
url,
|
|
997
|
+
transport: transportName,
|
|
998
|
+
state: "error",
|
|
999
|
+
error: toErrorMessage(error),
|
|
1000
|
+
phase: "terminate-session"
|
|
1001
|
+
},
|
|
1002
|
+
timestamp: Date.now()
|
|
1003
|
+
});
|
|
1004
|
+
}
|
|
1005
|
+
try {
|
|
1006
|
+
await this.client.close();
|
|
1007
|
+
} catch (error) {
|
|
1008
|
+
this._onObservabilityEvent.fire({
|
|
1009
|
+
type: "mcp:client:close",
|
|
1010
|
+
payload: {
|
|
1011
|
+
url,
|
|
1012
|
+
transport: transportName,
|
|
1013
|
+
state: "error",
|
|
1014
|
+
error: toErrorMessage(error),
|
|
1015
|
+
phase: "client-close"
|
|
1016
|
+
},
|
|
1017
|
+
timestamp: Date.now()
|
|
1018
|
+
});
|
|
1019
|
+
throw error;
|
|
1020
|
+
}
|
|
1021
|
+
this._onObservabilityEvent.fire({
|
|
1022
|
+
type: "mcp:client:close",
|
|
1023
|
+
payload: {
|
|
1024
|
+
url,
|
|
1025
|
+
transport: transportName,
|
|
1026
|
+
state: "closed"
|
|
1027
|
+
},
|
|
1028
|
+
timestamp: Date.now()
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Get the transport for the client
|
|
1033
|
+
* @param transportType - The transport type to get
|
|
1034
|
+
* @returns The transport for the client
|
|
1035
|
+
*/
|
|
1036
|
+
getTransport(transportType) {
|
|
1037
|
+
switch (transportType) {
|
|
1038
|
+
case "streamable-http": return this.withAuthorizationTurns(new StreamableHTTPClientTransport(this.url, this.authorizationTurnOptions(withStaticHeaders(this.options.transport))));
|
|
1039
|
+
case "sse": return this.withAuthorizationTurns(new SSEClientTransport(this.url, this.authorizationTurnOptions(withStaticHeaders(this.options.transport))));
|
|
1040
|
+
case "rpc": return new RPCClientTransport(this.options.transport);
|
|
1041
|
+
default: throw new Error(`Unsupported transport type: ${transportType}`);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Take an HTTP transport's OAuth flows one at a time: a `401` waits for the
|
|
1046
|
+
* authorization an earlier one started, so concurrent requests share one
|
|
1047
|
+
* client registration and one pending link.
|
|
1048
|
+
*/
|
|
1049
|
+
/** Transport options whose `fetch` records the token each 401 carried. */
|
|
1050
|
+
authorizationTurnOptions(options) {
|
|
1051
|
+
if (!this.options.transport.authProvider) return options;
|
|
1052
|
+
return {
|
|
1053
|
+
...options,
|
|
1054
|
+
fetch: this._authorizationTurns.wrapFetch(options.fetch)
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
withAuthorizationTurns(transport) {
|
|
1058
|
+
const { authProvider } = this.options.transport;
|
|
1059
|
+
if (authProvider) this._authorizationTurns.wrapTransport(transport, authProvider);
|
|
1060
|
+
return transport;
|
|
1061
|
+
}
|
|
1062
|
+
async tryConnect(transportType) {
|
|
1063
|
+
const transports = transportType === "auto" ? ["streamable-http", "sse"] : [transportType];
|
|
1064
|
+
for (const currentTransportType of transports) {
|
|
1065
|
+
const isLastTransport = currentTransportType === transports[transports.length - 1];
|
|
1066
|
+
const hasFallback = transportType === "auto" && currentTransportType === "streamable-http" && !isLastTransport;
|
|
1067
|
+
const transport = this.getTransport(currentTransportType);
|
|
1068
|
+
try {
|
|
1069
|
+
const prior = transport instanceof StreamableHTTPClientTransport && transport.sessionId && this.options.discoverResult ? {
|
|
1070
|
+
kind: "modern",
|
|
1071
|
+
discover: this.options.discoverResult
|
|
1072
|
+
} : void 0;
|
|
1073
|
+
await this.client.connect(transport, prior ? { prior } : void 0);
|
|
1074
|
+
this._transport = transport;
|
|
1075
|
+
this._pendingAuthTransport = void 0;
|
|
1076
|
+
if (prior) await this.openRestoredListSubscription();
|
|
1077
|
+
return {
|
|
1078
|
+
state: MCPConnectionState.CONNECTED,
|
|
1079
|
+
transport: currentTransportType
|
|
1080
|
+
};
|
|
1081
|
+
} catch (e) {
|
|
1082
|
+
const error = e instanceof Error ? e : new Error(String(e));
|
|
1083
|
+
if (isUnauthorized(error)) {
|
|
1084
|
+
this._pendingAuthTransport = transport;
|
|
1085
|
+
return { state: MCPConnectionState.AUTHENTICATING };
|
|
1086
|
+
}
|
|
1087
|
+
if (isTransportNotImplemented(error) && hasFallback) continue;
|
|
1088
|
+
return {
|
|
1089
|
+
state: MCPConnectionState.FAILED,
|
|
1090
|
+
error
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
return {
|
|
1095
|
+
state: MCPConnectionState.FAILED,
|
|
1096
|
+
error: /* @__PURE__ */ new Error("No transports available")
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
_capabilityErrorHandler(empty, method) {
|
|
1100
|
+
return (e) => {
|
|
1101
|
+
if (e.code === -32601) {
|
|
1102
|
+
const url = this.url.toString();
|
|
1103
|
+
this._onObservabilityEvent.fire({
|
|
1104
|
+
type: "mcp:client:discover",
|
|
1105
|
+
payload: {
|
|
1106
|
+
url,
|
|
1107
|
+
capability: method.split("/")[0],
|
|
1108
|
+
error: toErrorMessage(e)
|
|
1109
|
+
},
|
|
1110
|
+
timestamp: Date.now()
|
|
1111
|
+
});
|
|
1112
|
+
return empty;
|
|
1113
|
+
}
|
|
1114
|
+
throw e;
|
|
1115
|
+
};
|
|
1116
|
+
}
|
|
1117
|
+
};
|
|
1118
|
+
//#endregion
|
|
1119
|
+
//#region src/mcp/client/ai-tools.ts
|
|
1120
|
+
var _schemas = /* @__PURE__ */ new WeakMap();
|
|
1121
|
+
/**
|
|
1122
|
+
* Converts MCP tool catalogs into AI SDK tool records. Converted schemas are
|
|
1123
|
+
* cached per connection while that connection keeps the same catalog array
|
|
1124
|
+
* and schema-source identities; tool records and `execute` closures are
|
|
1125
|
+
* rebuilt on every call.
|
|
1126
|
+
*/
|
|
1127
|
+
var MCPAIToolConverter = class {
|
|
1128
|
+
constructor() {
|
|
1129
|
+
_classPrivateFieldInitSpec(this, _schemas, /* @__PURE__ */ new WeakMap());
|
|
1130
|
+
}
|
|
1131
|
+
/**
|
|
1132
|
+
* Convert the tools of the given connections.
|
|
1133
|
+
*
|
|
1134
|
+
* @param connections - Connections keyed by server id.
|
|
1135
|
+
* @param callTool - Runs a tool call for a tool's `execute`.
|
|
1136
|
+
* @returns AI SDK tools keyed `tool_<serverId>_<toolName>`.
|
|
1137
|
+
*/
|
|
1138
|
+
convert(connections, callTool) {
|
|
1139
|
+
const entries = [];
|
|
1140
|
+
for (const [serverId, conn] of Object.entries(connections)) {
|
|
1141
|
+
if (conn.connectionState !== MCPConnectionState.READY && conn.connectionState !== MCPConnectionState.AUTHENTICATING) console.warn(`[getAITools] WARNING: Reading tools from connection ${serverId} in state "${conn.connectionState}". Tools may not be loaded yet.`);
|
|
1142
|
+
const catalog = conn.tools;
|
|
1143
|
+
let cache = _classPrivateFieldGet2(_schemas, this).get(conn);
|
|
1144
|
+
if (!cache || cache.catalog !== catalog) {
|
|
1145
|
+
cache = {
|
|
1146
|
+
catalog,
|
|
1147
|
+
converted: []
|
|
1148
|
+
};
|
|
1149
|
+
_classPrivateFieldGet2(_schemas, this).set(conn, cache);
|
|
1150
|
+
}
|
|
1151
|
+
for (const [index, tool] of catalog.entries()) {
|
|
1152
|
+
const toolName = tool.name;
|
|
1153
|
+
try {
|
|
1154
|
+
const sourceInputSchema = tool.inputSchema;
|
|
1155
|
+
const sourceOutputSchema = tool.outputSchema;
|
|
1156
|
+
let slot = cache.converted[index];
|
|
1157
|
+
if (!slot || slot.tool !== tool || slot.inputSchema !== sourceInputSchema || slot.outputSchema !== sourceOutputSchema) {
|
|
1158
|
+
try {
|
|
1159
|
+
slot = {
|
|
1160
|
+
status: "converted",
|
|
1161
|
+
tool,
|
|
1162
|
+
inputSchema: sourceInputSchema,
|
|
1163
|
+
outputSchema: sourceOutputSchema,
|
|
1164
|
+
converted: {
|
|
1165
|
+
inputSchema: sourceInputSchema ? z.fromJSONSchema(sourceInputSchema) : z.fromJSONSchema({ type: "object" }),
|
|
1166
|
+
outputSchema: sourceOutputSchema ? z.fromJSONSchema(sourceOutputSchema) : void 0
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
} catch (error) {
|
|
1170
|
+
const errorText = String(error);
|
|
1171
|
+
cache.converted[index] = {
|
|
1172
|
+
status: "failed",
|
|
1173
|
+
tool,
|
|
1174
|
+
inputSchema: sourceInputSchema,
|
|
1175
|
+
outputSchema: sourceOutputSchema,
|
|
1176
|
+
error: errorText
|
|
1177
|
+
};
|
|
1178
|
+
console.warn(`[getAITools] Skipping tool "${toolName}" from "${serverId}": ${errorText}`);
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
cache.converted[index] = slot;
|
|
1182
|
+
}
|
|
1183
|
+
if (slot.status === "failed") continue;
|
|
1184
|
+
const toolKey = `tool_${serverId.replace(/-/g, "")}_${toolName}`;
|
|
1185
|
+
const title = tool.title ?? tool.annotations?.title;
|
|
1186
|
+
const description = tool.description;
|
|
1187
|
+
entries.push([toolKey, {
|
|
1188
|
+
description,
|
|
1189
|
+
title,
|
|
1190
|
+
execute: async (args) => {
|
|
1191
|
+
const result = await callTool({
|
|
1192
|
+
arguments: args,
|
|
1193
|
+
name: toolName,
|
|
1194
|
+
serverId
|
|
1195
|
+
});
|
|
1196
|
+
if (result.isError) {
|
|
1197
|
+
const textContent = result.content?.[0];
|
|
1198
|
+
const message = textContent?.type === "text" && textContent.text ? textContent.text : "Tool call failed";
|
|
1199
|
+
throw new Error(message);
|
|
1200
|
+
}
|
|
1201
|
+
return result;
|
|
1202
|
+
},
|
|
1203
|
+
inputSchema: slot.converted.inputSchema,
|
|
1204
|
+
outputSchema: slot.converted.outputSchema
|
|
1205
|
+
}]);
|
|
1206
|
+
} catch (error) {
|
|
1207
|
+
console.warn(`[getAITools] Skipping tool "${toolName}" from "${serverId}": ${error}`);
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
cache.converted.length = catalog.length;
|
|
1211
|
+
}
|
|
1212
|
+
return Object.fromEntries(entries);
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
//#endregion
|
|
1216
|
+
//#region src/mcp/client/authorization-rounds.ts
|
|
1217
|
+
/**
|
|
1218
|
+
* The authorization retry limit from the MCP authorization spec
|
|
1219
|
+
* (2026-07-28, "Step-Up Authorization Flow"): after a scope challenge the
|
|
1220
|
+
* client re-authorizes and retries "no more than a few times", then treats
|
|
1221
|
+
* the challenge as a permanent authorization failure, tracking attempts
|
|
1222
|
+
* so it does not loop on the same request.
|
|
1223
|
+
*
|
|
1224
|
+
* A round is one authorization URL the user is sent to. Rounds are counted
|
|
1225
|
+
* separately for each requested scope set, so challenges that alternate
|
|
1226
|
+
* between scope sets each use up their own budget. A new round for a scope
|
|
1227
|
+
* set only counts once its previous round completed (its callback exchanged
|
|
1228
|
+
* a code) and the server asked for the same scopes again. Several links
|
|
1229
|
+
* issued for one pending ask (for example two tool calls hitting the same
|
|
1230
|
+
* step-up at once) are one round.
|
|
1231
|
+
*/
|
|
1232
|
+
/** Completed authorization rounds allowed for one scope set. */
|
|
1233
|
+
const MAX_AUTHORIZATION_ROUNDS = 3;
|
|
1234
|
+
/** A scope set's rounds are forgotten this long after its latest round. */
|
|
1235
|
+
const AUTHORIZATION_ROUNDS_WINDOW_MS = 3600 * 1e3;
|
|
1236
|
+
/**
|
|
1237
|
+
* The requested scope set of an authorization URL: the `scope` parameter's
|
|
1238
|
+
* tokens, deduplicated and sorted, or an empty string when absent.
|
|
1239
|
+
*/
|
|
1240
|
+
function requestedScope(authUrl) {
|
|
1241
|
+
let scope;
|
|
1242
|
+
try {
|
|
1243
|
+
scope = new URL(authUrl).searchParams.get("scope");
|
|
1244
|
+
} catch {
|
|
1245
|
+
return "";
|
|
1246
|
+
}
|
|
1247
|
+
if (!scope) return "";
|
|
1248
|
+
return [...new Set(scope.split(/\s+/).filter(Boolean))].sort().join(" ");
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Decide whether a new authorization link may be shown.
|
|
1252
|
+
*
|
|
1253
|
+
* @param previous - The server's recorded rounds, when any.
|
|
1254
|
+
* @param scope - The requested scope set of the new link.
|
|
1255
|
+
* @param now - The current time in epoch milliseconds.
|
|
1256
|
+
* @param state - The OAuth state of the new link, when it has one.
|
|
1257
|
+
* @returns The rounds to record, or that the limit is reached.
|
|
1258
|
+
*/
|
|
1259
|
+
function startRound(previous, scope, now, state) {
|
|
1260
|
+
const byScope = live(previous?.byScope ?? {}, now);
|
|
1261
|
+
const current = entryFor(byScope, scope);
|
|
1262
|
+
let next;
|
|
1263
|
+
if (!current) next = {
|
|
1264
|
+
rounds: 1,
|
|
1265
|
+
completed: false,
|
|
1266
|
+
at: now
|
|
1267
|
+
};
|
|
1268
|
+
else if (!current.completed) next = {
|
|
1269
|
+
...current,
|
|
1270
|
+
at: now
|
|
1271
|
+
};
|
|
1272
|
+
else if (current.rounds + 1 > MAX_AUTHORIZATION_ROUNDS) return {
|
|
1273
|
+
_tag: "exhausted",
|
|
1274
|
+
rounds: current.rounds,
|
|
1275
|
+
scope
|
|
1276
|
+
};
|
|
1277
|
+
else next = {
|
|
1278
|
+
rounds: current.rounds + 1,
|
|
1279
|
+
completed: false,
|
|
1280
|
+
at: now
|
|
1281
|
+
};
|
|
1282
|
+
const scopes = {
|
|
1283
|
+
...byScope,
|
|
1284
|
+
[scope]: next
|
|
1285
|
+
};
|
|
1286
|
+
return {
|
|
1287
|
+
_tag: "start",
|
|
1288
|
+
rounds: {
|
|
1289
|
+
latest: scope,
|
|
1290
|
+
byScope: scopes,
|
|
1291
|
+
byState: rememberLink(previous?.byState ?? {}, scopes, state, scope)
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Record that a callback exchanged a code: the round of the link it belongs
|
|
1297
|
+
* to is complete. Links for other scope sets keep waiting. Rounds stored
|
|
1298
|
+
* before links were recorded count the callback for the latest round; with
|
|
1299
|
+
* links recorded, a link that is not among them completes nothing.
|
|
1300
|
+
*
|
|
1301
|
+
* @param previous - The server's recorded rounds, when any.
|
|
1302
|
+
* @param state - The OAuth state of the callback.
|
|
1303
|
+
*/
|
|
1304
|
+
function completeRound(previous, state) {
|
|
1305
|
+
if (!previous) return void 0;
|
|
1306
|
+
const links = previous.byState;
|
|
1307
|
+
const scope = !links ? previous.latest : state && Object.hasOwn(links, state) ? links[state] : void 0;
|
|
1308
|
+
const byState = Object.fromEntries(Object.entries(links ?? {}).filter(([link]) => link !== state));
|
|
1309
|
+
const current = scope === void 0 ? void 0 : entryFor(previous.byScope, scope);
|
|
1310
|
+
if (scope === void 0 || !current) return {
|
|
1311
|
+
...previous,
|
|
1312
|
+
byState
|
|
1313
|
+
};
|
|
1314
|
+
return {
|
|
1315
|
+
latest: previous.latest,
|
|
1316
|
+
byScope: {
|
|
1317
|
+
...previous.byScope,
|
|
1318
|
+
[scope]: {
|
|
1319
|
+
...current,
|
|
1320
|
+
completed: true
|
|
1321
|
+
}
|
|
1322
|
+
},
|
|
1323
|
+
byState
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
/** Parse recorded rounds read back from storage. */
|
|
1327
|
+
function parseAuthorizationRounds(value) {
|
|
1328
|
+
if (!isRecord(value) || typeof value.latest !== "string" || !isRecord(value.byScope)) return;
|
|
1329
|
+
const byScope = Object.fromEntries(Object.entries(value.byScope).flatMap(([scope, entry]) => isRecord(entry) && typeof entry.rounds === "number" && typeof entry.completed === "boolean" && typeof entry.at === "number" ? [[scope, {
|
|
1330
|
+
rounds: entry.rounds,
|
|
1331
|
+
completed: entry.completed,
|
|
1332
|
+
at: entry.at
|
|
1333
|
+
}]] : []));
|
|
1334
|
+
const byState = isRecord(value.byState) ? Object.fromEntries(Object.entries(value.byState).filter((entry) => typeof entry[1] === "string")) : void 0;
|
|
1335
|
+
return {
|
|
1336
|
+
latest: value.latest,
|
|
1337
|
+
byScope,
|
|
1338
|
+
...byState && { byState }
|
|
1339
|
+
};
|
|
1340
|
+
}
|
|
1341
|
+
/** Message for a server that hit the limit. */
|
|
1342
|
+
function authorizationExhaustedMessage(rounds, scope) {
|
|
1343
|
+
return `The server still requires authorization${scope ? ` for scope "${scope}"` : ""} after ${rounds} completed authorizations. Stopped to avoid an authorization loop; reconnect the server to try again.`;
|
|
1344
|
+
}
|
|
1345
|
+
/** Remember a new link's scope set, dropping links whose round is gone. */
|
|
1346
|
+
function rememberLink(links, byScope, state, scope) {
|
|
1347
|
+
const kept = Object.entries(links).filter(([link, linkScope]) => link !== state && Object.hasOwn(byScope, linkScope));
|
|
1348
|
+
if (state) kept.push([state, scope]);
|
|
1349
|
+
return Object.fromEntries(kept.slice(-64));
|
|
1350
|
+
}
|
|
1351
|
+
/** A scope set's own entry; never an inherited `Object` member. */
|
|
1352
|
+
function entryFor(byScope, scope) {
|
|
1353
|
+
return Object.hasOwn(byScope, scope) ? byScope[scope] : void 0;
|
|
1354
|
+
}
|
|
1355
|
+
/** Scope sets whose latest round is still inside the window. */
|
|
1356
|
+
function live(byScope, now) {
|
|
1357
|
+
return Object.fromEntries(Object.entries(byScope).filter(([, entry]) => now - entry.at <= AUTHORIZATION_ROUNDS_WINDOW_MS));
|
|
1358
|
+
}
|
|
1359
|
+
function isRecord(value) {
|
|
1360
|
+
return typeof value === "object" && value !== null;
|
|
1361
|
+
}
|
|
1362
|
+
//#endregion
|
|
1363
|
+
//#region src/mcp/client/oauth-callback.ts
|
|
1364
|
+
/** Server id embedded in an OAuth `state` of the form `{nonce}.{serverId}`. */
|
|
1365
|
+
function serverIdFromState(state) {
|
|
1366
|
+
if (!state) return null;
|
|
1367
|
+
const parts = state.split(".");
|
|
1368
|
+
return parts.length === 2 ? parts[1] : null;
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Whether a request is an OAuth callback for one of the stored servers: a
|
|
1372
|
+
* `GET` whose `state` names a server and whose origin and path match that
|
|
1373
|
+
* server's registered callback URL, so unrelated requests carrying a
|
|
1374
|
+
* `state` parameter are left alone.
|
|
1375
|
+
*/
|
|
1376
|
+
function isOAuthCallbackFor(request, servers) {
|
|
1377
|
+
if (request.method !== "GET") return false;
|
|
1378
|
+
const url = new URL(request.url);
|
|
1379
|
+
const serverId = serverIdFromState(url.searchParams.get("state"));
|
|
1380
|
+
if (!serverId) return false;
|
|
1381
|
+
return servers.some((server) => {
|
|
1382
|
+
if (server.id !== serverId) return false;
|
|
1383
|
+
try {
|
|
1384
|
+
const storedUrl = new URL(server.callback_url);
|
|
1385
|
+
return storedUrl.origin === url.origin && storedUrl.pathname === url.pathname;
|
|
1386
|
+
} catch {
|
|
1387
|
+
return false;
|
|
1388
|
+
}
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
/** Parse a callback request and find the server and connection it targets. */
|
|
1392
|
+
function parseOAuthCallback(request, lookup) {
|
|
1393
|
+
const url = new URL(request.url);
|
|
1394
|
+
const code = url.searchParams.get("code");
|
|
1395
|
+
const state = url.searchParams.get("state");
|
|
1396
|
+
const error = url.searchParams.get("error");
|
|
1397
|
+
if (!state) return {
|
|
1398
|
+
_tag: "invalid",
|
|
1399
|
+
error: "Unauthorized: no state provided"
|
|
1400
|
+
};
|
|
1401
|
+
const serverId = serverIdFromState(state);
|
|
1402
|
+
if (!serverId) return {
|
|
1403
|
+
_tag: "invalid",
|
|
1404
|
+
error: "No serverId found in state parameter. Expected format: {nonce}.{serverId}"
|
|
1405
|
+
};
|
|
1406
|
+
if (!code && !error) return {
|
|
1407
|
+
_tag: "invalid",
|
|
1408
|
+
serverId,
|
|
1409
|
+
state,
|
|
1410
|
+
error: "Unauthorized: no code provided"
|
|
1411
|
+
};
|
|
1412
|
+
if (!lookup.hasServer(serverId)) return {
|
|
1413
|
+
_tag: "invalid",
|
|
1414
|
+
serverId,
|
|
1415
|
+
error: `No server found with id "${serverId}". Was the request matched with \`isCallbackRequest()\`?`
|
|
1416
|
+
};
|
|
1417
|
+
if (!lookup.hasConnection(serverId)) return {
|
|
1418
|
+
_tag: "invalid",
|
|
1419
|
+
serverId,
|
|
1420
|
+
error: `No connection found for serverId "${serverId}".`
|
|
1421
|
+
};
|
|
1422
|
+
return {
|
|
1423
|
+
_tag: "callback",
|
|
1424
|
+
serverId,
|
|
1425
|
+
state,
|
|
1426
|
+
params: url.searchParams
|
|
1427
|
+
};
|
|
1428
|
+
}
|
|
1429
|
+
/** Whether the provider will still redeem `state` for this server. */
|
|
1430
|
+
async function isRedeemableState(serverId, authProvider, state) {
|
|
1431
|
+
authProvider.serverId = serverId;
|
|
1432
|
+
try {
|
|
1433
|
+
return (await authProvider.checkState(state)).valid;
|
|
1434
|
+
} catch {
|
|
1435
|
+
return false;
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* `authUrl` when it is an absolute http(s) URL, so a corrupted stored value
|
|
1440
|
+
* is never handed to a client. Whether the link still works is up to the
|
|
1441
|
+
* authorization server and the callback, not this check.
|
|
1442
|
+
*/
|
|
1443
|
+
function usableAuthUrl(authUrl) {
|
|
1444
|
+
if (!authUrl) return void 0;
|
|
1445
|
+
try {
|
|
1446
|
+
const { protocol } = new URL(authUrl);
|
|
1447
|
+
return protocol === "http:" || protocol === "https:" ? authUrl : void 0;
|
|
1448
|
+
} catch {
|
|
1449
|
+
return;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Consume the state of a callback that arrived after its flow was already
|
|
1454
|
+
* accepted (a duplicate or stale popup), so it cannot be replayed. Verifier
|
|
1455
|
+
* cleanup is left to the active completion path.
|
|
1456
|
+
*/
|
|
1457
|
+
async function consumeStaleState(serverId, authProvider, state) {
|
|
1458
|
+
authProvider.serverId = serverId;
|
|
1459
|
+
try {
|
|
1460
|
+
const stateValidation = await authProvider.checkState(state);
|
|
1461
|
+
if (!stateValidation.valid) {
|
|
1462
|
+
console.warn(`[MCPClientManager] Ignoring stale OAuth callback with invalid state for server "${serverId}": ${stateValidation.error ?? "Invalid state"}`);
|
|
1463
|
+
return;
|
|
1464
|
+
}
|
|
1465
|
+
await authProvider.consumeState(state);
|
|
1466
|
+
} catch (cleanupError) {
|
|
1467
|
+
console.warn(`[MCPClientManager] Failed to clean up stale OAuth callback state for server "${serverId}":`, cleanupError);
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* Exchange a callback's authorization code on the connection, inside the
|
|
1472
|
+
* PKCE verifier scope of its state, then delete that verifier. A completion
|
|
1473
|
+
* error wins over a cleanup error.
|
|
1474
|
+
*/
|
|
1475
|
+
async function exchangeAuthorizationCode(serverId, conn, authProvider, state, params) {
|
|
1476
|
+
const exchange = async () => {
|
|
1477
|
+
let completeError;
|
|
1478
|
+
let cleanupError;
|
|
1479
|
+
try {
|
|
1480
|
+
await conn.completeAuthorization(params, { alreadyAccepted: true });
|
|
1481
|
+
} catch (error) {
|
|
1482
|
+
completeError = error;
|
|
1483
|
+
}
|
|
1484
|
+
try {
|
|
1485
|
+
await authProvider.deleteCodeVerifier();
|
|
1486
|
+
} catch (deleteError) {
|
|
1487
|
+
cleanupError = deleteError;
|
|
1488
|
+
}
|
|
1489
|
+
if (completeError) {
|
|
1490
|
+
if (cleanupError) console.warn(`[MCPClientManager] Failed to clean up OAuth code verifier for server "${serverId}":`, cleanupError);
|
|
1491
|
+
throw completeError;
|
|
1492
|
+
}
|
|
1493
|
+
if (cleanupError) throw cleanupError;
|
|
1494
|
+
};
|
|
1495
|
+
if (authProvider.runWithCodeVerifierState) {
|
|
1496
|
+
await authProvider.runWithCodeVerifierState(state, exchange);
|
|
1497
|
+
return;
|
|
1498
|
+
}
|
|
1499
|
+
await exchange();
|
|
1500
|
+
}
|
|
1501
|
+
/** The response for a handled callback, per the configured handler or redirects. */
|
|
1502
|
+
function oauthCallbackResponse(result, request, config) {
|
|
1503
|
+
if (config?.customHandler) return config.customHandler(result);
|
|
1504
|
+
const baseOrigin = new URL(request.url).origin;
|
|
1505
|
+
const redirect = result.authSuccess ? config?.successRedirect : config?.errorRedirect;
|
|
1506
|
+
if (!redirect) return Response.redirect(baseOrigin);
|
|
1507
|
+
try {
|
|
1508
|
+
const target = new URL(redirect, baseOrigin);
|
|
1509
|
+
if (!result.authSuccess) target.searchParams.set("error", result.authError);
|
|
1510
|
+
return Response.redirect(target);
|
|
1511
|
+
} catch (error) {
|
|
1512
|
+
console.error("Invalid OAuth callback redirect URL:", redirect, error);
|
|
1513
|
+
return Response.redirect(baseOrigin);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
//#endregion
|
|
1517
|
+
//#region src/mcp/client/server-lanes.ts
|
|
1518
|
+
const noop = () => {};
|
|
1519
|
+
const NO_LANES = /* @__PURE__ */ new Set();
|
|
1520
|
+
/** Call `fn`, turning a synchronous throw into a rejection. */
|
|
1521
|
+
function invoke(fn) {
|
|
1522
|
+
try {
|
|
1523
|
+
return fn();
|
|
1524
|
+
} catch (error) {
|
|
1525
|
+
return Promise.reject(error);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
/**
|
|
1529
|
+
* Rejection for lane work that was still queued when its server's lane was
|
|
1530
|
+
* forgotten (the server was removed or its connections closed).
|
|
1531
|
+
*/
|
|
1532
|
+
var ServerLaneCancelledError = class extends Error {
|
|
1533
|
+
/**
|
|
1534
|
+
* @param serverId - The server whose queued work was cancelled.
|
|
1535
|
+
*/
|
|
1536
|
+
constructor(serverId) {
|
|
1537
|
+
super(`Connection work for MCP server "${serverId}" was cancelled because the server was removed or closed`);
|
|
1538
|
+
this.serverId = serverId;
|
|
1539
|
+
this._tag = "ServerLaneCancelledError";
|
|
1540
|
+
this.name = "ServerLaneCancelledError";
|
|
1541
|
+
}
|
|
1542
|
+
};
|
|
1543
|
+
var _tails = /* @__PURE__ */ new WeakMap();
|
|
1544
|
+
var _generations = /* @__PURE__ */ new WeakMap();
|
|
1545
|
+
var _held = /* @__PURE__ */ new WeakMap();
|
|
1546
|
+
var _ServerLanes_brand = /* @__PURE__ */ new WeakSet();
|
|
1547
|
+
/**
|
|
1548
|
+
* One queue of connection work per MCP server. Work for the same server runs
|
|
1549
|
+
* one item at a time in submission order, so connect, discovery, OAuth
|
|
1550
|
+
* callback completion and restore never interleave on one connection; work
|
|
1551
|
+
* for different servers runs independently.
|
|
1552
|
+
*
|
|
1553
|
+
* Work is re-entrant: work that is already running for a server may call
|
|
1554
|
+
* other lane-wrapped operations for the same server, and they run inline
|
|
1555
|
+
* instead of queueing behind their caller. Callbacks that should not inherit
|
|
1556
|
+
* that permission (event listeners) run through {@link ServerLanes.outside}.
|
|
1557
|
+
*/
|
|
1558
|
+
var ServerLanes = class {
|
|
1559
|
+
constructor() {
|
|
1560
|
+
_classPrivateMethodInitSpec(this, _ServerLanes_brand);
|
|
1561
|
+
_classPrivateFieldInitSpec(this, _tails, /* @__PURE__ */ new Map());
|
|
1562
|
+
_classPrivateFieldInitSpec(this, _generations, /* @__PURE__ */ new Map());
|
|
1563
|
+
_classPrivateFieldInitSpec(this, _held, new AsyncLocalStorage());
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* Run `work` once every earlier item for `serverId` has settled.
|
|
1567
|
+
*
|
|
1568
|
+
* @param serverId - The server the work belongs to.
|
|
1569
|
+
* @param work - The work to run; its result or rejection is returned.
|
|
1570
|
+
*/
|
|
1571
|
+
run(serverId, work) {
|
|
1572
|
+
const held = _classPrivateFieldGet2(_held, this).getStore();
|
|
1573
|
+
if (held?.has(serverId)) return invoke(work);
|
|
1574
|
+
const lane = new Set(held);
|
|
1575
|
+
lane.add(serverId);
|
|
1576
|
+
const generation = _assertClassBrand(_ServerLanes_brand, this, _generation).call(this, serverId);
|
|
1577
|
+
const start = () => _assertClassBrand(_ServerLanes_brand, this, _generation).call(this, serverId) === generation ? _classPrivateFieldGet2(_held, this).run(lane, work) : Promise.reject(new ServerLaneCancelledError(serverId));
|
|
1578
|
+
const previous = _classPrivateFieldGet2(_tails, this).get(serverId);
|
|
1579
|
+
let release = noop;
|
|
1580
|
+
const tail = new Promise((resolve) => {
|
|
1581
|
+
release = resolve;
|
|
1582
|
+
});
|
|
1583
|
+
_classPrivateFieldGet2(_tails, this).set(serverId, tail);
|
|
1584
|
+
tail.then(() => {
|
|
1585
|
+
if (_classPrivateFieldGet2(_tails, this).get(serverId) === tail) _classPrivateFieldGet2(_tails, this).delete(serverId);
|
|
1586
|
+
});
|
|
1587
|
+
const result = previous ? previous.then(start) : invoke(start);
|
|
1588
|
+
result.then(release, release);
|
|
1589
|
+
return result;
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Resolve once no work is queued or running for `serverId`, including work
|
|
1593
|
+
* queued while earlier work settles. Resolves immediately when called from
|
|
1594
|
+
* that server's own work.
|
|
1595
|
+
*/
|
|
1596
|
+
async idle(serverId) {
|
|
1597
|
+
if (_classPrivateFieldGet2(_held, this).getStore()?.has(serverId)) return;
|
|
1598
|
+
while (true) {
|
|
1599
|
+
const tail = _classPrivateFieldGet2(_tails, this).get(serverId);
|
|
1600
|
+
if (!tail) return;
|
|
1601
|
+
await tail;
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
/** Settle-promises for the work queued right now, one per busy server. */
|
|
1605
|
+
pending() {
|
|
1606
|
+
return [..._classPrivateFieldGet2(_tails, this).values()];
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* Cancel a server's queue: work still waiting rejects with
|
|
1610
|
+
* {@link ServerLaneCancelledError}, and work already running keeps
|
|
1611
|
+
* running. Later work for the same id (a server added again) still waits
|
|
1612
|
+
* for that running work, so a late OAuth exchange cannot write over the
|
|
1613
|
+
* new server's flow.
|
|
1614
|
+
*/
|
|
1615
|
+
forget(serverId) {
|
|
1616
|
+
_classPrivateFieldGet2(_generations, this).set(serverId, _assertClassBrand(_ServerLanes_brand, this, _generation).call(this, serverId) + 1);
|
|
1617
|
+
}
|
|
1618
|
+
/** Drop every server's queue, as {@link ServerLanes.forget} does for one. */
|
|
1619
|
+
forgetAll() {
|
|
1620
|
+
for (const serverId of [..._classPrivateFieldGet2(_tails, this).keys()]) this.forget(serverId);
|
|
1621
|
+
}
|
|
1622
|
+
/** Run `fn` without the current work's re-entrant lane permission. */
|
|
1623
|
+
outside(fn) {
|
|
1624
|
+
return _classPrivateFieldGet2(_held, this).run(NO_LANES, fn);
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
function _generation(serverId) {
|
|
1628
|
+
return _classPrivateFieldGet2(_generations, this).get(serverId) ?? 0;
|
|
1629
|
+
}
|
|
1630
|
+
//#endregion
|
|
1631
|
+
//#region src/mcp/client/authorization.ts
|
|
1632
|
+
/**
|
|
1633
|
+
* Everything about authorization links: building OAuth providers, putting a
|
|
1634
|
+
* server into `authenticating` with a link (within the step-up round
|
|
1635
|
+
* limit), completing OAuth callbacks, turning a request's 401 or step-up
|
|
1636
|
+
* into `MCPAuthorizationRequiredError`.
|
|
1637
|
+
*
|
|
1638
|
+
* A waiting server keeps the link it was given until someone reconnects it.
|
|
1639
|
+
* Whether that link still works is up to the authorization server; the
|
|
1640
|
+
* callback reports it when it does not. Only a link whose callback was
|
|
1641
|
+
* already redeemed is never shown again.
|
|
1642
|
+
*/
|
|
1643
|
+
var AuthorizationController = class {
|
|
1644
|
+
constructor(ctx, status, resume) {
|
|
1645
|
+
this.ctx = ctx;
|
|
1646
|
+
this.status = status;
|
|
1647
|
+
this.resume = resume;
|
|
1648
|
+
this.spentStates = /* @__PURE__ */ new Map();
|
|
1649
|
+
this.liveStepUps = /* @__PURE__ */ new Map();
|
|
1650
|
+
}
|
|
1651
|
+
/** Build the OAuth provider for a server that has a callback URL. */
|
|
1652
|
+
createProvider(serverId, callbackUrl, clientName, clientId) {
|
|
1653
|
+
const provider = this.ctx.createAuthProvider?.(callbackUrl) ?? new DurableObjectOAuthClientProvider(this.ctx.storage, clientName, callbackUrl);
|
|
1654
|
+
provider.serverId = serverId;
|
|
1655
|
+
if (clientId) provider.clientId = clientId;
|
|
1656
|
+
return provider;
|
|
1657
|
+
}
|
|
1658
|
+
/** Rebuild a server's provider from its stored row, as restore does. */
|
|
1659
|
+
providerFromRow(row) {
|
|
1660
|
+
if (!row?.callback_url) return void 0;
|
|
1661
|
+
return this.createProvider(row.id, row.callback_url, this.ctx.name, row.client_id ?? void 0);
|
|
1662
|
+
}
|
|
1663
|
+
/**
|
|
1664
|
+
* Clear a server's saved OAuth state. This only deletes local state; it
|
|
1665
|
+
* does not revoke tokens at the OAuth provider.
|
|
1666
|
+
*/
|
|
1667
|
+
async clearStorage(serverId, provider) {
|
|
1668
|
+
try {
|
|
1669
|
+
if (provider instanceof DurableObjectOAuthClientProvider) await provider.clearServerStorage();
|
|
1670
|
+
else await provider.invalidateCredentials?.("all");
|
|
1671
|
+
} catch (error) {
|
|
1672
|
+
console.warn(`[MCPClientManager] Failed to clear OAuth credentials for ${serverId}:`, error);
|
|
1673
|
+
}
|
|
1674
|
+
}
|
|
1675
|
+
/**
|
|
1676
|
+
* Stop a provider from storing anything more, for work still running on a
|
|
1677
|
+
* connection that was replaced. Only the default provider can be retired.
|
|
1678
|
+
*/
|
|
1679
|
+
retire(provider) {
|
|
1680
|
+
if (provider instanceof DurableObjectOAuthClientProvider) provider.retire();
|
|
1681
|
+
}
|
|
1682
|
+
/** Let a retired provider store again: a new connection uses it. */
|
|
1683
|
+
revive(provider) {
|
|
1684
|
+
if (provider instanceof DurableObjectOAuthClientProvider) provider.revive();
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Move a connection to `authenticating` on the link its provider holds.
|
|
1688
|
+
* Every path that ends up waiting for the user (connect, discovery, and a
|
|
1689
|
+
* request that hits a scope step-up or a failed refresh) goes through
|
|
1690
|
+
* here, so the saved `auth_url`, the connection state and the broadcast
|
|
1691
|
+
* always agree, and the OAuth callback finds the connection in the state
|
|
1692
|
+
* it completes from.
|
|
1693
|
+
*
|
|
1694
|
+
* Changes nothing when the provider holds no usable link. Records a
|
|
1695
|
+
* permanent failure instead of a link once the server has asked for the
|
|
1696
|
+
* same authorization past the round limit.
|
|
1697
|
+
*/
|
|
1698
|
+
enterAuthenticating(id, conn, { stepUp = false } = {}) {
|
|
1699
|
+
if (this.ctx.connections[id] !== conn) return { _tag: "unavailable" };
|
|
1700
|
+
const provider = conn.options.transport.authProvider;
|
|
1701
|
+
const authUrl = provider?.authUrl;
|
|
1702
|
+
if (!provider || !authUrl || !provider.redirectUrl) return { _tag: "unavailable" };
|
|
1703
|
+
if (this.isSpent(id, authUrl)) return { _tag: "unavailable" };
|
|
1704
|
+
const round = startRound(parseAuthorizationRounds(this.ctx.store.authorizationRounds(id)), requestedScope(authUrl), Date.now(), stateOf(authUrl));
|
|
1705
|
+
if (round._tag === "exhausted") {
|
|
1706
|
+
const error = authorizationExhaustedMessage(round.rounds, round.scope);
|
|
1707
|
+
this.status.stop(id, "authorization-exhausted", error);
|
|
1708
|
+
return {
|
|
1709
|
+
_tag: "exhausted",
|
|
1710
|
+
error
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
const clientId = provider.clientId;
|
|
1714
|
+
this.ctx.store.setAuthContinuation(id, authUrl, clientId, stepUp);
|
|
1715
|
+
this.ctx.store.setAuthorizationRounds(id, round.rounds);
|
|
1716
|
+
this.ctx.store.clearFailure(id);
|
|
1717
|
+
conn.connectionState = MCPConnectionState.AUTHENTICATING;
|
|
1718
|
+
this.ctx.observability.fire({
|
|
1719
|
+
type: "mcp:client:authorize",
|
|
1720
|
+
payload: {
|
|
1721
|
+
serverId: id,
|
|
1722
|
+
authUrl,
|
|
1723
|
+
clientId
|
|
1724
|
+
},
|
|
1725
|
+
timestamp: Date.now()
|
|
1726
|
+
});
|
|
1727
|
+
this.ctx.stateChanged();
|
|
1728
|
+
return {
|
|
1729
|
+
_tag: "authenticating",
|
|
1730
|
+
authUrl,
|
|
1731
|
+
clientId
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
/** Why a 401 left no link to show, for the recorded failure. */
|
|
1735
|
+
noLinkReason(id, conn) {
|
|
1736
|
+
const provider = conn.options.transport.authProvider;
|
|
1737
|
+
if (provider?.authUrl && this.isSpent(id, provider.authUrl)) return "The server still answers 401 after a completed authorization";
|
|
1738
|
+
if (!provider) return "The server rejected the request (401 Unauthorized). Check the credentials sent with it, or, if the server uses OAuth, pass callbackHost to addMcpServer() (a callbackUrl to registerServer()) so the user can be asked.";
|
|
1739
|
+
if (!provider.redirectUrl) return "The server requires authorization, but the OAuth provider has no redirect URL to send the user back to.";
|
|
1740
|
+
return "The server rejected the credentials, and no new authorization link was produced";
|
|
1741
|
+
}
|
|
1742
|
+
/** The link a waiting server was given: the live one, else the stored one. */
|
|
1743
|
+
pendingLink(id, conn) {
|
|
1744
|
+
return usableAuthUrl(conn.options.transport.authProvider?.authUrl) ?? usableAuthUrl(this.ctx.store.get(id)?.auth_url);
|
|
1745
|
+
}
|
|
1746
|
+
/** Forget a server's link and step-up budget, for an explicit reconnect. */
|
|
1747
|
+
forget(id) {
|
|
1748
|
+
this.ctx.store.clearAuthUrl(id);
|
|
1749
|
+
this.ctx.store.setAuthorizationRounds(id, void 0);
|
|
1750
|
+
this.liveStepUps.delete(id);
|
|
1751
|
+
}
|
|
1752
|
+
/**
|
|
1753
|
+
* The server was renamed from `oldId` to `newId` (migrateServerId). Move
|
|
1754
|
+
* what is kept by id. A link it was waiting on names the old id in its
|
|
1755
|
+
* state, so that link's callback can never reach the server: abandon the
|
|
1756
|
+
* flow. A step-up goes back to the session's state, and anything else
|
|
1757
|
+
* connects again under the new id when it is settled.
|
|
1758
|
+
*/
|
|
1759
|
+
renamed(oldId, newId, conn) {
|
|
1760
|
+
const spent = this.spentStates.get(oldId);
|
|
1761
|
+
this.spentStates.delete(oldId);
|
|
1762
|
+
if (spent !== void 0) this.spentStates.set(newId, spent);
|
|
1763
|
+
const stepUp = this.liveStepUps.get(oldId);
|
|
1764
|
+
this.liveStepUps.delete(oldId);
|
|
1765
|
+
const waiting = conn?.connectionState === MCPConnectionState.AUTHENTICATING;
|
|
1766
|
+
if (!waiting && !this.ctx.store.get(newId)?.auth_url) return;
|
|
1767
|
+
this.ctx.store.clearAuthUrl(newId);
|
|
1768
|
+
if (conn && waiting) conn.connectionState = stepUp?.conn === conn ? stepUp.stateBefore : MCPConnectionState.CONNECTING;
|
|
1769
|
+
}
|
|
1770
|
+
isLiveStepUp(id, conn) {
|
|
1771
|
+
return this.liveStepUps.get(id)?.conn === conn;
|
|
1772
|
+
}
|
|
1773
|
+
/**
|
|
1774
|
+
* The user declined a step-up: the session still holds its earlier grant,
|
|
1775
|
+
* so go back to where it was instead of failing the server. The next
|
|
1776
|
+
* request that needs the scope asks again.
|
|
1777
|
+
*/
|
|
1778
|
+
declineStepUp(serverId, conn, error) {
|
|
1779
|
+
const stepUp = this.liveStepUps.get(serverId);
|
|
1780
|
+
this.liveStepUps.delete(serverId);
|
|
1781
|
+
this.ctx.store.clearAuthUrl(serverId);
|
|
1782
|
+
conn.connectionState = stepUp?.stateBefore ?? MCPConnectionState.READY;
|
|
1783
|
+
conn.connectionError = null;
|
|
1784
|
+
this.ctx.stateChanged();
|
|
1785
|
+
return {
|
|
1786
|
+
serverId,
|
|
1787
|
+
authSuccess: false,
|
|
1788
|
+
authError: error
|
|
1789
|
+
};
|
|
1790
|
+
}
|
|
1791
|
+
isSpent(id, authUrl) {
|
|
1792
|
+
const spent = this.spentStates.get(id);
|
|
1793
|
+
return spent !== void 0 && stateOf(authUrl) === spent;
|
|
1794
|
+
}
|
|
1795
|
+
/**
|
|
1796
|
+
* Run a request on an established connection and surface mid-session
|
|
1797
|
+
* re-authorization.
|
|
1798
|
+
*
|
|
1799
|
+
* A request can fail after connect with `403 insufficient_scope` (scope
|
|
1800
|
+
* step-up) or a `401` whose refresh fails. The SDK then hands a new link
|
|
1801
|
+
* to the provider and throws `UnauthorizedError`. Left as is, nobody sees
|
|
1802
|
+
* that link, and its callback is ignored as stale because the connection
|
|
1803
|
+
* is still `ready`. Enter `authenticating` with it instead, as the connect
|
|
1804
|
+
* path does, and throw `MCPAuthorizationRequiredError`.
|
|
1805
|
+
*/
|
|
1806
|
+
async recoverRequest(serverId, request) {
|
|
1807
|
+
const conn = this.ctx.connections[serverId];
|
|
1808
|
+
if (!conn) throw new MCPConnectionNotFoundError(serverId);
|
|
1809
|
+
if (conn.connectionState === MCPConnectionState.AUTHENTICATING && !this.isLiveStepUp(serverId, conn)) {
|
|
1810
|
+
const authUrl = this.pendingLink(serverId, conn);
|
|
1811
|
+
if (authUrl) throw new MCPAuthorizationRequiredError(serverId, authUrl, { clientId: conn.options.transport.authProvider?.clientId });
|
|
1812
|
+
}
|
|
1813
|
+
const authUrlBefore = conn.options.transport.authProvider?.authUrl;
|
|
1814
|
+
const sessionBefore = conn.session;
|
|
1815
|
+
try {
|
|
1816
|
+
return await request(conn);
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
throw await this.authorizationRequired(serverId, conn, error, authUrlBefore, sessionBefore) ?? error;
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
async authorizationRequired(serverId, conn, error, authUrlBefore, sessionBefore) {
|
|
1822
|
+
const canTakeOver = () => {
|
|
1823
|
+
if (this.ctx.connections[serverId] !== conn) return false;
|
|
1824
|
+
if (conn.session !== sessionBefore) return false;
|
|
1825
|
+
const state = conn.connectionState;
|
|
1826
|
+
return state === MCPConnectionState.READY || state === MCPConnectionState.CONNECTED || state === MCPConnectionState.AUTHENTICATING;
|
|
1827
|
+
};
|
|
1828
|
+
if (!canTakeOver() || !isUnauthorized(error)) return void 0;
|
|
1829
|
+
const provider = conn.options.transport.authProvider;
|
|
1830
|
+
const authUrl = provider?.authUrl;
|
|
1831
|
+
if (!provider || !authUrl || authUrl === authUrlBefore) return void 0;
|
|
1832
|
+
const stateBefore = conn.connectionState;
|
|
1833
|
+
if (!await isLive(serverId, authUrl, provider)) return void 0;
|
|
1834
|
+
const stepUp = await holdsGrant(provider);
|
|
1835
|
+
if (!canTakeOver() || conn.connectionState !== stateBefore || provider.authUrl !== authUrl) return;
|
|
1836
|
+
const auth = this.enterAuthenticating(serverId, conn, { stepUp });
|
|
1837
|
+
if (auth._tag !== "authenticating") return void 0;
|
|
1838
|
+
if (!stepUp) this.liveStepUps.delete(serverId);
|
|
1839
|
+
else if (stateBefore !== MCPConnectionState.AUTHENTICATING) this.liveStepUps.set(serverId, {
|
|
1840
|
+
conn,
|
|
1841
|
+
stateBefore
|
|
1842
|
+
});
|
|
1843
|
+
return new MCPAuthorizationRequiredError(serverId, auth.authUrl, {
|
|
1844
|
+
clientId: auth.clientId,
|
|
1845
|
+
cause: error
|
|
1846
|
+
});
|
|
1847
|
+
}
|
|
1848
|
+
configureCallback(config) {
|
|
1849
|
+
this.callbackConfig = config;
|
|
1850
|
+
}
|
|
1851
|
+
getCallbackConfig() {
|
|
1852
|
+
return this.callbackConfig;
|
|
1853
|
+
}
|
|
1854
|
+
/** Whether a request is an OAuth callback for one of these servers. */
|
|
1855
|
+
isCallback(request) {
|
|
1856
|
+
return isOAuthCallbackFor(request, this.ctx.store.list());
|
|
1857
|
+
}
|
|
1858
|
+
/**
|
|
1859
|
+
* Complete the OAuth flow a callback belongs to: verify its state,
|
|
1860
|
+
* exchange its code, and leave the connection ready to reconnect. A
|
|
1861
|
+
* callback for a flow already accepted is consumed as a stale success;
|
|
1862
|
+
* one whose state cannot be verified changes nothing.
|
|
1863
|
+
*/
|
|
1864
|
+
async handleCallback(request) {
|
|
1865
|
+
const serverId = serverIdFromState(new URL(request.url).searchParams.get("state"));
|
|
1866
|
+
if (!serverId) return this.completeCallback(request);
|
|
1867
|
+
return this.ctx.lanes.run(serverId, () => this.completeCallback(request)).catch((error) => {
|
|
1868
|
+
if (error instanceof ServerLaneCancelledError) return this.gone(serverId);
|
|
1869
|
+
throw error;
|
|
1870
|
+
});
|
|
1871
|
+
}
|
|
1872
|
+
async completeCallback(request) {
|
|
1873
|
+
const callback = parseOAuthCallback(request, {
|
|
1874
|
+
hasServer: (id) => this.ctx.store.get(id) !== void 0,
|
|
1875
|
+
hasConnection: (id) => this.ctx.connections[id] !== void 0
|
|
1876
|
+
});
|
|
1877
|
+
if (callback._tag === "invalid") {
|
|
1878
|
+
const conn = callback.serverId ? this.ctx.connections[callback.serverId] : void 0;
|
|
1879
|
+
if (!callback.serverId || !conn) return {
|
|
1880
|
+
serverId: callback.serverId,
|
|
1881
|
+
authSuccess: false,
|
|
1882
|
+
authError: callback.error
|
|
1883
|
+
};
|
|
1884
|
+
const provider = conn.options.transport.authProvider;
|
|
1885
|
+
if (isPastAuthorization(conn)) {
|
|
1886
|
+
if (callback.state && provider) await consumeStaleState(callback.serverId, provider, callback.state);
|
|
1887
|
+
return this.staleSuccess(callback.serverId, conn);
|
|
1888
|
+
}
|
|
1889
|
+
if (callback.state && provider && !await isRedeemableState(callback.serverId, provider, callback.state)) return ignoreUnverified(callback.serverId, callback.error);
|
|
1890
|
+
if (this.ctx.connections[callback.serverId] !== conn) return this.gone(callback.serverId);
|
|
1891
|
+
return this.fail(callback.serverId, callback.error);
|
|
1892
|
+
}
|
|
1893
|
+
const { serverId, state, params } = callback;
|
|
1894
|
+
const conn = this.ctx.connections[serverId];
|
|
1895
|
+
try {
|
|
1896
|
+
const provider = conn.options.transport.authProvider;
|
|
1897
|
+
if (!provider) throw new Error("Trying to finalize authentication for a server connection without an authProvider");
|
|
1898
|
+
provider.serverId = serverId;
|
|
1899
|
+
const validation = await provider.checkState(state);
|
|
1900
|
+
if (!validation.valid) {
|
|
1901
|
+
if (isPastAuthorization(conn)) {
|
|
1902
|
+
await consumeStaleState(serverId, provider, state);
|
|
1903
|
+
return this.staleSuccess(serverId, conn);
|
|
1904
|
+
}
|
|
1905
|
+
return ignoreUnverified(serverId, params.get("error_description") ?? params.get("error") ?? validation.error ?? "Invalid state");
|
|
1906
|
+
}
|
|
1907
|
+
if (isPastAuthorization(conn)) {
|
|
1908
|
+
await consumeStaleState(serverId, provider, state);
|
|
1909
|
+
return this.staleSuccess(serverId, conn);
|
|
1910
|
+
}
|
|
1911
|
+
if (conn.connectionState !== MCPConnectionState.AUTHENTICATING && conn.connectionState !== MCPConnectionState.FAILED) throw new Error(`Failed to authenticate from "${conn.connectionState}" state`);
|
|
1912
|
+
const declined = params.get("error");
|
|
1913
|
+
if (declined && this.isLiveStepUp(serverId, conn)) {
|
|
1914
|
+
await consumeStaleState(serverId, provider, state);
|
|
1915
|
+
return this.declineStepUp(serverId, conn, declined);
|
|
1916
|
+
}
|
|
1917
|
+
if (declined && this.ctx.store.isPendingStepUp(serverId)) {
|
|
1918
|
+
await consumeStaleState(serverId, provider, state);
|
|
1919
|
+
this.ctx.store.clearAuthUrl(serverId);
|
|
1920
|
+
conn.connectionState = MCPConnectionState.CONNECTING;
|
|
1921
|
+
conn.connectionError = null;
|
|
1922
|
+
this.ctx.stateChanged();
|
|
1923
|
+
this.ctx.lanes.outside(() => this.resume(serverId));
|
|
1924
|
+
return {
|
|
1925
|
+
serverId,
|
|
1926
|
+
authSuccess: false,
|
|
1927
|
+
authError: declined
|
|
1928
|
+
};
|
|
1929
|
+
}
|
|
1930
|
+
conn.connectionState = MCPConnectionState.CONNECTING;
|
|
1931
|
+
this.ctx.store.clearAuthUrl(serverId);
|
|
1932
|
+
this.liveStepUps.delete(serverId);
|
|
1933
|
+
this.spentStates.set(serverId, state);
|
|
1934
|
+
await provider.consumeState(state);
|
|
1935
|
+
await exchangeAuthorizationCode(serverId, conn, provider, state, params);
|
|
1936
|
+
if (this.ctx.connections[serverId] !== conn) {
|
|
1937
|
+
if (this.ctx.connections[serverId]) {
|
|
1938
|
+
await provider.invalidateCredentials?.("tokens");
|
|
1939
|
+
return this.gone(serverId);
|
|
1940
|
+
}
|
|
1941
|
+
if (this.isClosed(serverId)) {
|
|
1942
|
+
this.ctx.store.setAuthorizationRounds(serverId, completeRound(parseAuthorizationRounds(this.ctx.store.authorizationRounds(serverId)), state));
|
|
1943
|
+
this.ctx.store.clearAuthUrl(serverId);
|
|
1944
|
+
return {
|
|
1945
|
+
serverId,
|
|
1946
|
+
authSuccess: true
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
await this.clearStorage(serverId, provider);
|
|
1950
|
+
return removedDuringAuthorization(serverId);
|
|
1951
|
+
}
|
|
1952
|
+
this.status.saveSession(serverId, conn);
|
|
1953
|
+
this.ctx.store.setAuthorizationRounds(serverId, completeRound(parseAuthorizationRounds(this.ctx.store.authorizationRounds(serverId)), state));
|
|
1954
|
+
const result = this.success(serverId, conn);
|
|
1955
|
+
this.ctx.stateChanged();
|
|
1956
|
+
return result;
|
|
1957
|
+
} catch (error) {
|
|
1958
|
+
if (this.ctx.connections[serverId] !== conn) return this.gone(serverId);
|
|
1959
|
+
return this.fail(serverId, toErrorMessage(error));
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
/**
|
|
1963
|
+
* The user denied the authorization or its code could not be exchanged.
|
|
1964
|
+
* Recorded, so a later wake does not start another flow nobody asked for.
|
|
1965
|
+
*/
|
|
1966
|
+
fail(serverId, error) {
|
|
1967
|
+
this.liveStepUps.delete(serverId);
|
|
1968
|
+
if (this.ctx.store.get(serverId)) this.status.stop(serverId, "authorization-failed", error);
|
|
1969
|
+
else if (this.ctx.connections[serverId]) {
|
|
1970
|
+
this.ctx.connections[serverId].connectionState = MCPConnectionState.FAILED;
|
|
1971
|
+
this.ctx.connections[serverId].connectionError = error;
|
|
1972
|
+
this.ctx.stateChanged();
|
|
1973
|
+
}
|
|
1974
|
+
return {
|
|
1975
|
+
serverId,
|
|
1976
|
+
authSuccess: false,
|
|
1977
|
+
authError: error
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
1980
|
+
/**
|
|
1981
|
+
* Success for a callback whose flow was already accepted, unless the
|
|
1982
|
+
* server was removed while its state was cleaned up.
|
|
1983
|
+
*/
|
|
1984
|
+
staleSuccess(serverId, conn) {
|
|
1985
|
+
if (this.ctx.connections[serverId] !== conn) return this.gone(serverId);
|
|
1986
|
+
return this.success(serverId, conn);
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* Whether a server whose connection is gone is still stored and not being
|
|
1990
|
+
* removed: its connection was closed (closeConnection), or closed and
|
|
1991
|
+
* registered again.
|
|
1992
|
+
*/
|
|
1993
|
+
isClosed(serverId) {
|
|
1994
|
+
return this.ctx.store.get(serverId) !== void 0 && !this.ctx.removing.has(serverId);
|
|
1995
|
+
}
|
|
1996
|
+
/**
|
|
1997
|
+
* Result for a callback whose connection went away while it was handled:
|
|
1998
|
+
* the server was registered again, closed, or removed.
|
|
1999
|
+
*/
|
|
2000
|
+
gone(serverId) {
|
|
2001
|
+
const what = this.ctx.connections[serverId] ? "replaced" : this.isClosed(serverId) ? "closed" : void 0;
|
|
2002
|
+
if (!what) return removedDuringAuthorization(serverId);
|
|
2003
|
+
return {
|
|
2004
|
+
serverId,
|
|
2005
|
+
authSuccess: false,
|
|
2006
|
+
authError: `The connection to server ${serverId} was ${what} during authorization`
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
success(serverId, conn) {
|
|
2010
|
+
this.ctx.store.clearAuthUrl(serverId);
|
|
2011
|
+
conn.connectionError = null;
|
|
2012
|
+
return {
|
|
2013
|
+
serverId,
|
|
2014
|
+
authSuccess: true
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
};
|
|
2018
|
+
/** Whether a connection's flow was already accepted by a callback. */
|
|
2019
|
+
function isPastAuthorization(conn) {
|
|
2020
|
+
return conn.connectionState === MCPConnectionState.READY || conn.connectionState === MCPConnectionState.CONNECTED || conn.connectionState === MCPConnectionState.CONNECTING || conn.connectionState === MCPConnectionState.DISCOVERING;
|
|
2021
|
+
}
|
|
2022
|
+
function ignoreUnverified(serverId, error) {
|
|
2023
|
+
console.warn(`[MCPClientManager] Ignoring OAuth callback with unverified state for server "${serverId}": ${error}`);
|
|
2024
|
+
return {
|
|
2025
|
+
serverId,
|
|
2026
|
+
authSuccess: false,
|
|
2027
|
+
authError: error
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
/** Result for a callback whose server was removed while it was handled. */
|
|
2031
|
+
function removedDuringAuthorization(serverId) {
|
|
2032
|
+
return {
|
|
2033
|
+
serverId,
|
|
2034
|
+
authSuccess: false,
|
|
2035
|
+
authError: `Server ${serverId} was removed during authorization`
|
|
2036
|
+
};
|
|
2037
|
+
}
|
|
2038
|
+
/** Whether a link's `state` can still be redeemed. */
|
|
2039
|
+
async function isLive(serverId, authUrl, provider) {
|
|
2040
|
+
const state = stateOf(authUrl);
|
|
2041
|
+
return state ? isRedeemableState(serverId, provider, state) : false;
|
|
2042
|
+
}
|
|
2043
|
+
/** Whether the provider still has tokens stored. */
|
|
2044
|
+
async function holdsGrant(provider) {
|
|
2045
|
+
try {
|
|
2046
|
+
return await provider.tokens() !== void 0;
|
|
2047
|
+
} catch {
|
|
2048
|
+
return false;
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
function stateOf(authUrl) {
|
|
2052
|
+
try {
|
|
2053
|
+
return new URL(authUrl).searchParams.get("state");
|
|
2054
|
+
} catch {
|
|
2055
|
+
return null;
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
//#endregion
|
|
2059
|
+
//#region src/mcp/client/elicitation.ts
|
|
2060
|
+
/**
|
|
2061
|
+
* The manager's elicitation handlers, held in memory only, and what they
|
|
2062
|
+
* make each connection advertise. Advertised modes are stamped on every
|
|
2063
|
+
* stored server so a restore re-advertises them before the handlers are
|
|
2064
|
+
* configured again.
|
|
2065
|
+
*/
|
|
2066
|
+
var ElicitationHandlers = class {
|
|
2067
|
+
constructor(ctx) {
|
|
2068
|
+
this.ctx = ctx;
|
|
2069
|
+
}
|
|
2070
|
+
/** Whether any handler is configured. */
|
|
2071
|
+
get configured() {
|
|
2072
|
+
return this.handlers !== void 0;
|
|
2073
|
+
}
|
|
2074
|
+
/** Replace the handlers and apply them to every live connection. */
|
|
2075
|
+
configure(handlers) {
|
|
2076
|
+
this.handlers = handlers && (handlers.form || handlers.url) ? handlers : void 0;
|
|
2077
|
+
this.ctx.store.stampCapabilities(this.capabilities());
|
|
2078
|
+
for (const [id, connection] of Object.entries(this.ctx.connections)) connection.configureElicitationHandlers(this.scopedTo(id));
|
|
2079
|
+
}
|
|
2080
|
+
/** Client capabilities advertised from the configured handlers. */
|
|
2081
|
+
capabilities() {
|
|
2082
|
+
const elicitation = elicitationCapabilitiesFromHandlers(this.handlers);
|
|
2083
|
+
return elicitation ? { elicitation } : void 0;
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
2086
|
+
* The handlers bound to one server id. Undefined when none are configured,
|
|
2087
|
+
* so the connection keeps its default throwing behaviour.
|
|
2088
|
+
*/
|
|
2089
|
+
scopedTo(serverId) {
|
|
2090
|
+
const handlers = this.handlers;
|
|
2091
|
+
if (!handlers) return void 0;
|
|
2092
|
+
const { form, url } = handlers;
|
|
2093
|
+
return {
|
|
2094
|
+
form: form ? (request, signal) => signal ? form(request, serverId, signal) : form(request, serverId) : void 0,
|
|
2095
|
+
url: url ? (request, signal) => signal ? url(request, serverId, signal) : url(request, serverId) : void 0
|
|
2096
|
+
};
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
2099
|
+
//#endregion
|
|
2100
|
+
//#region src/mcp/client/storage.ts
|
|
2101
|
+
/** Create the durable MCP server catalog table when it does not exist. */
|
|
2102
|
+
function ensureMcpServerTable(storage) {
|
|
2103
|
+
storage.sql.exec(`
|
|
2104
|
+
CREATE TABLE IF NOT EXISTS cf_agents_mcp_servers (
|
|
2105
|
+
id TEXT PRIMARY KEY NOT NULL,
|
|
2106
|
+
name TEXT NOT NULL,
|
|
2107
|
+
server_url TEXT NOT NULL,
|
|
2108
|
+
callback_url TEXT NOT NULL,
|
|
2109
|
+
client_id TEXT,
|
|
2110
|
+
auth_url TEXT,
|
|
2111
|
+
server_options TEXT
|
|
2112
|
+
)
|
|
2113
|
+
`);
|
|
2114
|
+
}
|
|
2115
|
+
function persistClientOptions(client) {
|
|
2116
|
+
if (!client) return void 0;
|
|
2117
|
+
return {
|
|
2118
|
+
capabilities: client.capabilities,
|
|
2119
|
+
supportedProtocolVersions: client.supportedProtocolVersions,
|
|
2120
|
+
enforceStrictCapabilities: client.enforceStrictCapabilities,
|
|
2121
|
+
debouncedNotificationMethods: client.debouncedNotificationMethods,
|
|
2122
|
+
versionNegotiation: client.versionNegotiation,
|
|
2123
|
+
inputRequired: client.inputRequired,
|
|
2124
|
+
listMaxPages: client.listMaxPages,
|
|
2125
|
+
cachePartition: client.cachePartition,
|
|
2126
|
+
defaultCacheTtlMs: client.defaultCacheTtlMs
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
/**
|
|
2130
|
+
* Headers as a plain record, so they survive JSON: a `Headers` instance
|
|
2131
|
+
* would be stored as `{}`.
|
|
2132
|
+
*/
|
|
2133
|
+
function persistHeaders(headers) {
|
|
2134
|
+
return headers ? Object.fromEntries(new Headers(headers)) : void 0;
|
|
2135
|
+
}
|
|
2136
|
+
function persistTransportOptions(value) {
|
|
2137
|
+
if (!value) return void 0;
|
|
2138
|
+
return {
|
|
2139
|
+
type: value.type,
|
|
2140
|
+
headers: persistHeaders(value.headers),
|
|
2141
|
+
requestInit: value.requestInit && {
|
|
2142
|
+
...value.requestInit,
|
|
2143
|
+
headers: persistHeaders(value.requestInit.headers)
|
|
2144
|
+
},
|
|
2145
|
+
reconnectionOptions: value.reconnectionOptions,
|
|
2146
|
+
skipIssuerMetadataValidation: value.skipIssuerMetadataValidation,
|
|
2147
|
+
onInsufficientScope: value.onInsufficientScope,
|
|
2148
|
+
maxStepUpRetries: value.maxStepUpRetries,
|
|
2149
|
+
sessionId: value.sessionId,
|
|
2150
|
+
protocolVersion: value.protocolVersion
|
|
2151
|
+
};
|
|
2152
|
+
}
|
|
2153
|
+
function encodeMcpServerOptions(options) {
|
|
2154
|
+
return JSON.stringify({
|
|
2155
|
+
client: persistClientOptions(options.client),
|
|
2156
|
+
transport: persistTransportOptions(options.transport),
|
|
2157
|
+
discoverResult: options.discoverResult,
|
|
2158
|
+
retry: options.retry,
|
|
2159
|
+
bindingName: options.bindingName,
|
|
2160
|
+
props: options.props,
|
|
2161
|
+
capabilities: options.capabilities
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
function decodeMcpServerOptions(value) {
|
|
2165
|
+
if (!value) return {};
|
|
2166
|
+
const parsed = JSON.parse(value);
|
|
2167
|
+
const transport = persistTransportOptions(parsed.transport);
|
|
2168
|
+
const statelessWithoutPrior = transport?.protocolVersion === "2026-07-28" && !parsed.discoverResult;
|
|
2169
|
+
if (transport?.sessionId && (!transport.protocolVersion || statelessWithoutPrior)) {
|
|
2170
|
+
delete transport.sessionId;
|
|
2171
|
+
delete transport.protocolVersion;
|
|
2172
|
+
delete parsed.discoverResult;
|
|
2173
|
+
}
|
|
2174
|
+
return {
|
|
2175
|
+
client: persistClientOptions(parsed.client),
|
|
2176
|
+
transport,
|
|
2177
|
+
discoverResult: parsed.discoverResult,
|
|
2178
|
+
retry: parsed.retry,
|
|
2179
|
+
...parsed.bindingName !== void 0 && { bindingName: parsed.bindingName },
|
|
2180
|
+
...parsed.props !== void 0 && { props: parsed.props },
|
|
2181
|
+
capabilities: parsed.capabilities
|
|
2182
|
+
};
|
|
2183
|
+
}
|
|
2184
|
+
function withMcpSession(options, session) {
|
|
2185
|
+
const transport = { ...options.transport ?? {} };
|
|
2186
|
+
if (!session) {
|
|
2187
|
+
delete transport.sessionId;
|
|
2188
|
+
delete transport.protocolVersion;
|
|
2189
|
+
const next = {
|
|
2190
|
+
...options,
|
|
2191
|
+
transport
|
|
2192
|
+
};
|
|
2193
|
+
delete next.discoverResult;
|
|
2194
|
+
return next;
|
|
2195
|
+
}
|
|
2196
|
+
transport.sessionId = session.id;
|
|
2197
|
+
transport.protocolVersion = session.protocolVersion;
|
|
2198
|
+
return {
|
|
2199
|
+
...options,
|
|
2200
|
+
transport,
|
|
2201
|
+
...session.discoverResult ? { discoverResult: session.discoverResult } : { discoverResult: void 0 }
|
|
2202
|
+
};
|
|
2203
|
+
}
|
|
2204
|
+
//#endregion
|
|
2205
|
+
//#region src/mcp/client/rpc.ts
|
|
2206
|
+
/**
|
|
2207
|
+
* Build the RPC transport for a stored server by resolving its Durable
|
|
2208
|
+
* Object binding from `env` by the binding name persisted with the server.
|
|
2209
|
+
*/
|
|
2210
|
+
function resolveRpcTransport(env, server) {
|
|
2211
|
+
if (!env) return {
|
|
2212
|
+
_tag: "unresolved",
|
|
2213
|
+
reason: "no env was provided; pass { env } when constructing MCPClientManager"
|
|
2214
|
+
};
|
|
2215
|
+
const options = decodeMcpServerOptions(server.server_options);
|
|
2216
|
+
const binding = options.bindingName ? Object.entries(env).find(([name]) => name === options.bindingName)?.[1] : void 0;
|
|
2217
|
+
if (!isDurableObjectNamespace(binding)) return {
|
|
2218
|
+
_tag: "unresolved",
|
|
2219
|
+
reason: `binding "${options.bindingName ?? "<missing>"}" not found in env`
|
|
2220
|
+
};
|
|
2221
|
+
return {
|
|
2222
|
+
_tag: "resolved",
|
|
2223
|
+
transport: {
|
|
2224
|
+
type: "rpc",
|
|
2225
|
+
namespace: binding,
|
|
2226
|
+
name: server.server_url.replace(RPC_DO_PREFIX, ""),
|
|
2227
|
+
props: options.props
|
|
2228
|
+
}
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
//#endregion
|
|
2232
|
+
//#region src/mcp/client/url-policy.ts
|
|
2233
|
+
/**
|
|
2234
|
+
* Rules for the identifiers and URLs the MCP client manager accepts: stable
|
|
2235
|
+
* server ids, and the SSRF policy that keeps HTTP connections off private
|
|
2236
|
+
* and internal networks.
|
|
2237
|
+
*/
|
|
2238
|
+
/** Maximum length of a normalized MCP server id. */
|
|
2239
|
+
const MCP_SERVER_ID_MAX_LENGTH = 64;
|
|
2240
|
+
/**
|
|
2241
|
+
* Normalize a caller-supplied MCP server id into a stable, storage- and
|
|
2242
|
+
* tool-name-safe form.
|
|
2243
|
+
*
|
|
2244
|
+
* The id is surfaced in several places where the character set matters:
|
|
2245
|
+
* - as the primary key in the `cf_agents_mcp_servers` SQLite table
|
|
2246
|
+
* - embedded in AI SDK tool names as `` `tool_${id.replace(/-/g, "")}_${tool}` ``
|
|
2247
|
+
* (tool names must match `/^[A-Za-z0-9_]+$/`)
|
|
2248
|
+
* - as a key on the `mcpConnections` map and OAuth provider storage
|
|
2249
|
+
*
|
|
2250
|
+
* Rules:
|
|
2251
|
+
* 1. Lowercase.
|
|
2252
|
+
* 2. Replace any run of disallowed characters with a single `-`.
|
|
2253
|
+
* 3. Collapse repeated `-` and trim leading/trailing `-`/`_`.
|
|
2254
|
+
* 4. Prefix with `id-` if the result is empty or doesn't start with a letter.
|
|
2255
|
+
* 5. Truncate to {@link MCP_SERVER_ID_MAX_LENGTH} characters.
|
|
2256
|
+
*
|
|
2257
|
+
* @example
|
|
2258
|
+
* normalizeServerId("my-supplied-id"); // "my-supplied-id"
|
|
2259
|
+
* normalizeServerId("GitHub MCP!"); // "github-mcp"
|
|
2260
|
+
* normalizeServerId("42-things"); // "id-42-things"
|
|
2261
|
+
*/
|
|
2262
|
+
function normalizeServerId(input) {
|
|
2263
|
+
if (typeof input !== "string") throw new TypeError(`normalizeServerId: expected string, got ${typeof input}`);
|
|
2264
|
+
let id = input.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, "");
|
|
2265
|
+
if (id.length === 0 || !/^[a-z]/.test(id)) id = `id-${id}`.replace(/-+$/g, "");
|
|
2266
|
+
if (id.length > 64) id = id.slice(0, 64).replace(/-+$/g, "");
|
|
2267
|
+
return id;
|
|
2268
|
+
}
|
|
2269
|
+
/**
|
|
2270
|
+
* Blocked hostname patterns for SSRF protection.
|
|
2271
|
+
* Prevents MCP client from connecting to internal/private network addresses
|
|
2272
|
+
* while allowing loopback hosts for local development.
|
|
2273
|
+
*/
|
|
2274
|
+
const BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
|
|
2275
|
+
"0.0.0.0",
|
|
2276
|
+
"[::]",
|
|
2277
|
+
"metadata.google.internal"
|
|
2278
|
+
]);
|
|
2279
|
+
/**
|
|
2280
|
+
* Check whether four IPv4 octets belong to a private/reserved range.
|
|
2281
|
+
* Blocks RFC 1918, link-local, cloud metadata, and unspecified addresses.
|
|
2282
|
+
*/
|
|
2283
|
+
function isPrivateIPv4(octets) {
|
|
2284
|
+
const [a, b] = octets;
|
|
2285
|
+
if (a === 10) return true;
|
|
2286
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
2287
|
+
if (a === 192 && b === 168) return true;
|
|
2288
|
+
if (a === 169 && b === 254) return true;
|
|
2289
|
+
if (a === 0) return true;
|
|
2290
|
+
return false;
|
|
2291
|
+
}
|
|
2292
|
+
/**
|
|
2293
|
+
* fe80::/10 — IPv6 link-local (RFC 4291 §2.5.6).
|
|
2294
|
+
*
|
|
2295
|
+
* The /10 boundary fixes the first 10 bits (1111111010), which means valid
|
|
2296
|
+
* first hextets range from fe80 through febf. Only hex digits 8, 9, a, b
|
|
2297
|
+
* have high two bits "10" — anything else (e.g. fe7f, fec0) is out of range.
|
|
2298
|
+
* The fourth hex digit is unconstrained by the /10 boundary.
|
|
2299
|
+
*
|
|
2300
|
+
* Historical bug: `startsWith("fe80")` only matched the narrower fe80::/16
|
|
2301
|
+
* prefix and let fe81::/feab::/febf:: slip through. See issue #1325.
|
|
2302
|
+
*/
|
|
2303
|
+
const IPV6_LINK_LOCAL = /^fe[89ab][0-9a-f]/;
|
|
2304
|
+
/**
|
|
2305
|
+
* Check whether a bracket-stripped, lowercased IPv6 address belongs to a
|
|
2306
|
+
* private/reserved range. Also unwraps IPv4-mapped IPv6 (::ffff:...) and
|
|
2307
|
+
* delegates to isPrivateIPv4 for those.
|
|
2308
|
+
*
|
|
2309
|
+
* Loopback (::1) and unspecified (::) are NOT blocked here:
|
|
2310
|
+
* - ::1 is intentionally allowed (parallel to 127.x.x.x for local dev)
|
|
2311
|
+
* - :: (== [::]) is blocked via BLOCKED_HOSTNAMES at the hostname level
|
|
2312
|
+
*/
|
|
2313
|
+
function isPrivateIPv6(addr) {
|
|
2314
|
+
if (addr.startsWith("fc") || addr.startsWith("fd")) return true;
|
|
2315
|
+
if (IPV6_LINK_LOCAL.test(addr)) return true;
|
|
2316
|
+
if (addr.startsWith("::ffff:")) {
|
|
2317
|
+
const mapped = addr.slice(7);
|
|
2318
|
+
const dotParts = mapped.split(".");
|
|
2319
|
+
if (dotParts.length === 4 && dotParts.every((p) => /^\d{1,3}$/.test(p))) {
|
|
2320
|
+
if (isPrivateIPv4(dotParts.map(Number))) return true;
|
|
2321
|
+
} else {
|
|
2322
|
+
const hexParts = mapped.split(":");
|
|
2323
|
+
if (hexParts.length === 2) {
|
|
2324
|
+
const hi = parseInt(hexParts[0], 16);
|
|
2325
|
+
const lo = parseInt(hexParts[1], 16);
|
|
2326
|
+
if (isPrivateIPv4([
|
|
2327
|
+
hi >> 8 & 255,
|
|
2328
|
+
hi & 255,
|
|
2329
|
+
lo >> 8 & 255,
|
|
2330
|
+
lo & 255
|
|
2331
|
+
])) return true;
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
return false;
|
|
2336
|
+
}
|
|
2337
|
+
/**
|
|
2338
|
+
* Check whether a hostname looks like a private/internal IP address.
|
|
2339
|
+
* Blocks RFC 1918, link-local, unique-local, unspecified,
|
|
2340
|
+
* and cloud metadata endpoints. Also detects IPv4-mapped IPv6 addresses.
|
|
2341
|
+
*/
|
|
2342
|
+
function isBlockedUrl(url) {
|
|
2343
|
+
let parsed;
|
|
2344
|
+
try {
|
|
2345
|
+
parsed = new URL(url);
|
|
2346
|
+
} catch {
|
|
2347
|
+
return true;
|
|
2348
|
+
}
|
|
2349
|
+
const hostname = parsed.hostname;
|
|
2350
|
+
if (BLOCKED_HOSTNAMES.has(hostname)) return true;
|
|
2351
|
+
const ipv4Parts = hostname.split(".");
|
|
2352
|
+
if (ipv4Parts.length === 4 && ipv4Parts.every((p) => /^\d{1,3}$/.test(p))) {
|
|
2353
|
+
if (isPrivateIPv4(ipv4Parts.map(Number))) return true;
|
|
2354
|
+
}
|
|
2355
|
+
if (hostname.startsWith("[") && hostname.endsWith("]")) {
|
|
2356
|
+
if (isPrivateIPv6(hostname.slice(1, -1).toLowerCase())) return true;
|
|
2357
|
+
}
|
|
2358
|
+
return false;
|
|
2359
|
+
}
|
|
2360
|
+
//#endregion
|
|
2361
|
+
//#region src/mcp/client/servers.ts
|
|
2362
|
+
/**
|
|
2363
|
+
* The life of each server: register, connect, discover, restore on wake,
|
|
2364
|
+
* settle for `addMcpServer()`, reconnect on request, close, remove, rename.
|
|
2365
|
+
*
|
|
2366
|
+
* All of it runs in the server's lane, one operation at a time. After every
|
|
2367
|
+
* failed connect or discovery (after its quick attempts),
|
|
2368
|
+
* {@link afterFailure} records why. A failed server stays failed, across
|
|
2369
|
+
* wakes too, until {@link reconnect} is called. Nothing retries on a timer.
|
|
2370
|
+
*/
|
|
2371
|
+
var ServerController = class {
|
|
2372
|
+
constructor(ctx, status, authorization, elicitation, entry) {
|
|
2373
|
+
this.ctx = ctx;
|
|
2374
|
+
this.status = status;
|
|
2375
|
+
this.authorization = authorization;
|
|
2376
|
+
this.elicitation = elicitation;
|
|
2377
|
+
this.entry = entry;
|
|
2378
|
+
this.disposables = /* @__PURE__ */ new Map();
|
|
2379
|
+
this.closedProviders = /* @__PURE__ */ new Map();
|
|
2380
|
+
this.registrations = /* @__PURE__ */ new Map();
|
|
2381
|
+
}
|
|
2382
|
+
/** Create the connection and save the server, without connecting. */
|
|
2383
|
+
register(id, options) {
|
|
2384
|
+
assertAllowedUrl(options.url);
|
|
2385
|
+
const authProvider = options.transport?.authProvider ?? (options.callbackUrl ? this.authorization.createProvider(id, options.callbackUrl, this.ctx.name, options.clientId) : void 0);
|
|
2386
|
+
if (authProvider) {
|
|
2387
|
+
authProvider.serverId = id;
|
|
2388
|
+
if (options.clientId) authProvider.clientId = options.clientId;
|
|
2389
|
+
}
|
|
2390
|
+
this.createConnection(id, options.url, {
|
|
2391
|
+
client: options.client,
|
|
2392
|
+
transport: {
|
|
2393
|
+
...options.transport,
|
|
2394
|
+
authProvider,
|
|
2395
|
+
type: options.transport?.type ?? "auto"
|
|
2396
|
+
}
|
|
2397
|
+
});
|
|
2398
|
+
this.ctx.store.save({
|
|
2399
|
+
id,
|
|
2400
|
+
name: options.name,
|
|
2401
|
+
server_url: options.url,
|
|
2402
|
+
callback_url: options.callbackUrl ?? "",
|
|
2403
|
+
client_id: options.clientId ?? null,
|
|
2404
|
+
auth_url: options.authUrl ?? null,
|
|
2405
|
+
server_options: encodeMcpServerOptions({
|
|
2406
|
+
client: options.client,
|
|
2407
|
+
transport: options.transport,
|
|
2408
|
+
retry: options.retry,
|
|
2409
|
+
capabilities: this.elicitation.capabilities()
|
|
2410
|
+
})
|
|
2411
|
+
});
|
|
2412
|
+
this.registrations.set(id, (this.registrations.get(id) ?? 0) + 1);
|
|
2413
|
+
this.ctx.store.clearFailure(id);
|
|
2414
|
+
this.ctx.store.setAuthorizationRounds(id, void 0);
|
|
2415
|
+
this.ctx.stateChanged();
|
|
2416
|
+
}
|
|
2417
|
+
/**
|
|
2418
|
+
* Create the in-memory connection, or return the one that exists, and
|
|
2419
|
+
* pipe its events to the manager. Does not save anything.
|
|
2420
|
+
*/
|
|
2421
|
+
createConnection(id, url, options) {
|
|
2422
|
+
const existing = this.ctx.connections[id];
|
|
2423
|
+
if (existing) return existing;
|
|
2424
|
+
const incoming = options.transport.authProvider;
|
|
2425
|
+
const closed = this.closedProviders.get(id);
|
|
2426
|
+
this.closedProviders.delete(id);
|
|
2427
|
+
if (closed && closed !== incoming) this.authorization.retire(closed);
|
|
2428
|
+
if (incoming) this.authorization.revive(incoming);
|
|
2429
|
+
const capabilitySeed = this.ctx.store.options(id)?.capabilities;
|
|
2430
|
+
const conn = new MCPClientConnection(new URL(url), {
|
|
2431
|
+
name: this.ctx.name,
|
|
2432
|
+
version: this.ctx.version
|
|
2433
|
+
}, {
|
|
2434
|
+
client: options.client ?? {},
|
|
2435
|
+
transport: {
|
|
2436
|
+
...options.transport,
|
|
2437
|
+
type: options.transport?.type ?? "auto"
|
|
2438
|
+
},
|
|
2439
|
+
elicitationHandlers: this.elicitation.scopedTo(id),
|
|
2440
|
+
capabilitySeed,
|
|
2441
|
+
discoverResult: options.discoverResult
|
|
2442
|
+
});
|
|
2443
|
+
this.ctx.connections[id] = conn;
|
|
2444
|
+
const store = new DisposableStore();
|
|
2445
|
+
this.disposables.get(id)?.dispose();
|
|
2446
|
+
this.disposables.set(id, store);
|
|
2447
|
+
store.add(conn.onObservabilityEvent((event) => this.ctx.observability.fire(event)));
|
|
2448
|
+
store.add(conn.onListChanged(() => this.ctx.stateChanged()));
|
|
2449
|
+
if (capabilitySeed) {
|
|
2450
|
+
const seedClear = conn.onObservabilityEvent((event) => {
|
|
2451
|
+
if (event.type !== "mcp:client:connect" || event.payload.state !== MCPConnectionState.CONNECTED) return;
|
|
2452
|
+
seedClear.dispose();
|
|
2453
|
+
if (this.elicitation.configured || !conn.options.capabilitySeed) return;
|
|
2454
|
+
const currentId = this.idOf(conn);
|
|
2455
|
+
if (currentId) this.ctx.store.clearCapabilities(currentId);
|
|
2456
|
+
});
|
|
2457
|
+
store.add(seedClear);
|
|
2458
|
+
}
|
|
2459
|
+
return conn;
|
|
2460
|
+
}
|
|
2461
|
+
/**
|
|
2462
|
+
* One connect attempt, in the server's lane. The manager's
|
|
2463
|
+
* `connectToServer()`.
|
|
2464
|
+
*/
|
|
2465
|
+
connect(id) {
|
|
2466
|
+
return this.ctx.lanes.run(id, () => this.connectInLane(id));
|
|
2467
|
+
}
|
|
2468
|
+
async connectInLane(id) {
|
|
2469
|
+
const conn = this.ctx.connections[id];
|
|
2470
|
+
if (!conn) throw new Error(`Server ${id} is not registered. Call registerServer() first.`);
|
|
2471
|
+
if (this.ctx.store.failure(id)) {
|
|
2472
|
+
this.ctx.store.clearFailure(id);
|
|
2473
|
+
this.ctx.store.setAuthorizationRounds(id, void 0);
|
|
2474
|
+
}
|
|
2475
|
+
const error = await conn.init();
|
|
2476
|
+
if (this.ctx.connections[id] !== conn) {
|
|
2477
|
+
await conn.close().catch(() => {});
|
|
2478
|
+
return {
|
|
2479
|
+
state: MCPConnectionState.FAILED,
|
|
2480
|
+
error: `Server ${id} was removed while connecting`
|
|
2481
|
+
};
|
|
2482
|
+
}
|
|
2483
|
+
this.status.saveSession(id, conn);
|
|
2484
|
+
this.ctx.stateChanged();
|
|
2485
|
+
switch (conn.connectionState) {
|
|
2486
|
+
case MCPConnectionState.FAILED: return {
|
|
2487
|
+
state: MCPConnectionState.FAILED,
|
|
2488
|
+
error: error ?? "Unknown connection error"
|
|
2489
|
+
};
|
|
2490
|
+
case MCPConnectionState.AUTHENTICATING: {
|
|
2491
|
+
const auth = this.authorization.enterAuthenticating(id, conn);
|
|
2492
|
+
switch (auth._tag) {
|
|
2493
|
+
case "authenticating": return {
|
|
2494
|
+
state: MCPConnectionState.AUTHENTICATING,
|
|
2495
|
+
authUrl: auth.authUrl,
|
|
2496
|
+
clientId: auth.clientId
|
|
2497
|
+
};
|
|
2498
|
+
case "exhausted": return {
|
|
2499
|
+
state: MCPConnectionState.FAILED,
|
|
2500
|
+
error: auth.error
|
|
2501
|
+
};
|
|
2502
|
+
case "unavailable":
|
|
2503
|
+
conn.accessRefused = true;
|
|
2504
|
+
return {
|
|
2505
|
+
state: MCPConnectionState.FAILED,
|
|
2506
|
+
error: this.authorization.noLinkReason(id, conn)
|
|
2507
|
+
};
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
case MCPConnectionState.CONNECTED: return { state: MCPConnectionState.CONNECTED };
|
|
2511
|
+
default: return {
|
|
2512
|
+
state: MCPConnectionState.FAILED,
|
|
2513
|
+
error: `Unexpected connection state after init: ${conn.connectionState}`
|
|
2514
|
+
};
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
/**
|
|
2518
|
+
* Discover a connected server, in its lane. The manager's
|
|
2519
|
+
* `discoverIfConnected()`.
|
|
2520
|
+
*/
|
|
2521
|
+
discover(id, options) {
|
|
2522
|
+
return this.ctx.lanes.run(id, () => this.discoverInLane(id, options));
|
|
2523
|
+
}
|
|
2524
|
+
async discoverInLane(id, options) {
|
|
2525
|
+
const conn = this.ctx.connections[id];
|
|
2526
|
+
if (!conn) {
|
|
2527
|
+
this.ctx.observability.fire({
|
|
2528
|
+
type: "mcp:client:discover",
|
|
2529
|
+
payload: {},
|
|
2530
|
+
timestamp: Date.now()
|
|
2531
|
+
});
|
|
2532
|
+
return;
|
|
2533
|
+
}
|
|
2534
|
+
const result = await conn.discover(options);
|
|
2535
|
+
if (this.ctx.connections[id] !== conn) return discoverResult(conn, result);
|
|
2536
|
+
if (!result.success && result.reason === "stale-session") return this.recoverStaleSession(conn, id, options);
|
|
2537
|
+
return this.afterDiscovery(id, conn, result);
|
|
2538
|
+
}
|
|
2539
|
+
/** Record what discovery found: ready, or waiting for the user. */
|
|
2540
|
+
afterDiscovery(id, conn, result) {
|
|
2541
|
+
if (result.success) this.status.ready(id);
|
|
2542
|
+
const auth = conn.connectionState === MCPConnectionState.AUTHENTICATING ? this.authorization.enterAuthenticating(id, conn) : void 0;
|
|
2543
|
+
this.ctx.stateChanged();
|
|
2544
|
+
return discoverResult(conn, result, auth);
|
|
2545
|
+
}
|
|
2546
|
+
/** A resumed session the server forgot: start a fresh one and discover. */
|
|
2547
|
+
async recoverStaleSession(conn, id, options) {
|
|
2548
|
+
conn.clearResumedSession();
|
|
2549
|
+
this.ctx.store.setSession(id);
|
|
2550
|
+
let connected;
|
|
2551
|
+
try {
|
|
2552
|
+
connected = await this.entry.connectToServer(id);
|
|
2553
|
+
} catch (error) {
|
|
2554
|
+
return {
|
|
2555
|
+
success: false,
|
|
2556
|
+
error: toErrorMessage(error),
|
|
2557
|
+
state: conn.connectionState
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2560
|
+
if (connected.state === MCPConnectionState.AUTHENTICATING) return {
|
|
2561
|
+
success: false,
|
|
2562
|
+
error: "The server requires authorization",
|
|
2563
|
+
state: conn.connectionState,
|
|
2564
|
+
authUrl: connected.authUrl,
|
|
2565
|
+
clientId: connected.clientId
|
|
2566
|
+
};
|
|
2567
|
+
if (connected.state !== MCPConnectionState.CONNECTED) return {
|
|
2568
|
+
success: false,
|
|
2569
|
+
error: connected.error,
|
|
2570
|
+
state: conn.connectionState
|
|
2571
|
+
};
|
|
2572
|
+
return this.afterDiscovery(id, conn, await conn.discover(options));
|
|
2573
|
+
}
|
|
2574
|
+
/**
|
|
2575
|
+
* Connect and discover as one unit of lane work, then act on the outcome
|
|
2576
|
+
* through {@link afterFailure}. Each attempt is a connect plus discovery;
|
|
2577
|
+
* a failed one is retried in place with the server's retry options (3
|
|
2578
|
+
* attempts by default) before the server counts as failed. A refusal gets
|
|
2579
|
+
* the same answer every time, so it is not retried.
|
|
2580
|
+
*/
|
|
2581
|
+
bringUp(id) {
|
|
2582
|
+
return this.ctx.lanes.run(id, async () => {
|
|
2583
|
+
const retry = this.ctx.store.options(id)?.retry;
|
|
2584
|
+
const owner = this.ctx.connections[id];
|
|
2585
|
+
const replaced = () => this.ctx.connections[id] !== owner;
|
|
2586
|
+
let settlement;
|
|
2587
|
+
try {
|
|
2588
|
+
settlement = await tryN(retry?.maxAttempts ?? 3, async () => {
|
|
2589
|
+
if (replaced()) return { state: "removed" };
|
|
2590
|
+
const attempt = await this.attempt(id);
|
|
2591
|
+
if (attempt.state === MCPConnectionState.FAILED && !attempt.refused && !this.ctx.store.failure(id) && this.ctx.connections[id]) throw new AttemptFailedError(attempt);
|
|
2592
|
+
return attempt;
|
|
2593
|
+
}, {
|
|
2594
|
+
baseDelayMs: retry?.baseDelayMs ?? 500,
|
|
2595
|
+
maxDelayMs: retry?.maxDelayMs ?? 5e3
|
|
2596
|
+
});
|
|
2597
|
+
} catch (error) {
|
|
2598
|
+
if (!(error instanceof AttemptFailedError)) throw error;
|
|
2599
|
+
settlement = error.settlement;
|
|
2600
|
+
}
|
|
2601
|
+
if (replaced()) return { state: "removed" };
|
|
2602
|
+
if (settlement.state === MCPConnectionState.FAILED) this.afterFailure(id, settlement);
|
|
2603
|
+
return settlement;
|
|
2604
|
+
});
|
|
2605
|
+
}
|
|
2606
|
+
/** One connect plus discovery. */
|
|
2607
|
+
async attempt(id) {
|
|
2608
|
+
let connected;
|
|
2609
|
+
try {
|
|
2610
|
+
connected = await this.entry.connectToServer(id);
|
|
2611
|
+
} catch (error) {
|
|
2612
|
+
connected = {
|
|
2613
|
+
state: MCPConnectionState.FAILED,
|
|
2614
|
+
error: toErrorMessage(error)
|
|
2615
|
+
};
|
|
2616
|
+
}
|
|
2617
|
+
if (connected.state === MCPConnectionState.CONNECTED) return this.settleDiscovery(id);
|
|
2618
|
+
if (connected.state === MCPConnectionState.AUTHENTICATING) return {
|
|
2619
|
+
state: MCPConnectionState.AUTHENTICATING,
|
|
2620
|
+
authUrl: connected.authUrl
|
|
2621
|
+
};
|
|
2622
|
+
return this.failed(id, "connect", connected.error);
|
|
2623
|
+
}
|
|
2624
|
+
async settleDiscovery(id) {
|
|
2625
|
+
const discovered = await this.entry.discoverIfConnected(id);
|
|
2626
|
+
if (discovered?.state === MCPConnectionState.AUTHENTICATING) {
|
|
2627
|
+
if (discovered.authUrl) return {
|
|
2628
|
+
state: MCPConnectionState.AUTHENTICATING,
|
|
2629
|
+
authUrl: discovered.authUrl
|
|
2630
|
+
};
|
|
2631
|
+
return {
|
|
2632
|
+
state: MCPConnectionState.FAILED,
|
|
2633
|
+
phase: "discover",
|
|
2634
|
+
error: discovered.error ?? "The server requires authorization",
|
|
2635
|
+
refused: true
|
|
2636
|
+
};
|
|
2637
|
+
}
|
|
2638
|
+
if (!discovered?.success) return this.failed(id, "discover", discovered?.error ?? "connection not found");
|
|
2639
|
+
return { state: MCPConnectionState.READY };
|
|
2640
|
+
}
|
|
2641
|
+
/** A failed settlement, marked refused when the connection was refused. */
|
|
2642
|
+
failed(id, phase, error) {
|
|
2643
|
+
return {
|
|
2644
|
+
state: MCPConnectionState.FAILED,
|
|
2645
|
+
phase,
|
|
2646
|
+
error,
|
|
2647
|
+
...this.ctx.connections[id]?.accessRefused && { refused: true }
|
|
2648
|
+
};
|
|
2649
|
+
}
|
|
2650
|
+
/**
|
|
2651
|
+
* After a failed connect or discovery, its quick attempts used up: record
|
|
2652
|
+
* why, so the server stays failed (across wakes too) until someone
|
|
2653
|
+
* reconnects it. Nothing retries it on a timer.
|
|
2654
|
+
*/
|
|
2655
|
+
afterFailure(id, settlement) {
|
|
2656
|
+
if (!this.ctx.connections[id] || !this.ctx.store.get(id)) return;
|
|
2657
|
+
if (this.ctx.store.failure(id)) return;
|
|
2658
|
+
if (settlement.refused) {
|
|
2659
|
+
this.status.stop(id, "authorization-failed", `Authorization was refused: ${settlement.error}`);
|
|
2660
|
+
return;
|
|
2661
|
+
}
|
|
2662
|
+
this.status.stop(id, "connect-failed", settlement.error);
|
|
2663
|
+
}
|
|
2664
|
+
/** Connect and discover a registered server. */
|
|
2665
|
+
connectAndDiscover(id) {
|
|
2666
|
+
return removedIfCancelled(this.bringUp(id));
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Bring a registered server to a settled state once the work queued for
|
|
2670
|
+
* it has run, for `addMcpServer()`: a ready server stays ready, a waiting
|
|
2671
|
+
* server returns its link, a connected server is discovered, one never
|
|
2672
|
+
* connected is connected. A failed server is reported as failed and never
|
|
2673
|
+
* retried here; that is reconnect()'s job.
|
|
2674
|
+
*/
|
|
2675
|
+
settle(id) {
|
|
2676
|
+
return removedIfCancelled(this.ctx.lanes.run(id, async () => {
|
|
2677
|
+
const conn = this.ctx.connections[id];
|
|
2678
|
+
if (!conn) return { state: "removed" };
|
|
2679
|
+
switch (conn.connectionState) {
|
|
2680
|
+
case MCPConnectionState.READY: return { state: MCPConnectionState.READY };
|
|
2681
|
+
case MCPConnectionState.FAILED: return {
|
|
2682
|
+
state: MCPConnectionState.FAILED,
|
|
2683
|
+
phase: "connect",
|
|
2684
|
+
error: `${conn.connectionError ?? "Connection failed"} Call reconnectMcpServer("${id}") to try again.`
|
|
2685
|
+
};
|
|
2686
|
+
case MCPConnectionState.CONNECTED: {
|
|
2687
|
+
const settlement = await this.settleDiscovery(id);
|
|
2688
|
+
if (settlement.state === MCPConnectionState.FAILED) this.afterFailure(id, settlement);
|
|
2689
|
+
return settlement;
|
|
2690
|
+
}
|
|
2691
|
+
case MCPConnectionState.AUTHENTICATING: {
|
|
2692
|
+
const authUrl = this.authorization.pendingLink(id, conn);
|
|
2693
|
+
if (authUrl) return {
|
|
2694
|
+
state: MCPConnectionState.AUTHENTICATING,
|
|
2695
|
+
authUrl
|
|
2696
|
+
};
|
|
2697
|
+
return this.connectAndDiscover(id);
|
|
2698
|
+
}
|
|
2699
|
+
case MCPConnectionState.CONNECTING:
|
|
2700
|
+
case MCPConnectionState.DISCOVERING: return this.connectAndDiscover(id);
|
|
2701
|
+
}
|
|
2702
|
+
}));
|
|
2703
|
+
}
|
|
2704
|
+
/**
|
|
2705
|
+
* Try a server again because someone asked: forget a recorded failure,
|
|
2706
|
+
* its link and step-up budget, and connect now. With the manager's own
|
|
2707
|
+
* `connectToServer()`, the only paths that retry a failed server; nothing
|
|
2708
|
+
* automatic does.
|
|
2709
|
+
*/
|
|
2710
|
+
reconnect(id) {
|
|
2711
|
+
return removedIfCancelled(this.ctx.lanes.run(id, async () => {
|
|
2712
|
+
if (!this.ctx.connections[id]) return { state: "removed" };
|
|
2713
|
+
this.ctx.store.clearFailure(id);
|
|
2714
|
+
this.authorization.forget(id);
|
|
2715
|
+
return this.connectAndDiscover(id);
|
|
2716
|
+
}));
|
|
2717
|
+
}
|
|
2718
|
+
/** Connect and discover after an OAuth callback, in the background. */
|
|
2719
|
+
establish(id) {
|
|
2720
|
+
return this.ctx.lanes.run(id, async () => {
|
|
2721
|
+
const conn = this.ctx.connections[id];
|
|
2722
|
+
if (!conn) {
|
|
2723
|
+
this.ctx.observability.fire({
|
|
2724
|
+
type: "mcp:client:preconnect",
|
|
2725
|
+
payload: { serverId: id },
|
|
2726
|
+
timestamp: Date.now()
|
|
2727
|
+
});
|
|
2728
|
+
return;
|
|
2729
|
+
}
|
|
2730
|
+
if (conn.connectionState !== MCPConnectionState.DISCOVERING && conn.connectionState !== MCPConnectionState.READY && conn.connectionState !== MCPConnectionState.AUTHENTICATING) {
|
|
2731
|
+
await this.bringUp(id);
|
|
2732
|
+
this.ctx.stateChanged();
|
|
2733
|
+
}
|
|
2734
|
+
this.ctx.observability.fire({
|
|
2735
|
+
type: "mcp:client:connect",
|
|
2736
|
+
payload: {
|
|
2737
|
+
url: conn.url.toString(),
|
|
2738
|
+
transport: conn.options.transport.type || "unknown",
|
|
2739
|
+
state: conn.connectionState
|
|
2740
|
+
},
|
|
2741
|
+
timestamp: Date.now()
|
|
2742
|
+
});
|
|
2743
|
+
});
|
|
2744
|
+
}
|
|
2745
|
+
/**
|
|
2746
|
+
* Rebuild the connections of stored HTTP servers on wake. A server with a
|
|
2747
|
+
* recorded failure stays failed, a waiting flow keeps waiting while its
|
|
2748
|
+
* link works, and the rest connect in the background.
|
|
2749
|
+
*
|
|
2750
|
+
* @param clientName - Durable Object identity used to scope OAuth state.
|
|
2751
|
+
*/
|
|
2752
|
+
async restore(clientName) {
|
|
2753
|
+
for (const server of this.ctx.store.list()) {
|
|
2754
|
+
if (server.server_url.startsWith("rpc:")) continue;
|
|
2755
|
+
if (!await this.dropStaleConnection(server.id)) continue;
|
|
2756
|
+
const options = decodeMcpServerOptions(server.server_options);
|
|
2757
|
+
const authProvider = server.callback_url ? this.authorization.createProvider(server.id, server.callback_url, clientName, server.client_id ?? void 0) : void 0;
|
|
2758
|
+
const conn = this.createConnection(server.id, server.server_url, {
|
|
2759
|
+
client: options?.client ?? {},
|
|
2760
|
+
transport: {
|
|
2761
|
+
...options?.transport ?? {},
|
|
2762
|
+
type: options?.transport?.type ?? "auto",
|
|
2763
|
+
authProvider
|
|
2764
|
+
},
|
|
2765
|
+
discoverResult: options?.discoverResult
|
|
2766
|
+
});
|
|
2767
|
+
if (this.showRecordedFailure(server, conn)) continue;
|
|
2768
|
+
if (server.auth_url) {
|
|
2769
|
+
conn.connectionState = MCPConnectionState.AUTHENTICATING;
|
|
2770
|
+
continue;
|
|
2771
|
+
}
|
|
2772
|
+
this.connectInBackground(server.id);
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
/**
|
|
2776
|
+
* Rebuild stored RPC servers. Like HTTP servers they connect in the
|
|
2777
|
+
* background: startup has a 30s budget a slow `McpAgent` must not hold.
|
|
2778
|
+
*/
|
|
2779
|
+
restoreRpc() {
|
|
2780
|
+
for (const server of this.ctx.store.listRpc()) {
|
|
2781
|
+
if (this.ctx.connections[server.id]) continue;
|
|
2782
|
+
const resolved = resolveRpcTransport(this.ctx.env, server);
|
|
2783
|
+
if (resolved._tag === "unresolved") {
|
|
2784
|
+
console.warn(`[MCPClientManager] Cannot restore RPC MCP server "${server.name}": ${resolved.reason}`);
|
|
2785
|
+
continue;
|
|
2786
|
+
}
|
|
2787
|
+
const conn = this.createConnection(server.id, server.server_url, { transport: resolved.transport });
|
|
2788
|
+
if (this.showRecordedFailure(server, conn)) continue;
|
|
2789
|
+
this.connectInBackground(server.id);
|
|
2790
|
+
}
|
|
2791
|
+
}
|
|
2792
|
+
/**
|
|
2793
|
+
* Leave a live connection alone (ready, or a flow in progress), or close
|
|
2794
|
+
* a failed one so it can be rebuilt. Returns whether to rebuild.
|
|
2795
|
+
*/
|
|
2796
|
+
async dropStaleConnection(id) {
|
|
2797
|
+
const existing = this.ctx.connections[id];
|
|
2798
|
+
if (!existing) return true;
|
|
2799
|
+
switch (existing.connectionState) {
|
|
2800
|
+
case MCPConnectionState.READY:
|
|
2801
|
+
console.warn(`[MCPClientManager] Server ${id} already has a ready connection. Skipping recreation.`);
|
|
2802
|
+
return false;
|
|
2803
|
+
case MCPConnectionState.AUTHENTICATING:
|
|
2804
|
+
case MCPConnectionState.CONNECTING:
|
|
2805
|
+
case MCPConnectionState.DISCOVERING: return false;
|
|
2806
|
+
case MCPConnectionState.FAILED:
|
|
2807
|
+
try {
|
|
2808
|
+
await existing.close();
|
|
2809
|
+
} catch (error) {
|
|
2810
|
+
console.warn(`[MCPClientManager] Error closing failed connection ${id}:`, error);
|
|
2811
|
+
} finally {
|
|
2812
|
+
this.forgetConnection(existing);
|
|
2813
|
+
}
|
|
2814
|
+
return true;
|
|
2815
|
+
default: return true;
|
|
2816
|
+
}
|
|
2817
|
+
}
|
|
2818
|
+
/** Show a recorded failure on a rebuilt connection. */
|
|
2819
|
+
showRecordedFailure(server, conn) {
|
|
2820
|
+
const failure = this.ctx.store.failure(server.id);
|
|
2821
|
+
if (!failure) return false;
|
|
2822
|
+
conn.connectionState = MCPConnectionState.FAILED;
|
|
2823
|
+
conn.connectionError = failure.message;
|
|
2824
|
+
return true;
|
|
2825
|
+
}
|
|
2826
|
+
connectInBackground(id) {
|
|
2827
|
+
this.bringUp(id).catch((error) => {
|
|
2828
|
+
if (error instanceof ServerLaneCancelledError) return;
|
|
2829
|
+
console.error(`[MCPClientManager] Error restoring ${id}:`, error);
|
|
2830
|
+
});
|
|
2831
|
+
}
|
|
2832
|
+
/** Close a server's connection and cancel its queued work. */
|
|
2833
|
+
async close(id) {
|
|
2834
|
+
const conn = this.ctx.connections[id];
|
|
2835
|
+
if (!conn) throw new Error(`Connection with id "${id}" does not exist.`);
|
|
2836
|
+
conn.cancelDiscovery();
|
|
2837
|
+
this.ctx.lanes.forget(id);
|
|
2838
|
+
try {
|
|
2839
|
+
await conn.close();
|
|
2840
|
+
} finally {
|
|
2841
|
+
this.forgetConnection(conn);
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
/** Close every connection, keeping the servers stored. */
|
|
2845
|
+
async closeAll() {
|
|
2846
|
+
const ids = Object.keys(this.ctx.connections);
|
|
2847
|
+
this.ctx.lanes.forgetAll();
|
|
2848
|
+
for (const id of ids) this.ctx.connections[id].cancelDiscovery();
|
|
2849
|
+
const errors = (await Promise.allSettled(ids.map(async (id) => {
|
|
2850
|
+
const conn = this.ctx.connections[id];
|
|
2851
|
+
try {
|
|
2852
|
+
await conn.close();
|
|
2853
|
+
} finally {
|
|
2854
|
+
this.forgetConnection(conn);
|
|
2855
|
+
}
|
|
2856
|
+
}))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
2857
|
+
if (errors.length === 1) throw errors[0];
|
|
2858
|
+
if (errors.length > 1) throw new AggregateError(errors, "Failed to close one or more MCP connections");
|
|
2859
|
+
}
|
|
2860
|
+
/** Close a server's connection and delete it with its OAuth state. */
|
|
2861
|
+
async remove(id) {
|
|
2862
|
+
this.ctx.removing.add(id);
|
|
2863
|
+
try {
|
|
2864
|
+
await this.removeServer(id);
|
|
2865
|
+
} finally {
|
|
2866
|
+
this.ctx.removing.delete(id);
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
async removeServer(id) {
|
|
2870
|
+
const registration = this.registrations.get(id);
|
|
2871
|
+
const conn = this.ctx.connections[id];
|
|
2872
|
+
let authProvider = conn?.options.transport.authProvider ?? this.closedProviders.get(id);
|
|
2873
|
+
if (!authProvider) try {
|
|
2874
|
+
authProvider = this.authorization.providerFromRow(this.ctx.store.get(id));
|
|
2875
|
+
} catch (error) {
|
|
2876
|
+
console.warn(`[MCPClientManager] Failed to create auth provider for ${id}:`, error);
|
|
2877
|
+
}
|
|
2878
|
+
if (conn) await this.close(id).catch(() => {});
|
|
2879
|
+
const registeredAgain = () => this.registrations.get(id) !== registration;
|
|
2880
|
+
if (registeredAgain()) {
|
|
2881
|
+
const current = this.ctx.connections[id]?.options.transport.authProvider;
|
|
2882
|
+
if (authProvider && authProvider !== current) this.authorization.retire(authProvider);
|
|
2883
|
+
return;
|
|
2884
|
+
}
|
|
2885
|
+
if (authProvider) await this.authorization.clearStorage(id, authProvider);
|
|
2886
|
+
if (this.closedProviders.get(id) === authProvider) this.closedProviders.delete(id);
|
|
2887
|
+
if (registeredAgain() || this.ctx.connections[id]) return;
|
|
2888
|
+
this.ctx.store.remove(id);
|
|
2889
|
+
this.ctx.stateChanged();
|
|
2890
|
+
}
|
|
2891
|
+
/**
|
|
2892
|
+
* Rename a server's id everywhere it is a key: its row, its connection,
|
|
2893
|
+
* its provider and its OAuth storage keys. A no-op when
|
|
2894
|
+
* the ids match; throws when `newId` is taken.
|
|
2895
|
+
*/
|
|
2896
|
+
async migrate(oldId, newId, clientName) {
|
|
2897
|
+
if (oldId === newId) return;
|
|
2898
|
+
await this.ctx.lanes.idle(oldId);
|
|
2899
|
+
const renamed = this.ctx.storage.transactionSync(() => {
|
|
2900
|
+
const result = this.ctx.store.rename(oldId, newId);
|
|
2901
|
+
if (result === "renamed") this.moveOAuthKeys(`/${clientName}/${oldId}/`, `/${clientName}/${newId}/`);
|
|
2902
|
+
return result;
|
|
2903
|
+
});
|
|
2904
|
+
if (renamed === "missing") {
|
|
2905
|
+
this.renameConnection(oldId, newId);
|
|
2906
|
+
return;
|
|
2907
|
+
}
|
|
2908
|
+
if (renamed === "collision") throw new Error(`Cannot migrate MCP server id "${oldId}" → "${newId}": new id is already in use.`);
|
|
2909
|
+
this.authorization.renamed(oldId, newId, this.ctx.connections[oldId]);
|
|
2910
|
+
this.renameConnection(oldId, newId);
|
|
2911
|
+
this.ctx.stateChanged();
|
|
2912
|
+
}
|
|
2913
|
+
/** Move the provider's storage keys to the new id. Throws on failure. */
|
|
2914
|
+
moveOAuthKeys(oldPrefix, newPrefix) {
|
|
2915
|
+
const { kv } = this.ctx.storage;
|
|
2916
|
+
for (const [key, value] of [...kv.list({ prefix: oldPrefix })]) {
|
|
2917
|
+
kv.put(newPrefix + key.slice(oldPrefix.length), value);
|
|
2918
|
+
kv.delete(key);
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
renameConnection(oldId, newId) {
|
|
2922
|
+
const conn = this.ctx.connections[oldId];
|
|
2923
|
+
if (conn) {
|
|
2924
|
+
this.ctx.connections[newId] = conn;
|
|
2925
|
+
delete this.ctx.connections[oldId];
|
|
2926
|
+
const authProvider = conn.options.transport.authProvider;
|
|
2927
|
+
if (authProvider) authProvider.serverId = newId;
|
|
2928
|
+
const scoped = this.elicitation.scopedTo(newId);
|
|
2929
|
+
if (scoped) conn.configureElicitationHandlers(scoped);
|
|
2930
|
+
}
|
|
2931
|
+
const disposables = this.disposables.get(oldId);
|
|
2932
|
+
if (disposables) {
|
|
2933
|
+
this.disposables.set(newId, disposables);
|
|
2934
|
+
this.disposables.delete(oldId);
|
|
2935
|
+
}
|
|
2936
|
+
const registration = this.registrations.get(oldId);
|
|
2937
|
+
if (registration !== void 0) {
|
|
2938
|
+
this.registrations.set(newId, registration);
|
|
2939
|
+
this.registrations.delete(oldId);
|
|
2940
|
+
}
|
|
2941
|
+
const closed = this.closedProviders.get(oldId);
|
|
2942
|
+
if (closed) {
|
|
2943
|
+
closed.serverId = newId;
|
|
2944
|
+
this.closedProviders.set(newId, closed);
|
|
2945
|
+
this.closedProviders.delete(oldId);
|
|
2946
|
+
}
|
|
2947
|
+
}
|
|
2948
|
+
/**
|
|
2949
|
+
* Drop a closed connection and its session; the server stays stored. Only
|
|
2950
|
+
* this connection: while it was closing, an overlapping close may have
|
|
2951
|
+
* dropped it already and the server may have a new connection, or the
|
|
2952
|
+
* server may have been renamed.
|
|
2953
|
+
*/
|
|
2954
|
+
forgetConnection(conn) {
|
|
2955
|
+
const id = this.idOf(conn);
|
|
2956
|
+
if (id === void 0) return;
|
|
2957
|
+
const authProvider = conn.options.transport.authProvider;
|
|
2958
|
+
if (authProvider) this.closedProviders.set(id, authProvider);
|
|
2959
|
+
this.ctx.store.setSession(id);
|
|
2960
|
+
this.disposables.get(id)?.dispose();
|
|
2961
|
+
this.disposables.delete(id);
|
|
2962
|
+
delete this.ctx.connections[id];
|
|
2963
|
+
}
|
|
2964
|
+
idOf(conn) {
|
|
2965
|
+
return Object.keys(this.ctx.connections).find((key) => this.ctx.connections[key] === conn);
|
|
2966
|
+
}
|
|
2967
|
+
};
|
|
2968
|
+
/** Throw for a URL the SSRF policy blocks. */
|
|
2969
|
+
function assertAllowedUrl(url) {
|
|
2970
|
+
if (isBlockedUrl(url)) throw new Error(`Blocked URL: ${url} — MCP client connections to private/internal addresses are not allowed`);
|
|
2971
|
+
}
|
|
2972
|
+
/** Report work cancelled by removal as a removed server. */
|
|
2973
|
+
async function removedIfCancelled(work) {
|
|
2974
|
+
try {
|
|
2975
|
+
return await work;
|
|
2976
|
+
} catch (error) {
|
|
2977
|
+
if (error instanceof ServerLaneCancelledError) return { state: "removed" };
|
|
2978
|
+
throw error;
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
function discoverResult(conn, result, auth) {
|
|
2982
|
+
if (result.success) return {
|
|
2983
|
+
success: true,
|
|
2984
|
+
state: conn.connectionState
|
|
2985
|
+
};
|
|
2986
|
+
return {
|
|
2987
|
+
success: false,
|
|
2988
|
+
error: auth?._tag === "exhausted" ? auth.error : result.error,
|
|
2989
|
+
state: conn.connectionState,
|
|
2990
|
+
...auth?._tag === "authenticating" && {
|
|
2991
|
+
authUrl: auth.authUrl,
|
|
2992
|
+
clientId: auth.clientId
|
|
2993
|
+
}
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
2996
|
+
/** Carries a failed attempt out of `tryN` so it is retried. */
|
|
2997
|
+
var AttemptFailedError = class extends Error {
|
|
2998
|
+
constructor(settlement) {
|
|
2999
|
+
super("MCP connection attempt failed");
|
|
3000
|
+
this.settlement = settlement;
|
|
3001
|
+
}
|
|
3002
|
+
};
|
|
3003
|
+
//#endregion
|
|
3004
|
+
//#region src/mcp/client/legacy-connect.ts
|
|
3005
|
+
/**
|
|
3006
|
+
* The deprecated `MCPClientManager.connect()`: create (or, with an OAuth
|
|
3007
|
+
* code, reuse) a connection, connect it, and discover it. Kept apart from
|
|
3008
|
+
* the server controller because nothing else works this way: it neither
|
|
3009
|
+
* saves the server nor schedules reconnects.
|
|
3010
|
+
*/
|
|
3011
|
+
function legacyConnect(ctx, servers, entry, url, options) {
|
|
3012
|
+
const id = options.reconnect?.id ?? nanoid(8);
|
|
3013
|
+
return ctx.lanes.run(id, async () => {
|
|
3014
|
+
const provider = options.transport?.authProvider;
|
|
3015
|
+
if (provider) {
|
|
3016
|
+
provider.serverId = id;
|
|
3017
|
+
if (options.reconnect?.oauthClientId) provider.clientId = options.reconnect.oauthClientId;
|
|
3018
|
+
}
|
|
3019
|
+
assertAllowedUrl(url);
|
|
3020
|
+
if (!options.reconnect?.oauthCode || !ctx.connections[id]) {
|
|
3021
|
+
const replaced = ctx.connections[id];
|
|
3022
|
+
if (replaced) {
|
|
3023
|
+
delete ctx.connections[id];
|
|
3024
|
+
await replaced.close().catch(() => {});
|
|
3025
|
+
ctx.store.setSession(id);
|
|
3026
|
+
}
|
|
3027
|
+
servers.createConnection(id, url, {
|
|
3028
|
+
client: options.client,
|
|
3029
|
+
transport: options.transport ?? {}
|
|
3030
|
+
});
|
|
3031
|
+
}
|
|
3032
|
+
const conn = ctx.connections[id];
|
|
3033
|
+
const stillRegistered = () => {
|
|
3034
|
+
if (ctx.connections[id] !== conn) throw new Error(`MCP server ${id} was removed while connecting`);
|
|
3035
|
+
};
|
|
3036
|
+
await conn.init();
|
|
3037
|
+
stillRegistered();
|
|
3038
|
+
if (options.reconnect?.oauthCode) try {
|
|
3039
|
+
await completeAuthorization(conn, id, options.reconnect.oauthCode);
|
|
3040
|
+
stillRegistered();
|
|
3041
|
+
await conn.init();
|
|
3042
|
+
stillRegistered();
|
|
3043
|
+
} catch (error) {
|
|
3044
|
+
ctx.observability.fire({
|
|
3045
|
+
type: "mcp:client:connect",
|
|
3046
|
+
payload: {
|
|
3047
|
+
url,
|
|
3048
|
+
transport: options.transport?.type ?? "auto",
|
|
3049
|
+
state: conn.connectionState,
|
|
3050
|
+
error: toErrorMessage(error)
|
|
3051
|
+
},
|
|
3052
|
+
timestamp: Date.now()
|
|
3053
|
+
});
|
|
3054
|
+
throw error;
|
|
3055
|
+
}
|
|
3056
|
+
const authUrl = provider?.authUrl;
|
|
3057
|
+
if (conn.connectionState === MCPConnectionState.AUTHENTICATING && authUrl && provider?.redirectUrl) return {
|
|
3058
|
+
authUrl,
|
|
3059
|
+
clientId: provider.clientId,
|
|
3060
|
+
id
|
|
3061
|
+
};
|
|
3062
|
+
const discovered = await entry.discoverIfConnected(id);
|
|
3063
|
+
stillRegistered();
|
|
3064
|
+
if (discovered && !discovered.success) throw new Error(`Failed to discover server capabilities: ${discovered.error}`);
|
|
3065
|
+
return { id };
|
|
3066
|
+
});
|
|
3067
|
+
}
|
|
3068
|
+
/** Exchange the code, always cleaning up the code verifier afterwards. */
|
|
3069
|
+
async function completeAuthorization(conn, id, code) {
|
|
3070
|
+
let completeError;
|
|
3071
|
+
try {
|
|
3072
|
+
await conn.completeAuthorization(code);
|
|
3073
|
+
} catch (error) {
|
|
3074
|
+
completeError = error;
|
|
3075
|
+
}
|
|
3076
|
+
try {
|
|
3077
|
+
await conn.options.transport.authProvider?.deleteCodeVerifier();
|
|
3078
|
+
} catch (cleanupError) {
|
|
3079
|
+
console.warn(`[MCPClientManager] Failed to clean up OAuth code verifier for server "${id}":`, cleanupError);
|
|
3080
|
+
}
|
|
3081
|
+
if (completeError) throw completeError;
|
|
3082
|
+
}
|
|
3083
|
+
//#endregion
|
|
3084
|
+
//#region src/mcp/client/server-store.ts
|
|
3085
|
+
const SERVER_COLUMNS = "id, name, server_url, client_id, auth_url, callback_url, server_options";
|
|
3086
|
+
var _statusColumnsReady = /* @__PURE__ */ new WeakMap();
|
|
3087
|
+
var _McpServerStore_brand = /* @__PURE__ */ new WeakSet();
|
|
3088
|
+
/**
|
|
3089
|
+
* The durable MCP server catalog: one `cf_agents_mcp_servers` row per
|
|
3090
|
+
* registered server. Every SQL statement the client manager runs lives here,
|
|
3091
|
+
* and `server_options` is read and written only through the storage codec.
|
|
3092
|
+
* The table itself is created by `ensureMcpServerTable` during startup.
|
|
3093
|
+
*/
|
|
3094
|
+
var McpServerStore = class {
|
|
3095
|
+
/**
|
|
3096
|
+
* @param storage - The Durable Object storage holding the catalog table.
|
|
3097
|
+
*/
|
|
3098
|
+
constructor(storage) {
|
|
3099
|
+
this.storage = storage;
|
|
3100
|
+
_classPrivateMethodInitSpec(this, _McpServerStore_brand);
|
|
3101
|
+
_classPrivateFieldInitSpec(this, _statusColumnsReady, false);
|
|
3102
|
+
}
|
|
3103
|
+
/** Every stored server, in table order. */
|
|
3104
|
+
list() {
|
|
3105
|
+
return _assertClassBrand(_McpServerStore_brand, this, _exec).call(this, `SELECT ${SERVER_COLUMNS} FROM cf_agents_mcp_servers`);
|
|
3106
|
+
}
|
|
3107
|
+
/** Stored servers reached over Durable Object RPC (`rpc://` URLs). */
|
|
3108
|
+
listRpc() {
|
|
3109
|
+
return this.list().filter((server) => server.server_url.startsWith(RPC_DO_PREFIX));
|
|
3110
|
+
}
|
|
3111
|
+
/** One stored server, or undefined when it is not registered. */
|
|
3112
|
+
get(id) {
|
|
3113
|
+
return _assertClassBrand(_McpServerStore_brand, this, _exec).call(this, `SELECT ${SERVER_COLUMNS} FROM cf_agents_mcp_servers WHERE id = ?`, id)[0];
|
|
3114
|
+
}
|
|
3115
|
+
/**
|
|
3116
|
+
* Insert one server row, or update every catalog column of an existing
|
|
3117
|
+
* one. A recorded failure is kept; registration clears it explicitly.
|
|
3118
|
+
*/
|
|
3119
|
+
save(server) {
|
|
3120
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, `INSERT INTO cf_agents_mcp_servers (${SERVER_COLUMNS})
|
|
3121
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
3122
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
3123
|
+
name = excluded.name,
|
|
3124
|
+
server_url = excluded.server_url,
|
|
3125
|
+
client_id = excluded.client_id,
|
|
3126
|
+
auth_url = excluded.auth_url,
|
|
3127
|
+
callback_url = excluded.callback_url,
|
|
3128
|
+
server_options = excluded.server_options`, server.id, server.name, server.server_url, server.client_id ?? null, server.auth_url ?? null, server.callback_url, server.server_options ?? null);
|
|
3129
|
+
}
|
|
3130
|
+
/** Delete one server row. */
|
|
3131
|
+
remove(id) {
|
|
3132
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "DELETE FROM cf_agents_mcp_servers WHERE id = ?", id);
|
|
3133
|
+
}
|
|
3134
|
+
/** Move a row to a new primary key, refusing to overwrite another row. */
|
|
3135
|
+
rename(oldId, newId) {
|
|
3136
|
+
if (!this.get(oldId)) return "missing";
|
|
3137
|
+
if (this.get(newId)) return "collision";
|
|
3138
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "UPDATE cf_agents_mcp_servers SET id = ? WHERE id = ?", newId, oldId);
|
|
3139
|
+
return "renamed";
|
|
3140
|
+
}
|
|
3141
|
+
/** The decoded `server_options` of one server. */
|
|
3142
|
+
options(id) {
|
|
3143
|
+
const row = this.get(id);
|
|
3144
|
+
if (!row?.server_options) return void 0;
|
|
3145
|
+
return decodeMcpServerOptions(row.server_options);
|
|
3146
|
+
}
|
|
3147
|
+
/**
|
|
3148
|
+
* Record the authorization URL and OAuth client id a flow is waiting on,
|
|
3149
|
+
* and whether it is a step-up on a grant the server already holds.
|
|
3150
|
+
*/
|
|
3151
|
+
setAuthContinuation(id, authUrl, clientId, stepUp) {
|
|
3152
|
+
const row = this.get(id);
|
|
3153
|
+
if (!row) return;
|
|
3154
|
+
this.save({
|
|
3155
|
+
...row,
|
|
3156
|
+
auth_url: authUrl,
|
|
3157
|
+
client_id: clientId ?? null
|
|
3158
|
+
});
|
|
3159
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3160
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "UPDATE cf_agents_mcp_servers SET pending_step_up = ? WHERE id = ?", stepUp ? 1 : null, id);
|
|
3161
|
+
}
|
|
3162
|
+
/** Whether the flow a server waits on is a step-up on its current grant. */
|
|
3163
|
+
isPendingStepUp(id) {
|
|
3164
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3165
|
+
return _assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "SELECT pending_step_up FROM cf_agents_mcp_servers WHERE id = ?", id)[0]?.pending_step_up === 1;
|
|
3166
|
+
}
|
|
3167
|
+
/** Forget the authorization URL of one server. */
|
|
3168
|
+
clearAuthUrl(id) {
|
|
3169
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3170
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "UPDATE cf_agents_mcp_servers SET auth_url = NULL, pending_step_up = NULL WHERE id = ?", id);
|
|
3171
|
+
}
|
|
3172
|
+
/** Persist, or with no session clear, the resumable session of a server. */
|
|
3173
|
+
setSession(id, session) {
|
|
3174
|
+
const row = this.get(id);
|
|
3175
|
+
if (!row) return;
|
|
3176
|
+
const options = decodeMcpServerOptions(row.server_options);
|
|
3177
|
+
this.save({
|
|
3178
|
+
...row,
|
|
3179
|
+
server_options: encodeMcpServerOptions(withMcpSession(options, session))
|
|
3180
|
+
});
|
|
3181
|
+
}
|
|
3182
|
+
/**
|
|
3183
|
+
* Clear the capabilities persisted on one server. The stamp is valid for
|
|
3184
|
+
* one successful restore: sessions that configure elicitation handlers
|
|
3185
|
+
* re-stamp every row, so a deploy that stops configuring them stops
|
|
3186
|
+
* advertising stale modes after its first connected wake.
|
|
3187
|
+
*/
|
|
3188
|
+
clearCapabilities(id) {
|
|
3189
|
+
const row = this.get(id);
|
|
3190
|
+
if (!row?.server_options) return;
|
|
3191
|
+
const options = decodeMcpServerOptions(row.server_options);
|
|
3192
|
+
if (!options.capabilities) return;
|
|
3193
|
+
options.capabilities = void 0;
|
|
3194
|
+
this.save({
|
|
3195
|
+
...row,
|
|
3196
|
+
server_options: encodeMcpServerOptions(options)
|
|
3197
|
+
});
|
|
3198
|
+
}
|
|
3199
|
+
/** The failure recorded for one server, if it stopped trying. */
|
|
3200
|
+
failure(id) {
|
|
3201
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3202
|
+
const value = _assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "SELECT failure FROM cf_agents_mcp_servers WHERE id = ?", id)[0]?.failure;
|
|
3203
|
+
if (!value) return void 0;
|
|
3204
|
+
try {
|
|
3205
|
+
return JSON.parse(value);
|
|
3206
|
+
} catch {
|
|
3207
|
+
return;
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
/** Record that one server stopped trying, and why. */
|
|
3211
|
+
setFailure(id, failure) {
|
|
3212
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3213
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "UPDATE cf_agents_mcp_servers SET failure = ? WHERE id = ?", JSON.stringify(failure), id);
|
|
3214
|
+
}
|
|
3215
|
+
/** Forget a recorded failure, so the server may connect again. */
|
|
3216
|
+
clearFailure(id) {
|
|
3217
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3218
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "UPDATE cf_agents_mcp_servers SET failure = NULL WHERE id = ? AND failure IS NOT NULL", id);
|
|
3219
|
+
}
|
|
3220
|
+
/** Authorization rounds recorded for one server, as stored JSON. */
|
|
3221
|
+
authorizationRounds(id) {
|
|
3222
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3223
|
+
const value = _assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "SELECT authorization_rounds FROM cf_agents_mcp_servers WHERE id = ?", id)[0]?.authorization_rounds;
|
|
3224
|
+
if (!value) return void 0;
|
|
3225
|
+
try {
|
|
3226
|
+
return JSON.parse(value);
|
|
3227
|
+
} catch {
|
|
3228
|
+
return;
|
|
3229
|
+
}
|
|
3230
|
+
}
|
|
3231
|
+
/** Record, or with no value forget, the authorization rounds of a server. */
|
|
3232
|
+
setAuthorizationRounds(id, rounds) {
|
|
3233
|
+
_assertClassBrand(_McpServerStore_brand, this, _ensureStatusColumns).call(this);
|
|
3234
|
+
_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "UPDATE cf_agents_mcp_servers SET authorization_rounds = ? WHERE id = ?", rounds === void 0 ? null : JSON.stringify(rounds), id);
|
|
3235
|
+
}
|
|
3236
|
+
/** Stamp the handler-derived capabilities on every stored server. */
|
|
3237
|
+
stampCapabilities(capabilities) {
|
|
3238
|
+
for (const row of this.list()) {
|
|
3239
|
+
const options = decodeMcpServerOptions(row.server_options);
|
|
3240
|
+
if (JSON.stringify(options.capabilities) === JSON.stringify(capabilities)) continue;
|
|
3241
|
+
options.capabilities = capabilities;
|
|
3242
|
+
this.save({
|
|
3243
|
+
...row,
|
|
3244
|
+
server_options: encodeMcpServerOptions(options)
|
|
3245
|
+
});
|
|
3246
|
+
}
|
|
3247
|
+
}
|
|
3248
|
+
};
|
|
3249
|
+
function _exec(query, ...bindings) {
|
|
3250
|
+
return [...this.storage.sql.exec(query, ...bindings)];
|
|
3251
|
+
}
|
|
3252
|
+
/**
|
|
3253
|
+
* Add the status columns (`failure`, `authorization_rounds`,
|
|
3254
|
+
* `pending_step_up`) on first use.
|
|
3255
|
+
* They are owned here rather than in `ensureMcpServerTable`, so the
|
|
3256
|
+
* catalog's base DDL (and the Agent schema snapshot built from it) stays
|
|
3257
|
+
* unchanged and objects that never use them never alter the table.
|
|
3258
|
+
*/
|
|
3259
|
+
function _ensureStatusColumns() {
|
|
3260
|
+
if (_classPrivateFieldGet2(_statusColumnsReady, this)) return;
|
|
3261
|
+
const present = new Set(_assertClassBrand(_McpServerStore_brand, this, _exec).call(this, "SELECT name FROM pragma_table_info('cf_agents_mcp_servers')").map((column) => column.name));
|
|
3262
|
+
for (const [column, type] of [
|
|
3263
|
+
["failure", "TEXT"],
|
|
3264
|
+
["authorization_rounds", "TEXT"],
|
|
3265
|
+
["pending_step_up", "INTEGER"]
|
|
3266
|
+
]) if (!present.has(column)) _assertClassBrand(_McpServerStore_brand, this, _exec).call(this, `ALTER TABLE cf_agents_mcp_servers ADD COLUMN ${column} ${type}`);
|
|
3267
|
+
_classPrivateFieldSet2(_statusColumnsReady, this, true);
|
|
3268
|
+
}
|
|
3269
|
+
//#endregion
|
|
3270
|
+
//#region src/mcp/client/status.ts
|
|
3271
|
+
/**
|
|
3272
|
+
* The transitions every controller shares: a server stops with a recorded
|
|
3273
|
+
* reason, a server reaches ready, and a connection's resumable session is
|
|
3274
|
+
* saved with its row.
|
|
3275
|
+
*/
|
|
3276
|
+
var ServerStatus = class {
|
|
3277
|
+
constructor(ctx) {
|
|
3278
|
+
this.ctx = ctx;
|
|
3279
|
+
}
|
|
3280
|
+
/**
|
|
3281
|
+
* Mark a server failed and record why, so later wakes show the same
|
|
3282
|
+
* failure instead of trying again. Clears its pending link. Only an
|
|
3283
|
+
* explicit reconnect clears the failure.
|
|
3284
|
+
*/
|
|
3285
|
+
stop(serverId, reason, message) {
|
|
3286
|
+
this.ctx.store.clearAuthUrl(serverId);
|
|
3287
|
+
this.ctx.store.setFailure(serverId, {
|
|
3288
|
+
reason,
|
|
3289
|
+
message,
|
|
3290
|
+
at: Date.now()
|
|
3291
|
+
});
|
|
3292
|
+
const conn = this.ctx.connections[serverId];
|
|
3293
|
+
if (conn) {
|
|
3294
|
+
conn.connectionState = MCPConnectionState.FAILED;
|
|
3295
|
+
conn.connectionError = message;
|
|
3296
|
+
}
|
|
3297
|
+
this.ctx.stateChanged();
|
|
3298
|
+
}
|
|
3299
|
+
/** A server reached ready: forget its failure. */
|
|
3300
|
+
ready(serverId) {
|
|
3301
|
+
this.ctx.store.clearFailure(serverId);
|
|
3302
|
+
const conn = this.ctx.connections[serverId];
|
|
3303
|
+
if (conn) conn.connectionError = null;
|
|
3304
|
+
}
|
|
3305
|
+
/** Save the connection's resumable session with its row, or clear it. */
|
|
3306
|
+
saveSession(serverId, conn) {
|
|
3307
|
+
const { sessionId, protocolVersion, discoverResult } = conn;
|
|
3308
|
+
this.ctx.store.setSession(serverId, sessionId && protocolVersion ? {
|
|
3309
|
+
id: sessionId,
|
|
3310
|
+
protocolVersion,
|
|
3311
|
+
discoverResult
|
|
3312
|
+
} : void 0);
|
|
3313
|
+
}
|
|
3314
|
+
};
|
|
3315
|
+
//#endregion
|
|
3316
|
+
//#region src/mcp/client/manager.ts
|
|
3317
|
+
const MCP_SCHEMA_VERSION_KEY = "cf_agents:mcp_schema_version";
|
|
3318
|
+
const CURRENT_MCP_SCHEMA_VERSION = 1;
|
|
3319
|
+
var _store = /* @__PURE__ */ new WeakMap();
|
|
3320
|
+
/**
|
|
3321
|
+
* A Durable Object capability that persists and aggregates MCP client
|
|
3322
|
+
* connections. Install it on any Lifecycle, or use `agent.mcp` on an Agent.
|
|
3323
|
+
*
|
|
3324
|
+
* The manager is the public API and the Lifecycle hooks. Behind it:
|
|
3325
|
+
* - {@link ServerController}: each server's connection life, and what
|
|
3326
|
+
* happens after a failure
|
|
3327
|
+
* - {@link AuthorizationController}: authorization links, OAuth callbacks
|
|
3328
|
+
* and re-authorization during requests
|
|
3329
|
+
*/
|
|
3330
|
+
var MCPClientManager = class extends LifecycleCapability {
|
|
3331
|
+
/**
|
|
3332
|
+
* Construct a reusable Durable Object MCP client capability.
|
|
3333
|
+
*
|
|
3334
|
+
* @param name - MCP client implementation name sent during negotiation.
|
|
3335
|
+
* @param version - MCP client implementation version sent during negotiation.
|
|
3336
|
+
* @param options - Optional runtime bindings and OAuth configuration.
|
|
3337
|
+
*/
|
|
3338
|
+
constructor(_name, version, options = {}) {
|
|
3339
|
+
super("mcp");
|
|
3340
|
+
this._name = _name;
|
|
3341
|
+
this.mcpConnections = {};
|
|
3342
|
+
this._onObservabilityEvent = new Emitter();
|
|
3343
|
+
this.onObservabilityEvent = this._onObservabilityEvent.event;
|
|
3344
|
+
this._onServerStateChanged = new Emitter();
|
|
3345
|
+
this.onServerStateChanged = this._onServerStateChanged.event;
|
|
3346
|
+
this._lanes = new ServerLanes();
|
|
3347
|
+
this._isRestored = false;
|
|
3348
|
+
_classPrivateFieldInitSpec(this, _store, void 0);
|
|
3349
|
+
this.aiTools = new MCPAIToolConverter();
|
|
3350
|
+
this.didWarnAboutUnstableGetAITools = false;
|
|
3351
|
+
const manager = this;
|
|
3352
|
+
const ctx = {
|
|
3353
|
+
name: _name,
|
|
3354
|
+
version,
|
|
3355
|
+
get connections() {
|
|
3356
|
+
return manager.mcpConnections;
|
|
3357
|
+
},
|
|
3358
|
+
get store() {
|
|
3359
|
+
_classPrivateFieldGet2(_store, manager) ?? _classPrivateFieldSet2(_store, manager, new McpServerStore(manager.lifecycle.storage));
|
|
3360
|
+
return _classPrivateFieldGet2(_store, manager);
|
|
3361
|
+
},
|
|
3362
|
+
get storage() {
|
|
3363
|
+
return manager.lifecycle.storage;
|
|
3364
|
+
},
|
|
3365
|
+
lanes: this._lanes,
|
|
3366
|
+
removing: /* @__PURE__ */ new Set(),
|
|
3367
|
+
env: options.env,
|
|
3368
|
+
createAuthProvider: options.createAuthProvider,
|
|
3369
|
+
observability: this._onObservabilityEvent,
|
|
3370
|
+
stateChanged: () => this._lanes.outside(() => this._onServerStateChanged.fire())
|
|
3371
|
+
};
|
|
3372
|
+
this.status = new ServerStatus(ctx);
|
|
3373
|
+
this.elicitation = new ElicitationHandlers(ctx);
|
|
3374
|
+
this.authorization = new AuthorizationController(ctx, this.status, (id) => {
|
|
3375
|
+
this.establishConnection(id).catch((error) => {
|
|
3376
|
+
if (error instanceof ServerLaneCancelledError) return;
|
|
3377
|
+
console.error("[MCPClientManager] Reconnecting after a declined step-up failed:", error);
|
|
3378
|
+
});
|
|
3379
|
+
});
|
|
3380
|
+
this.servers = new ServerController(ctx, this.status, this.authorization, this.elicitation, {
|
|
3381
|
+
connectToServer: (id) => this.connectToServer(id),
|
|
3382
|
+
discoverIfConnected: (...args) => this.discoverIfConnected(...args)
|
|
3383
|
+
});
|
|
3384
|
+
this.ctx = ctx;
|
|
3385
|
+
}
|
|
3386
|
+
/** Restore persisted HTTP and RPC connections before the host handles work. */
|
|
3387
|
+
async onStart() {
|
|
3388
|
+
if ((await this.lifecycle.storage.get(MCP_SCHEMA_VERSION_KEY) ?? 0) < CURRENT_MCP_SCHEMA_VERSION) {
|
|
3389
|
+
ensureMcpServerTable(this.lifecycle.storage);
|
|
3390
|
+
await this.lifecycle.storage.put(MCP_SCHEMA_VERSION_KEY, CURRENT_MCP_SCHEMA_VERSION);
|
|
3391
|
+
}
|
|
3392
|
+
await this.restoreConnectionsFromStorage(this._name);
|
|
3393
|
+
this.servers.restoreRpc();
|
|
3394
|
+
this.ctx.stateChanged();
|
|
3395
|
+
}
|
|
3396
|
+
/** Intercept a registered MCP OAuth callback request. */
|
|
3397
|
+
async onRequest(context) {
|
|
3398
|
+
const { request } = context;
|
|
3399
|
+
if (!this.isCallbackRequest(request)) return void 0;
|
|
3400
|
+
const result = await this.handleCallbackRequest(request);
|
|
3401
|
+
if (result.authSuccess) this.establishConnection(result.serverId).catch((error) => {
|
|
3402
|
+
if (error instanceof ServerLaneCancelledError) return;
|
|
3403
|
+
console.error("[MCPClientManager] Connection establishment after OAuth failed:", error);
|
|
3404
|
+
});
|
|
3405
|
+
return oauthCallbackResponse(result, request, this.getOAuthCallbackConfig());
|
|
3406
|
+
}
|
|
3407
|
+
/**
|
|
3408
|
+
* Register an MCP server connection without connecting
|
|
3409
|
+
* Creates the connection object, sets up observability, and saves to storage
|
|
3410
|
+
*
|
|
3411
|
+
* @param id Server ID
|
|
3412
|
+
* @param options Registration options including URL, name, callback URL, and connection config
|
|
3413
|
+
* @returns Server ID
|
|
3414
|
+
*/
|
|
3415
|
+
async registerServer(id, options) {
|
|
3416
|
+
this.servers.register(id, options);
|
|
3417
|
+
return id;
|
|
3418
|
+
}
|
|
3419
|
+
/**
|
|
3420
|
+
* Connect to an already registered MCP server and initialize the connection.
|
|
3421
|
+
*
|
|
3422
|
+
* For OAuth servers, returns `{ state: "authenticating", authUrl, clientId? }`.
|
|
3423
|
+
* The user must complete the OAuth flow via the authUrl, which triggers a
|
|
3424
|
+
* callback handled by `handleCallbackRequest()`.
|
|
3425
|
+
*
|
|
3426
|
+
* For non-OAuth servers, establishes the transport connection and returns
|
|
3427
|
+
* `{ state: "connected" }`. Call `discoverIfConnected()` afterwards to
|
|
3428
|
+
* discover capabilities and transition to "ready" state.
|
|
3429
|
+
*
|
|
3430
|
+
* @param id Server ID (must be registered first via registerServer())
|
|
3431
|
+
* @returns Connection result with current state and OAuth info (if applicable)
|
|
3432
|
+
*/
|
|
3433
|
+
async connectToServer(id) {
|
|
3434
|
+
return this.servers.connect(id);
|
|
3435
|
+
}
|
|
3436
|
+
/**
|
|
3437
|
+
* Discover server capabilities if connection is in CONNECTED or READY state.
|
|
3438
|
+
* Transitions to DISCOVERING then READY (or CONNECTED on error).
|
|
3439
|
+
* Can be called to refresh server capabilities (e.g., from a UI refresh button).
|
|
3440
|
+
*
|
|
3441
|
+
* Runs after any connection work already queued for the same server, so a
|
|
3442
|
+
* call made during another discovery waits for it and then refreshes again.
|
|
3443
|
+
*
|
|
3444
|
+
* @param serverId The server ID to discover
|
|
3445
|
+
* @param options Optional configuration
|
|
3446
|
+
* @param options.timeoutMs Timeout in milliseconds (default: 30000)
|
|
3447
|
+
* @returns Result with current state and optional error, or undefined if connection not found
|
|
3448
|
+
*/
|
|
3449
|
+
async discoverIfConnected(serverId, options = {}) {
|
|
3450
|
+
return this.servers.discover(serverId, options);
|
|
3451
|
+
}
|
|
3452
|
+
/**
|
|
3453
|
+
* Establish connection in the background after OAuth completion.
|
|
3454
|
+
* This method connects to the server and discovers its capabilities.
|
|
3455
|
+
* The connection is automatically tracked so that `waitForConnections()`
|
|
3456
|
+
* will include it.
|
|
3457
|
+
* @param serverId The server ID to establish connection for
|
|
3458
|
+
*/
|
|
3459
|
+
async establishConnection(serverId) {
|
|
3460
|
+
return this.servers.establish(serverId);
|
|
3461
|
+
}
|
|
3462
|
+
/**
|
|
3463
|
+
* @internal Connect a registered server and discover its capabilities, as
|
|
3464
|
+
* one unit of lane work. A failure is recorded.
|
|
3465
|
+
*/
|
|
3466
|
+
connectAndDiscover(id) {
|
|
3467
|
+
return this.servers.connectAndDiscover(id);
|
|
3468
|
+
}
|
|
3469
|
+
/**
|
|
3470
|
+
* @internal Bring an already-registered server to a settled state once the
|
|
3471
|
+
* work queued for it has run, for `addMcpServer()`. Never retries a failed
|
|
3472
|
+
* server.
|
|
3473
|
+
*/
|
|
3474
|
+
settleServer(id) {
|
|
3475
|
+
return this.servers.settle(id);
|
|
3476
|
+
}
|
|
3477
|
+
/**
|
|
3478
|
+
* @internal Try a server again because someone asked: forget a recorded
|
|
3479
|
+
* failure, its link and the step-up budget, and connect now.
|
|
3480
|
+
*/
|
|
3481
|
+
reconnectServer(id) {
|
|
3482
|
+
return this.servers.reconnect(id);
|
|
3483
|
+
}
|
|
3484
|
+
/**
|
|
3485
|
+
* Restore persisted HTTP MCP connections. Runs once per wake.
|
|
3486
|
+
*
|
|
3487
|
+
* @param clientName - Durable Object identity used to scope OAuth state.
|
|
3488
|
+
*/
|
|
3489
|
+
async restoreConnectionsFromStorage(clientName) {
|
|
3490
|
+
if (this._isRestored) return;
|
|
3491
|
+
await this.servers.restore(clientName);
|
|
3492
|
+
this._isRestored = true;
|
|
3493
|
+
}
|
|
3494
|
+
/**
|
|
3495
|
+
* Wait for all in-flight connection and discovery operations to settle.
|
|
3496
|
+
* This is useful when you need MCP tools to be available before proceeding,
|
|
3497
|
+
* e.g. before calling getAITools() after the agent wakes from hibernation.
|
|
3498
|
+
*
|
|
3499
|
+
* Returns once every pending connection has either connected and discovered,
|
|
3500
|
+
* failed, or timed out. Never rejects.
|
|
3501
|
+
*
|
|
3502
|
+
* @param options.timeout - Maximum time in milliseconds to wait.
|
|
3503
|
+
* `0` returns immediately without waiting.
|
|
3504
|
+
* `undefined` (default) waits indefinitely.
|
|
3505
|
+
*/
|
|
3506
|
+
async waitForConnections(options) {
|
|
3507
|
+
const pending = this._lanes.pending();
|
|
3508
|
+
if (pending.length === 0) return;
|
|
3509
|
+
if (options?.timeout != null && options.timeout <= 0) return;
|
|
3510
|
+
const settled = Promise.allSettled(pending);
|
|
3511
|
+
if (options?.timeout == null) {
|
|
3512
|
+
await settled;
|
|
3513
|
+
return;
|
|
3514
|
+
}
|
|
3515
|
+
let timerId;
|
|
3516
|
+
const timer = new Promise((resolve) => {
|
|
3517
|
+
timerId = setTimeout(resolve, options.timeout);
|
|
3518
|
+
});
|
|
3519
|
+
await Promise.race([settled, timer]);
|
|
3520
|
+
clearTimeout(timerId);
|
|
3521
|
+
}
|
|
3522
|
+
/**
|
|
3523
|
+
* Rename a server's id, in-place, across every place the id is used as a
|
|
3524
|
+
* key: its row, its connection, its provider, its OAuth storage keys under
|
|
3525
|
+
* `/{clientName}/{oldId}/...`. Used to migrate a
|
|
3526
|
+
* server registered under an auto-generated id to a caller-supplied
|
|
3527
|
+
* stable id (see `Agent.addMcpServer`'s `{ id }` option).
|
|
3528
|
+
*
|
|
3529
|
+
* A no-op when `oldId === newId`. Throws when a row already exists under
|
|
3530
|
+
* `newId`; the caller is expected to have verified uniqueness.
|
|
3531
|
+
*
|
|
3532
|
+
* @internal Exposed for `Agent.addMcpServer` JIT-migration.
|
|
3533
|
+
*/
|
|
3534
|
+
async migrateServerId(oldId, newId, clientName) {
|
|
3535
|
+
return this.servers.migrate(oldId, newId, clientName);
|
|
3536
|
+
}
|
|
3537
|
+
/**
|
|
3538
|
+
* Closes a connection to an MCP server
|
|
3539
|
+
* @param id The id of the connection to close
|
|
3540
|
+
*/
|
|
3541
|
+
async closeConnection(id) {
|
|
3542
|
+
return this.servers.close(id);
|
|
3543
|
+
}
|
|
3544
|
+
/**
|
|
3545
|
+
* Closes every in-memory connection. Servers stay stored, and their
|
|
3546
|
+
* callback URLs still match incoming OAuth requests; use removeServer()
|
|
3547
|
+
* to delete a server.
|
|
3548
|
+
*/
|
|
3549
|
+
async closeAllConnections() {
|
|
3550
|
+
return this.servers.closeAll();
|
|
3551
|
+
}
|
|
3552
|
+
/**
|
|
3553
|
+
* Remove an MCP server - closes connection if active and removes from storage.
|
|
3554
|
+
*/
|
|
3555
|
+
async removeServer(serverId) {
|
|
3556
|
+
return this.servers.remove(serverId);
|
|
3557
|
+
}
|
|
3558
|
+
/**
|
|
3559
|
+
* List all MCP servers from storage
|
|
3560
|
+
*/
|
|
3561
|
+
listServers() {
|
|
3562
|
+
return this.ctx.store.list();
|
|
3563
|
+
}
|
|
3564
|
+
/** Get saved RPC servers from storage (servers with `rpc://` URLs). */
|
|
3565
|
+
getRpcServersFromStorage() {
|
|
3566
|
+
return this.ctx.store.listRpc();
|
|
3567
|
+
}
|
|
3568
|
+
/**
|
|
3569
|
+
* Save an RPC server to storage for hibernation recovery.
|
|
3570
|
+
* The binding name is stored so this manager can resolve the namespace from
|
|
3571
|
+
* its runtime environment during restore.
|
|
3572
|
+
*/
|
|
3573
|
+
saveRpcServerToStorage(id, name, normalizedName, bindingName, props) {
|
|
3574
|
+
this.ctx.store.save({
|
|
3575
|
+
id,
|
|
3576
|
+
name,
|
|
3577
|
+
server_url: `${RPC_DO_PREFIX}${normalizedName}`,
|
|
3578
|
+
client_id: null,
|
|
3579
|
+
auth_url: null,
|
|
3580
|
+
callback_url: "",
|
|
3581
|
+
server_options: encodeMcpServerOptions({
|
|
3582
|
+
bindingName,
|
|
3583
|
+
props,
|
|
3584
|
+
capabilities: this.elicitation.capabilities()
|
|
3585
|
+
})
|
|
3586
|
+
});
|
|
3587
|
+
}
|
|
3588
|
+
/**
|
|
3589
|
+
* Connect to and register an MCP server
|
|
3590
|
+
*
|
|
3591
|
+
* @deprecated This method is maintained for backward compatibility.
|
|
3592
|
+
* For new code, use registerServer() and connectToServer() separately.
|
|
3593
|
+
*
|
|
3594
|
+
* @param url Server URL
|
|
3595
|
+
* @param options Connection options
|
|
3596
|
+
* @returns Object with server ID, auth URL (if OAuth), and client ID (if OAuth)
|
|
3597
|
+
*/
|
|
3598
|
+
async connect(url, options = {}) {
|
|
3599
|
+
return legacyConnect(this.ctx, this.servers, this, url, options);
|
|
3600
|
+
}
|
|
3601
|
+
/** Whether a request is an OAuth callback for one of this manager's servers. */
|
|
3602
|
+
isCallbackRequest(req) {
|
|
3603
|
+
return this.authorization.isCallback(req);
|
|
3604
|
+
}
|
|
3605
|
+
/**
|
|
3606
|
+
* Complete the OAuth flow a callback request belongs to: verify its state,
|
|
3607
|
+
* exchange its code, and leave the connection ready to reconnect. A
|
|
3608
|
+
* callback for a flow that was already accepted is consumed as a stale
|
|
3609
|
+
* success; one whose state cannot be verified changes nothing.
|
|
3610
|
+
*/
|
|
3611
|
+
async handleCallbackRequest(req) {
|
|
3612
|
+
return this.authorization.handleCallback(req);
|
|
3613
|
+
}
|
|
3614
|
+
/**
|
|
3615
|
+
* Configure OAuth callback handling
|
|
3616
|
+
* @param config OAuth callback configuration
|
|
3617
|
+
*/
|
|
3618
|
+
configureOAuthCallback(config) {
|
|
3619
|
+
this.authorization.configureCallback(config);
|
|
3620
|
+
}
|
|
3621
|
+
/**
|
|
3622
|
+
* Get the current OAuth callback configuration
|
|
3623
|
+
* @returns The current OAuth callback configuration
|
|
3624
|
+
*/
|
|
3625
|
+
getOAuthCallbackConfig() {
|
|
3626
|
+
return this.authorization.getCallbackConfig();
|
|
3627
|
+
}
|
|
3628
|
+
/**
|
|
3629
|
+
* Configure handling for server-initiated `elicitation/create` requests.
|
|
3630
|
+
*
|
|
3631
|
+
* The handler is held in memory only and applied to every MCP connection
|
|
3632
|
+
* created or restored by this manager. Call this before registering
|
|
3633
|
+
* connections when you want the initial MCP handshake to advertise
|
|
3634
|
+
* handler-driven form- and url-mode elicitation. Existing active connections
|
|
3635
|
+
* keep their negotiated capabilities until they reconnect.
|
|
3636
|
+
*
|
|
3637
|
+
* The advertised modes are persisted with each stored server, so
|
|
3638
|
+
* connections restored after hibernation re-advertise them at the handshake
|
|
3639
|
+
* even when this is called later in the wake-up (e.g. from onStart) — the
|
|
3640
|
+
* handlers attach to the live connections as soon as this runs.
|
|
3641
|
+
*
|
|
3642
|
+
* Pass undefined to clear the handler.
|
|
3643
|
+
*
|
|
3644
|
+
* @param handlers Elicitation handlers keyed by mode, each scoped with the server id that sent the request
|
|
3645
|
+
*/
|
|
3646
|
+
configureElicitationHandlers(handlers) {
|
|
3647
|
+
this.elicitation.configure(handlers);
|
|
3648
|
+
}
|
|
3649
|
+
/**
|
|
3650
|
+
* @param filter - Optional filter to scope results to specific servers
|
|
3651
|
+
* @returns namespaced list of tools
|
|
3652
|
+
*/
|
|
3653
|
+
listTools(filter) {
|
|
3654
|
+
return getNamespacedData(this.connectionsFor(filter), "tools");
|
|
3655
|
+
}
|
|
3656
|
+
/**
|
|
3657
|
+
* @param filter - Optional filter to scope results to specific servers
|
|
3658
|
+
* @returns namespaced list of prompts
|
|
3659
|
+
*/
|
|
3660
|
+
listPrompts(filter) {
|
|
3661
|
+
return getNamespacedData(this.connectionsFor(filter), "prompts");
|
|
3662
|
+
}
|
|
3663
|
+
/**
|
|
3664
|
+
* @param filter - Optional filter to scope results to specific servers
|
|
3665
|
+
* @returns namespaced list of resources
|
|
3666
|
+
*/
|
|
3667
|
+
listResources(filter) {
|
|
3668
|
+
return getNamespacedData(this.connectionsFor(filter), "resources");
|
|
3669
|
+
}
|
|
3670
|
+
/**
|
|
3671
|
+
* @param filter - Optional filter to scope results to specific servers
|
|
3672
|
+
* @returns namespaced list of resource templates
|
|
3673
|
+
*/
|
|
3674
|
+
listResourceTemplates(filter) {
|
|
3675
|
+
return getNamespacedData(this.connectionsFor(filter), "resourceTemplates");
|
|
3676
|
+
}
|
|
3677
|
+
/**
|
|
3678
|
+
* Convert connected MCP tools for the AI SDK. Converted schemas are reused
|
|
3679
|
+
* while a live connection retains the same catalog array and schema-source
|
|
3680
|
+
* identities; tool records and execute closures are rebuilt on every call.
|
|
3681
|
+
*
|
|
3682
|
+
* @param filter - Optional filter to scope results to specific servers
|
|
3683
|
+
* @returns a set of tools that you can use with the AI SDK
|
|
3684
|
+
*/
|
|
3685
|
+
getAITools(filter) {
|
|
3686
|
+
return this.aiTools.convert(this.connectionsFor(filter), (params) => this.callTool(params));
|
|
3687
|
+
}
|
|
3688
|
+
/**
|
|
3689
|
+
* @deprecated this has been renamed to getAITools(), and unstable_getAITools will be removed in the next major version
|
|
3690
|
+
* @param filter - Optional filter to scope results to specific servers
|
|
3691
|
+
* @returns a set of tools that you can use with the AI SDK
|
|
3692
|
+
*/
|
|
3693
|
+
unstable_getAITools(filter) {
|
|
3694
|
+
if (!this.didWarnAboutUnstableGetAITools) {
|
|
3695
|
+
this.didWarnAboutUnstableGetAITools = true;
|
|
3696
|
+
console.warn("unstable_getAITools is deprecated, use getAITools instead. unstable_getAITools will be removed in the next major version.");
|
|
3697
|
+
}
|
|
3698
|
+
return this.getAITools(filter);
|
|
3699
|
+
}
|
|
3700
|
+
async callTool(params, schemaOrOptions, options) {
|
|
3701
|
+
const { serverId, ...mcpParams } = params;
|
|
3702
|
+
const name = mcpParams.name.replace(`${serverId}.`, "");
|
|
3703
|
+
return this.authorization.recoverRequest(serverId, (conn) => callV2Tool(conn.client, {
|
|
3704
|
+
...mcpParams,
|
|
3705
|
+
name
|
|
3706
|
+
}, schemaOrOptions, options));
|
|
3707
|
+
}
|
|
3708
|
+
/**
|
|
3709
|
+
* Namespaced version of readResource
|
|
3710
|
+
*/
|
|
3711
|
+
readResource(params, options) {
|
|
3712
|
+
const { serverId, ...mcpParams } = params;
|
|
3713
|
+
return this.authorization.recoverRequest(serverId, (conn) => conn.client.readResource(mcpParams, options));
|
|
3714
|
+
}
|
|
3715
|
+
/**
|
|
3716
|
+
* Namespaced version of getPrompt
|
|
3717
|
+
*/
|
|
3718
|
+
getPrompt(params, options) {
|
|
3719
|
+
const { serverId, ...mcpParams } = params;
|
|
3720
|
+
return this.authorization.recoverRequest(serverId, (conn) => conn.client.getPrompt(mcpParams, options));
|
|
3721
|
+
}
|
|
3722
|
+
/**
|
|
3723
|
+
* Dispose the manager and all resources.
|
|
3724
|
+
*/
|
|
3725
|
+
async dispose() {
|
|
3726
|
+
try {
|
|
3727
|
+
await this.closeAllConnections();
|
|
3728
|
+
} finally {
|
|
3729
|
+
this._onServerStateChanged.dispose();
|
|
3730
|
+
this._onObservabilityEvent.dispose();
|
|
3731
|
+
}
|
|
3732
|
+
}
|
|
3733
|
+
connectionsFor(filter) {
|
|
3734
|
+
return filterConnections(this.mcpConnections, () => this.ctx.store.list(), filter);
|
|
3735
|
+
}
|
|
3736
|
+
};
|
|
3737
|
+
//#endregion
|
|
3738
|
+
export { MCPConnectionState as a, getNamespacedData as c, isDurableObjectNamespace as d, DisposableStore as f, ensureMcpServerTable as i, RPCClientTransport as l, MCP_SERVER_ID_MAX_LENGTH as n, MCPAuthorizationRequiredError as o, normalizeServerId as r, MCPConnectionNotFoundError as s, MCPClientManager as t, RPC_DO_PREFIX as u };
|
|
3739
|
+
|
|
3740
|
+
//# sourceMappingURL=client-CkT8voRY.js.map
|