@zackbart/connecta 0.6.1 → 0.7.1
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/CHANGELOG.md +294 -0
- package/README.md +24 -20
- package/dist/auth/bearer.d.ts +4 -3
- package/dist/auth/bearer.d.ts.map +1 -1
- package/dist/auth/bearer.js +10 -8
- package/dist/auth/bearer.js.map +1 -1
- package/dist/auth/clerk.d.ts +8 -7
- package/dist/auth/clerk.d.ts.map +1 -1
- package/dist/auth/clerk.js +27 -8
- package/dist/auth/clerk.js.map +1 -1
- package/dist/connector-scope.d.ts +13 -0
- package/dist/connector-scope.d.ts.map +1 -0
- package/dist/connector-scope.js +35 -0
- package/dist/connector-scope.js.map +1 -0
- package/dist/connectors/api.d.ts +5 -5
- package/dist/connectors/api.d.ts.map +1 -1
- package/dist/connectors/remote-mcp.d.ts +27 -4
- package/dist/connectors/remote-mcp.d.ts.map +1 -1
- package/dist/connectors/remote-mcp.js +400 -19
- package/dist/connectors/remote-mcp.js.map +1 -1
- package/dist/credential-health.d.ts +8 -5
- package/dist/credential-health.d.ts.map +1 -1
- package/dist/credential-health.js +99 -51
- package/dist/credential-health.js.map +1 -1
- package/dist/credentials.d.ts +51 -2
- package/dist/credentials.d.ts.map +1 -1
- package/dist/credentials.js +68 -3
- package/dist/credentials.js.map +1 -1
- package/dist/execute.d.ts.map +1 -1
- package/dist/execute.js +10 -8
- package/dist/execute.js.map +1 -1
- package/dist/index.d.ts +84 -83
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +74 -24
- package/dist/index.js.map +1 -1
- package/dist/meta-tools.d.ts +28 -3
- package/dist/meta-tools.d.ts.map +1 -1
- package/dist/meta-tools.js +131 -16
- package/dist/meta-tools.js.map +1 -1
- package/dist/registry.d.ts +3 -2
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +4 -3
- package/dist/registry.js.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +152 -52
- package/dist/server.js.map +1 -1
- package/dist/toolkits.js +1 -1
- package/dist/types.d.ts +41 -27
- package/dist/types.d.ts.map +1 -1
- package/dist/ui.d.ts +24 -10
- package/dist/ui.d.ts.map +1 -1
- package/dist/ui.js +594 -172
- package/dist/ui.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -2
- package/src/auth/bearer.ts +10 -8
- package/src/auth/clerk.ts +28 -9
- package/src/connector-scope.ts +41 -0
- package/src/connectors/api.ts +5 -5
- package/src/connectors/remote-mcp.ts +489 -35
- package/src/credential-health.ts +120 -57
- package/src/credentials.ts +96 -3
- package/src/execute.ts +18 -7
- package/src/index.ts +174 -107
- package/src/meta-tools.ts +173 -24
- package/src/registry.ts +4 -3
- package/src/server.ts +191 -70
- package/src/toolkits.ts +1 -1
- package/src/types.ts +41 -27
- package/src/ui.ts +631 -170
- package/src/version.ts +1 -1
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Enough for local transport abort/close without letting cleanup own latency. */
|
|
2
|
+
const CONNECTOR_SCOPE_CLOSE_BUDGET_MS = 100;
|
|
3
|
+
/**
|
|
4
|
+
* Tell a connector that a scope owned by the core has ended.
|
|
5
|
+
*
|
|
6
|
+
* Scope teardown is deliberately best-effort: a missing hook is a no-op and a
|
|
7
|
+
* rejected hook is swallowed so cleanup can never replace the probe result that
|
|
8
|
+
* caused it. The hook gets a small, fixed completion window so edge runtimes do
|
|
9
|
+
* not cut off a real close as the response ends, but one that never settles
|
|
10
|
+
* cannot hold the completed probe open indefinitely. Callers own the
|
|
11
|
+
* at-most-once guarantee and must not use the scope again after this returns.
|
|
12
|
+
*/
|
|
13
|
+
export async function closeConnectorScope(connector, ctx) {
|
|
14
|
+
try {
|
|
15
|
+
const closing = connector.closeScope?.(ctx);
|
|
16
|
+
if (!closing)
|
|
17
|
+
return;
|
|
18
|
+
await new Promise((resolve) => {
|
|
19
|
+
const timer = setTimeout(resolve, CONNECTOR_SCOPE_CLOSE_BUDGET_MS);
|
|
20
|
+
// Both handlers stay attached after the timer wins, so a late rejection
|
|
21
|
+
// is still consumed rather than becoming an unhandled rejection.
|
|
22
|
+
closing.then(() => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
resolve();
|
|
25
|
+
}, () => {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
resolve();
|
|
28
|
+
});
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// The scope is over whether or not the connector managed to clean it up.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=connector-scope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connector-scope.js","sourceRoot":"","sources":["../src/connector-scope.ts"],"names":[],"mappings":"AAEA,kFAAkF;AAClF,MAAM,+BAA+B,GAAG,GAAG,CAAC;AAE5C;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,SAAoB,EACpB,GAAqB;IAErB,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,SAAS,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,CAAC;QAC5C,IAAI,CAAC,OAAO;YAAE,OAAO;QACrB,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE;YAClC,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,EAAE,+BAA+B,CAAC,CAAC;YACnE,wEAAwE;YACxE,iEAAiE;YACjE,OAAO,CAAC,IAAI,CACV,GAAG,EAAE;gBACH,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,EAAE,CAAC;YACZ,CAAC,EACD,GAAG,EAAE;gBACH,YAAY,CAAC,KAAK,CAAC,CAAC;gBACpB,OAAO,EAAE,CAAC;YACZ,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,yEAAyE;IAC3E,CAAC;AACH,CAAC"}
|
package/dist/connectors/api.d.ts
CHANGED
|
@@ -20,9 +20,9 @@ export interface ApiOptions {
|
|
|
20
20
|
/**
|
|
21
21
|
* Max inline result size (bytes) for this connector's tools before
|
|
22
22
|
* call_tool/batch_call truncate and stash the full text for get_result
|
|
23
|
-
* paging. Overrides the deployment's `maxResultBytes`; omit to inherit
|
|
24
|
-
* Must be a whole number of bytes >= 1; anything else warns at startup
|
|
25
|
-
* is ignored.
|
|
23
|
+
* paging. Overrides the deployment's `calls.maxResultBytes`; omit to inherit
|
|
24
|
+
* it. Must be a whole number of bytes >= 1; anything else warns at startup
|
|
25
|
+
* and is ignored.
|
|
26
26
|
*/
|
|
27
27
|
maxResultBytes?: number;
|
|
28
28
|
/**
|
|
@@ -30,9 +30,9 @@ export interface ApiOptions {
|
|
|
30
30
|
* meta-tool as `connector:<id>`. See `Connector.usageGuide`.
|
|
31
31
|
*/
|
|
32
32
|
usageGuide?: string;
|
|
33
|
-
/** Optional operator-managed credential exposed through ctx.credential and /
|
|
33
|
+
/** Optional operator-managed credential exposed through ctx.credential and /credentials. */
|
|
34
34
|
credential?: ConnectorCredentialConfig;
|
|
35
|
-
/** Optional validation behind /
|
|
35
|
+
/** Optional validation behind /credentials' Test action. */
|
|
36
36
|
testCredential?: (value: string, ctx: ConnectorContext) => Promise<CredentialTestResult>;
|
|
37
37
|
/** Optional validation for named multi-field credentials. */
|
|
38
38
|
testCredentials?: (values: ConnectorCredentialValues, ctx: ConnectorContext) => Promise<CredentialTestResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/connectors/api.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,yBAAyB,EACzB,yBAAyB,EACzB,gBAAgB,EAChB,oBAAoB,EACpB,UAAU,EACV,eAAe,EAEhB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4DAA4D;IAC5D,WAAW,CAAC,EAAE,UAAU,CAAC;IACzB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,UAAU,CAAC;IAC1B;;;OAGG;IACH,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;CAC3E;AAED,MAAM,WAAW,UAAU;IACzB,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/connectors/api.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,yBAAyB,EACzB,yBAAyB,EACzB,gBAAgB,EAChB,oBAAoB,EACpB,UAAU,EACV,eAAe,EAEhB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,4DAA4D;IAC5D,WAAW,CAAC,EAAE,UAAU,CAAC;IACzB,0EAA0E;IAC1E,YAAY,CAAC,EAAE,UAAU,CAAC;IAC1B;;;OAGG;IACH,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,OAAO,EAAE,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;CAC3E;AAED,MAAM,WAAW,UAAU;IACzB,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,4FAA4F;IAC5F,UAAU,CAAC,EAAE,yBAAyB,CAAC;IACvC,4DAA4D;IAC5D,cAAc,CAAC,EAAE,CACf,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,gBAAgB,KAClB,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACnC,6DAA6D;IAC7D,eAAe,CAAC,EAAE,CAChB,MAAM,EAAE,yBAAyB,EACjC,GAAG,EAAE,gBAAgB,KAClB,OAAO,CAAC,oBAAoB,CAAC,CAAC;IACnC;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,KAAK,EAAE,OAAO,EAAE,CAAC;CAClB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,GAAG,SAAS,CAkD3D"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
1
|
+
import type { FetchLike, Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
2
|
+
import { ConnectorCallError } from "../errors.js";
|
|
2
3
|
import type { Connector, ConnectorContext, Logger } from "../types.js";
|
|
3
4
|
export type RemoteMcpAuth = {
|
|
4
5
|
type: "headers";
|
|
@@ -6,6 +7,7 @@ export type RemoteMcpAuth = {
|
|
|
6
7
|
} | {
|
|
7
8
|
type: "oauth";
|
|
8
9
|
};
|
|
10
|
+
export type RemoteMcpRedirectPolicy = "none" | "same-origin";
|
|
9
11
|
export interface RemoteMcpOptions {
|
|
10
12
|
url: string;
|
|
11
13
|
/** Human-readable display name; the connector id remains the address prefix. */
|
|
@@ -14,9 +16,9 @@ export interface RemoteMcpOptions {
|
|
|
14
16
|
/**
|
|
15
17
|
* Max inline result size (bytes) for this connector's tools before
|
|
16
18
|
* call_tool/batch_call truncate and stash the full text for get_result
|
|
17
|
-
* paging. Overrides the deployment's `maxResultBytes`; omit to inherit
|
|
18
|
-
* Must be a whole number of bytes >= 1; anything else warns at startup
|
|
19
|
-
* is ignored.
|
|
19
|
+
* paging. Overrides the deployment's `calls.maxResultBytes`; omit to inherit
|
|
20
|
+
* it. Must be a whole number of bytes >= 1; anything else warns at startup
|
|
21
|
+
* and is ignored.
|
|
20
22
|
*/
|
|
21
23
|
maxResultBytes?: number;
|
|
22
24
|
/**
|
|
@@ -25,6 +27,14 @@ export interface RemoteMcpOptions {
|
|
|
25
27
|
*/
|
|
26
28
|
usageGuide?: string;
|
|
27
29
|
auth?: RemoteMcpAuth;
|
|
30
|
+
/**
|
|
31
|
+
* Downstream HTTP redirect policy. Defaults to `"none"`: every redirect is
|
|
32
|
+
* rejected. `"same-origin"` follows at most five redirects while preserving
|
|
33
|
+
* standard 301/302/303/307/308 method semantics. Cross-origin redirects and
|
|
34
|
+
* HTTPS downgrades are always refused, so credentials never cross the
|
|
35
|
+
* configured request's origin.
|
|
36
|
+
*/
|
|
37
|
+
redirects?: RemoteMcpRedirectPolicy;
|
|
28
38
|
/**
|
|
29
39
|
* Refuse to connect to a non-`https://` `url` at construction (default
|
|
30
40
|
* false). Loopback hosts (`localhost`, `127.0.0.1`, `[::1]`) are always
|
|
@@ -45,6 +55,19 @@ export interface RemoteMcpOptions {
|
|
|
45
55
|
*/
|
|
46
56
|
_transportFactory?: (ctx: ConnectorContext) => Transport;
|
|
47
57
|
}
|
|
58
|
+
export declare const MAX_REMOTE_REDIRECT_HOPS = 5;
|
|
59
|
+
export declare class RemoteMcpRedirectError extends ConnectorCallError {
|
|
60
|
+
constructor(connectorId: string, reason: string);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Wrap fetch with explicit, bounded redirect handling.
|
|
64
|
+
*
|
|
65
|
+
* The starting URL of each fetch call is trusted by its caller (the configured
|
|
66
|
+
* MCP endpoint, or an OAuth URL discovered by the pinned SDK). Only Location
|
|
67
|
+
* values are policy-controlled here. No rejected target is ever fetched, so
|
|
68
|
+
* arbitrary static header names receive the same protection as Authorization.
|
|
69
|
+
*/
|
|
70
|
+
export declare function redirectSafeFetch(connectorId: string, policy?: RemoteMcpRedirectPolicy, baseFetch?: FetchLike): FetchLike;
|
|
48
71
|
/**
|
|
49
72
|
* Proxy a downstream remote MCP server. SDK clients and transports are scoped
|
|
50
73
|
* to one inbound request: reused by calls within a batch/execute_code run, but
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-mcp.d.ts","sourceRoot":"","sources":["../../src/connectors/remote-mcp.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"remote-mcp.d.ts","sourceRoot":"","sources":["../../src/connectors/remote-mcp.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,SAAS,EACT,SAAS,EACV,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,KAAK,EACV,SAAS,EACT,gBAAgB,EAEhB,MAAM,EAEP,MAAM,aAAa,CAAC;AAErB,MAAM,MAAM,aAAa,GACrB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,GACpD;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAEtB,MAAM,MAAM,uBAAuB,GAAG,MAAM,GAAG,aAAa,CAAC;AAE7D,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,aAAa,CAAC;IACrB;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,uBAAuB,CAAC;IACpC;;;;;;OAMG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,GAAG,EAAE,gBAAgB,KAAK,SAAS,CAAC;CAC1D;AAwJD,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAW1C,qBAAa,sBAAuB,SAAQ,kBAAkB;gBAChD,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAOhD;AAaD;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAC/B,WAAW,EAAE,MAAM,EACnB,MAAM,GAAE,uBAAgC,EACxC,SAAS,GAAE,SAAiB,GAC3B,SAAS,CA2EX;AAiBD;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,gBAAgB,GAAG,SAAS,CAwfvE"}
|
|
@@ -5,15 +5,222 @@ import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validatio
|
|
|
5
5
|
import { KvOAuthProvider } from "../auth/downstream-oauth.js";
|
|
6
6
|
import { ConnectorCallError } from "../errors.js";
|
|
7
7
|
import { CONNECTA_VERSION } from "../version.js";
|
|
8
|
+
/**
|
|
9
|
+
* How long a downstream gets to answer the session-termination DELETE before
|
|
10
|
+
* teardown stops waiting. Deliberately a fraction of the core's scope-close
|
|
11
|
+
* budget (`closeConnectorScope`), so the whole teardown still lands inside the
|
|
12
|
+
* window that budget makes safe on an edge runtime: whatever is still in flight
|
|
13
|
+
* when this expires is aborted by the close that immediately follows. What that
|
|
14
|
+
* costs is only the acknowledgement — the DELETE is headers-only and has long
|
|
15
|
+
* since gone out — so a slow provider still usually ends the session; it just
|
|
16
|
+
* does not get to tell us so.
|
|
17
|
+
*/
|
|
18
|
+
const TERMINATE_SESSION_BUDGET_MS = 50;
|
|
19
|
+
/**
|
|
20
|
+
* Ceiling on the tools one catalog refresh will accumulate while walking
|
|
21
|
+
* `tools/list`.
|
|
22
|
+
*
|
|
23
|
+
* This is the bound that matters, and pages are the wrong dimension to put it
|
|
24
|
+
* in: the *server* picks the page size, so a page ceiling is a tool ceiling
|
|
25
|
+
* multiplied by a number connecta can neither observe in advance nor control.
|
|
26
|
+
* At ten tools a page, 100 pages is 1,000 tools; at a hundred, 10,000 — and
|
|
27
|
+
* connecta's own large-catalog envelope is benchmarked to 100,000 (issue #82).
|
|
28
|
+
* A page ceiling low enough to be a real defense therefore sits *inside* the
|
|
29
|
+
* catalog sizes this product exists to serve. Worse, the common conformant
|
|
30
|
+
* idiom is to advertise a `nextCursor` whenever a page came back full and then
|
|
31
|
+
* serve one empty page to terminate, so a perfectly well-behaved 10,000-tool
|
|
32
|
+
* server paging at 100 spends 101 requests: bound the pages and its entire
|
|
33
|
+
* catalog fails, for doing nothing wrong.
|
|
34
|
+
*
|
|
35
|
+
* So the ceiling goes on accumulated tools — the thing actually held in memory
|
|
36
|
+
* — and it sits at the top of the benchmarked envelope rather than below it.
|
|
37
|
+
* Deliberately the same philosophy as issue #82's discovery-response bounds:
|
|
38
|
+
* cap the bytes a caller can be made to hold, not the number of round trips it
|
|
39
|
+
* took to get them.
|
|
40
|
+
*/
|
|
41
|
+
const MAX_TOOLS = 100_000;
|
|
42
|
+
/**
|
|
43
|
+
* Absolute backstop on `tools/list` pages in one refresh — a runaway guard, not
|
|
44
|
+
* the primary defense.
|
|
45
|
+
*
|
|
46
|
+
* The walk terminates on its own well before this: a cursor handed back twice
|
|
47
|
+
* is a definite loop, two consecutive pages that add no new tools are a server
|
|
48
|
+
* going nowhere, and MAX_TOOLS caps what any of it can accumulate. This exists
|
|
49
|
+
* only so the loop is finite even if a downstream somehow satisfies all three
|
|
50
|
+
* forever, because the caller's probe deadline abandons the *caller*, not the
|
|
51
|
+
* loop. Set high enough that no honest server reaches it.
|
|
52
|
+
*/
|
|
53
|
+
const MAX_TOOL_PAGES = 10_000;
|
|
54
|
+
/**
|
|
55
|
+
* Re-prime an SDK client's tool-metadata cache from the *full* walked catalog.
|
|
56
|
+
*
|
|
57
|
+
* `Client.listTools()` ends by calling its private `cacheToolMetadata`, which
|
|
58
|
+
* **clears** the output-schema validators and the task-support sets before
|
|
59
|
+
* repopulating them from the page it just received. Call it once per page —
|
|
60
|
+
* which walking the chain necessarily does — and the request-scoped client is
|
|
61
|
+
* left holding metadata for the *last* page alone. `callTool` then finds no
|
|
62
|
+
* validator for every earlier-page tool and silently skips both the "declared
|
|
63
|
+
* an outputSchema but returned no structuredContent" check and the
|
|
64
|
+
* structured-content validation, and finds no task requirement so a
|
|
65
|
+
* required-task tool is dispatched as a plain `tools/call`. Enforcement would
|
|
66
|
+
* depend on which page a tool happened to land on, which is not enforcement.
|
|
67
|
+
*
|
|
68
|
+
* So hand the whole aggregated list back deliberately, once, at the end. The
|
|
69
|
+
* SDK types the method `private`, hence the cast; the SDK version is pinned
|
|
70
|
+
* exactly and `test/remote-mcp-pagination.test.ts` asserts the method still
|
|
71
|
+
* exists, so a bump that renames it fails CI rather than quietly restoring the
|
|
72
|
+
* bug.
|
|
73
|
+
*/
|
|
74
|
+
function primeToolMetadata(client, tools) {
|
|
75
|
+
const prime = client.cacheToolMetadata;
|
|
76
|
+
if (typeof prime !== "function")
|
|
77
|
+
return;
|
|
78
|
+
prime.call(client, tools);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* True for a result-parse failure caused by the page's `nextCursor` itself —
|
|
82
|
+
* in practice `nextCursor: null`, a very common JSON idiom for "no more pages"
|
|
83
|
+
* that the MCP schema does not accept (the chain ends on an *absent* cursor).
|
|
84
|
+
* Duck-typed rather than `instanceof ZodError`: the SDK may parse with its own
|
|
85
|
+
* zod instance, and cross-instance `instanceof` is a coin flip.
|
|
86
|
+
*/
|
|
87
|
+
function isCursorShapeError(err) {
|
|
88
|
+
const issues = err?.issues;
|
|
89
|
+
return (Array.isArray(issues) &&
|
|
90
|
+
issues.some((issue) => {
|
|
91
|
+
const path = issue.path;
|
|
92
|
+
return Array.isArray(path) && path[0] === "nextCursor";
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
8
95
|
function msg(err) {
|
|
9
96
|
return err instanceof Error ? err.message : String(err);
|
|
10
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* End the downstream's session before the connection is torn down.
|
|
100
|
+
*
|
|
101
|
+
* `Client.close()` only unwinds our side — it aborts the transport's controller
|
|
102
|
+
* and fires `onclose`. Spec session termination is a separate DELETE carrying
|
|
103
|
+
* `Mcp-Session-Id`, and without it a stateful provider keeps the session alive
|
|
104
|
+
* until its own (often hour-long) timeout, which a periodic probe would then
|
|
105
|
+
* accumulate several of per connector.
|
|
106
|
+
*
|
|
107
|
+
* Ordering is load-bearing: the SDK sends that DELETE on the transport's
|
|
108
|
+
* AbortSignal, so calling this *after* close would abort the request on issue
|
|
109
|
+
* and silently do nothing. Everything else is best-effort — a transport with no
|
|
110
|
+
* `terminateSession` (a custom one, or an older SDK), a downstream that refuses
|
|
111
|
+
* (405 is a legal answer), errors, or never replies all fall through to the
|
|
112
|
+
* close with the session left to age out as it did before.
|
|
113
|
+
*/
|
|
114
|
+
async function terminateSession(transport) {
|
|
115
|
+
const terminate = transport.terminateSession;
|
|
116
|
+
if (typeof terminate !== "function")
|
|
117
|
+
return;
|
|
118
|
+
// The SDK issues no request at all when no `mcp-session-id` was captured, so
|
|
119
|
+
// a stateless downstream never sees a spurious DELETE.
|
|
120
|
+
const done = (async () => terminate.call(transport))().catch(() => {
|
|
121
|
+
// The session is being abandoned either way; a refusal changes nothing.
|
|
122
|
+
// Caught here rather than at the await below so a late rejection — one
|
|
123
|
+
// arriving after the budget expired — is still consumed.
|
|
124
|
+
});
|
|
125
|
+
await new Promise((resolve) => {
|
|
126
|
+
const timer = setTimeout(resolve, TERMINATE_SESSION_BUDGET_MS);
|
|
127
|
+
done.then(() => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
resolve();
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
}
|
|
11
133
|
function isLoopbackHost(hostname) {
|
|
12
134
|
return (hostname === "localhost" ||
|
|
13
135
|
hostname === "127.0.0.1" ||
|
|
14
136
|
hostname === "[::1]" ||
|
|
15
137
|
hostname === "::1");
|
|
16
138
|
}
|
|
139
|
+
export const MAX_REMOTE_REDIRECT_HOPS = 5;
|
|
140
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
141
|
+
const BODY_HEADERS = [
|
|
142
|
+
"content-encoding",
|
|
143
|
+
"content-language",
|
|
144
|
+
"content-length",
|
|
145
|
+
"content-location",
|
|
146
|
+
"content-type",
|
|
147
|
+
"transfer-encoding",
|
|
148
|
+
];
|
|
149
|
+
export class RemoteMcpRedirectError extends ConnectorCallError {
|
|
150
|
+
constructor(connectorId, reason) {
|
|
151
|
+
super("connector_call_failed", `Connector "${connectorId}" redirect policy rejected the downstream response: ${reason}.`);
|
|
152
|
+
this.name = "RemoteMcpRedirectError";
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function redirectedInit(init, status) {
|
|
156
|
+
const method = (init.method ?? "GET").toUpperCase();
|
|
157
|
+
const becomesGet = (status === 303 && method !== "GET" && method !== "HEAD") ||
|
|
158
|
+
((status === 301 || status === 302) && method === "POST");
|
|
159
|
+
if (!becomesGet)
|
|
160
|
+
return init;
|
|
161
|
+
const headers = new Headers(init.headers);
|
|
162
|
+
for (const name of BODY_HEADERS)
|
|
163
|
+
headers.delete(name);
|
|
164
|
+
return { ...init, method: "GET", body: undefined, headers };
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Wrap fetch with explicit, bounded redirect handling.
|
|
168
|
+
*
|
|
169
|
+
* The starting URL of each fetch call is trusted by its caller (the configured
|
|
170
|
+
* MCP endpoint, or an OAuth URL discovered by the pinned SDK). Only Location
|
|
171
|
+
* values are policy-controlled here. No rejected target is ever fetched, so
|
|
172
|
+
* arbitrary static header names receive the same protection as Authorization.
|
|
173
|
+
*/
|
|
174
|
+
export function redirectSafeFetch(connectorId, policy = "none", baseFetch = fetch) {
|
|
175
|
+
return async (input, initialInit = {}) => {
|
|
176
|
+
let current = new URL(input);
|
|
177
|
+
let init = initialInit;
|
|
178
|
+
const seen = new Set([current.href]);
|
|
179
|
+
let hops = 0;
|
|
180
|
+
while (true) {
|
|
181
|
+
const response = await baseFetch(current, {
|
|
182
|
+
...init,
|
|
183
|
+
redirect: "manual",
|
|
184
|
+
});
|
|
185
|
+
if (!REDIRECT_STATUSES.has(response.status))
|
|
186
|
+
return response;
|
|
187
|
+
const location = response.headers.get("location");
|
|
188
|
+
await response.body?.cancel().catch(() => { });
|
|
189
|
+
if (!location) {
|
|
190
|
+
throw new RemoteMcpRedirectError(connectorId, `HTTP ${response.status} carried no Location header`);
|
|
191
|
+
}
|
|
192
|
+
if (policy === "none") {
|
|
193
|
+
throw new RemoteMcpRedirectError(connectorId, `HTTP ${response.status} redirects are disabled`);
|
|
194
|
+
}
|
|
195
|
+
if (hops >= MAX_REMOTE_REDIRECT_HOPS) {
|
|
196
|
+
throw new RemoteMcpRedirectError(connectorId, `the redirect chain exceeded ${MAX_REMOTE_REDIRECT_HOPS} hops`);
|
|
197
|
+
}
|
|
198
|
+
let next;
|
|
199
|
+
try {
|
|
200
|
+
next = new URL(location, current);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
throw new RemoteMcpRedirectError(connectorId, `HTTP ${response.status} carried an invalid Location header`);
|
|
204
|
+
}
|
|
205
|
+
if (current.protocol === "https:" && next.protocol !== "https:") {
|
|
206
|
+
throw new RemoteMcpRedirectError(connectorId, "an HTTPS-to-HTTP downgrade is not allowed");
|
|
207
|
+
}
|
|
208
|
+
if (next.origin !== current.origin) {
|
|
209
|
+
throw new RemoteMcpRedirectError(connectorId, "a cross-origin redirect is not allowed");
|
|
210
|
+
}
|
|
211
|
+
if (next.username || next.password) {
|
|
212
|
+
throw new RemoteMcpRedirectError(connectorId, "a redirect target containing URL credentials is not allowed");
|
|
213
|
+
}
|
|
214
|
+
if (seen.has(next.href)) {
|
|
215
|
+
throw new RemoteMcpRedirectError(connectorId, "the redirect chain loops");
|
|
216
|
+
}
|
|
217
|
+
seen.add(next.href);
|
|
218
|
+
hops++;
|
|
219
|
+
init = redirectedInit(init, response.status);
|
|
220
|
+
current = next;
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
17
224
|
/**
|
|
18
225
|
* Proxy a downstream remote MCP server. SDK clients and transports are scoped
|
|
19
226
|
* to one inbound request: reused by calls within a batch/execute_code run, but
|
|
@@ -47,6 +254,25 @@ export function remoteMcp(id, opts) {
|
|
|
47
254
|
}
|
|
48
255
|
/** Typed per-call auth signal; the SDK's UnauthorizedError stays as cause. */
|
|
49
256
|
const authRequiredError = (cause) => new ConnectorCallError("auth_required", `Connector "${id}" requires authorization — call authorize_connector({ connector: "${id}" }) and open the returned URL.`, { cause });
|
|
257
|
+
const scopeEndedError = () => new Error(`Connector "${id}" scope ended during connection.`);
|
|
258
|
+
/**
|
|
259
|
+
* One `tools/list` request. The only thing wrapped here is the diagnosis of a
|
|
260
|
+
* `nextCursor` the MCP result schema refuses — overwhelmingly `null`, which
|
|
261
|
+
* plenty of servers use to mean "no more pages" but the spec spells as an
|
|
262
|
+
* *absent* cursor. The SDK surfaces that as a raw validation dump about a
|
|
263
|
+
* field the operator never sees; say which server broke which rule instead.
|
|
264
|
+
* Accepting `null` as end-of-chain outright is issue #99.
|
|
265
|
+
*/
|
|
266
|
+
const listPage = async (client, cursor) => {
|
|
267
|
+
try {
|
|
268
|
+
return await client.listTools(cursor === undefined ? undefined : { cursor });
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
if (!isCursorShapeError(err))
|
|
272
|
+
throw err;
|
|
273
|
+
throw new Error(`Connector "${id}" returned a tools/list page whose nextCursor is neither a string nor absent (a null cursor is the usual culprit) — MCP ends pagination on an absent nextCursor, so this catalog cannot be walked.`, { cause: err });
|
|
274
|
+
}
|
|
275
|
+
};
|
|
50
276
|
const stateFor = (ctx) => {
|
|
51
277
|
const scope = ctx.requestScope ?? ctx;
|
|
52
278
|
let state = states.get(scope);
|
|
@@ -58,6 +284,7 @@ export function remoteMcp(id, opts) {
|
|
|
58
284
|
authRequired: false,
|
|
59
285
|
provider: null,
|
|
60
286
|
connectedGeneration: null,
|
|
287
|
+
closed: false,
|
|
61
288
|
};
|
|
62
289
|
states.set(scope, state);
|
|
63
290
|
}
|
|
@@ -67,25 +294,22 @@ export function remoteMcp(id, opts) {
|
|
|
67
294
|
state.provider ??= new KvOAuthProvider(id, ctx.storage, `${ctx.baseUrl}/oauth/callback/${id}`);
|
|
68
295
|
return state.provider;
|
|
69
296
|
};
|
|
70
|
-
// NOTE: StreamableHTTPClientTransport speaks over fetch, which transparently
|
|
71
|
-
// follows 3xx redirects. A malicious or compromised downstream MCP could
|
|
72
|
-
// redirect to an internal address (e.g. http://169.254.169.254/…) and fetch
|
|
73
|
-
// would re-issue the request — potentially carrying static auth headers. The
|
|
74
|
-
// scheme check above only guards the first hop; a fully robust guard (manual
|
|
75
|
-
// redirect handling + per-hop re-validation + stripping auth headers cross-
|
|
76
|
-
// origin) lives in the SDK transport and is deferred to a future non-patch
|
|
77
|
-
// release rather than reimplemented here.
|
|
78
297
|
const buildTransport = (ctx, state) => {
|
|
79
298
|
if (opts._transportFactory)
|
|
80
299
|
return opts._transportFactory(ctx);
|
|
81
300
|
const url = new URL(opts.url);
|
|
301
|
+
const guardedFetch = redirectSafeFetch(id, opts.redirects);
|
|
82
302
|
if (opts.auth?.type === "oauth") {
|
|
83
303
|
return new StreamableHTTPClientTransport(url, {
|
|
84
304
|
authProvider: getProvider(ctx, state),
|
|
305
|
+
fetch: guardedFetch,
|
|
85
306
|
});
|
|
86
307
|
}
|
|
87
308
|
const headers = opts.auth?.type === "headers" ? opts.auth.headers : undefined;
|
|
88
|
-
return new StreamableHTTPClientTransport(url,
|
|
309
|
+
return new StreamableHTTPClientTransport(url, {
|
|
310
|
+
...(headers ? { requestInit: { headers } } : {}),
|
|
311
|
+
fetch: guardedFetch,
|
|
312
|
+
});
|
|
89
313
|
};
|
|
90
314
|
const reset = (state) => {
|
|
91
315
|
state.client = null;
|
|
@@ -93,22 +317,29 @@ export function remoteMcp(id, opts) {
|
|
|
93
317
|
state.connecting = null;
|
|
94
318
|
state.authRequired = false;
|
|
95
319
|
state.connectedGeneration = null;
|
|
320
|
+
// `closed` is deliberately not cleared — see ConnectionState.
|
|
96
321
|
};
|
|
97
322
|
const ensureConnected = async (ctx, state) => {
|
|
98
323
|
// Cross-isolate force re-auth: another isolate bumped the KV generation and
|
|
99
324
|
// wiped credentials. This request's cached client still speaks the old
|
|
100
325
|
// token — drop it so the next connect runs against current state.
|
|
101
326
|
if (state.client && isOauth && state.connectedGeneration !== null) {
|
|
102
|
-
|
|
103
|
-
|
|
327
|
+
const generation = await getProvider(ctx, state).generation();
|
|
328
|
+
if (state.closed)
|
|
329
|
+
throw scopeEndedError();
|
|
330
|
+
if (generation !== state.connectedGeneration) {
|
|
104
331
|
reset(state);
|
|
105
332
|
}
|
|
106
333
|
}
|
|
334
|
+
if (state.closed)
|
|
335
|
+
throw scopeEndedError();
|
|
107
336
|
if (state.client)
|
|
108
337
|
return;
|
|
109
338
|
state.connecting ??= (async () => {
|
|
110
339
|
const provider = isOauth ? getProvider(ctx, state) : null;
|
|
111
340
|
const genAtStart = provider ? await provider.generation() : 0;
|
|
341
|
+
if (state.closed)
|
|
342
|
+
throw scopeEndedError();
|
|
112
343
|
// Stamp the provider so any saveTokens/saveClientInformation the SDK fires
|
|
113
344
|
// during this connect (code exchange, DCR) — or during a later refresh on
|
|
114
345
|
// the resulting client — is dropped if a concurrent force bumps the
|
|
@@ -123,19 +354,47 @@ export function remoteMcp(id, opts) {
|
|
|
123
354
|
state.transport = t;
|
|
124
355
|
try {
|
|
125
356
|
await c.connect(t);
|
|
357
|
+
// A probe deadline can end its scope while connect is still in flight.
|
|
358
|
+
// The transport is closed immediately by closeScope; if connect wins
|
|
359
|
+
// that race anyway, close the resulting client rather than resurrecting
|
|
360
|
+
// a session in the detached state object.
|
|
361
|
+
if (state.closed) {
|
|
362
|
+
try {
|
|
363
|
+
await c.close();
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
// The scope has already been discarded either way.
|
|
367
|
+
}
|
|
368
|
+
throw scopeEndedError();
|
|
369
|
+
}
|
|
126
370
|
// A force re-auth that landed WHILE we were connecting wiped the creds
|
|
127
371
|
// this client just bound to. Discard it rather than cache a connection
|
|
128
372
|
// that resurrects the wiped-and-reauthorized connector from a stale
|
|
129
373
|
// isolate. Surfaces as auth_required — the connector genuinely needs
|
|
130
374
|
// re-consent now.
|
|
131
|
-
if (provider
|
|
132
|
-
|
|
133
|
-
|
|
375
|
+
if (provider) {
|
|
376
|
+
const generation = await provider.generation();
|
|
377
|
+
// closeScope can land while the generation read is pending, after
|
|
378
|
+
// connect succeeded but before this client is cached. Discard the
|
|
379
|
+
// client on that side of the await too.
|
|
380
|
+
if (state.closed) {
|
|
381
|
+
try {
|
|
382
|
+
await c.close();
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
// The scope has already been discarded either way.
|
|
386
|
+
}
|
|
387
|
+
throw scopeEndedError();
|
|
134
388
|
}
|
|
135
|
-
|
|
136
|
-
|
|
389
|
+
if (generation !== genAtStart) {
|
|
390
|
+
try {
|
|
391
|
+
await c.close();
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
// discarding either way
|
|
395
|
+
}
|
|
396
|
+
throw new UnauthorizedError("Connector was re-authorized during connect; reconnect required.");
|
|
137
397
|
}
|
|
138
|
-
throw new UnauthorizedError("Connector was re-authorized during connect; reconnect required.");
|
|
139
398
|
}
|
|
140
399
|
state.client = c;
|
|
141
400
|
state.connectedGeneration = genAtStart;
|
|
@@ -164,11 +423,102 @@ export function remoteMcp(id, opts) {
|
|
|
164
423
|
description: opts.description,
|
|
165
424
|
maxResultBytes: opts.maxResultBytes,
|
|
166
425
|
usageGuide: opts.usageGuide,
|
|
426
|
+
// `tools/list` is cursor-paginated: the server chooses the page size and
|
|
427
|
+
// signals "there is more" with a `nextCursor`, which the SDK's
|
|
428
|
+
// Client.listTools() returns without following. Collect the whole chain
|
|
429
|
+
// here, because a half-collected catalog is indistinguishable from a small
|
|
430
|
+
// one — later-page tools would simply appear not to exist, unsearchable and
|
|
431
|
+
// unaddressable, with nothing anywhere saying why.
|
|
432
|
+
//
|
|
433
|
+
// All pages ride the one request-scoped client already connected above, and
|
|
434
|
+
// the accumulator is returned rather than stored: a cursor is opaque and
|
|
435
|
+
// session-bound, so nothing here may outlive this call.
|
|
167
436
|
async listTools(ctx) {
|
|
168
437
|
const state = stateFor(ctx);
|
|
169
438
|
await ensureConnected(ctx, state);
|
|
170
|
-
|
|
171
|
-
|
|
439
|
+
// Bind the client once so the whole walk provably rides one session — a
|
|
440
|
+
// cursor is only meaningful to the connection that issued it, and a
|
|
441
|
+
// re-read could in principle pick up a different one. It is NOT guarding
|
|
442
|
+
// against closeScope nulling state.client mid-loop: closeScope sets
|
|
443
|
+
// `closed` and nulls `client` in one synchronous run, and the loop
|
|
444
|
+
// re-checks `closed` before every page, so the nulled client is
|
|
445
|
+
// unreachable from here.
|
|
446
|
+
const client = state.client;
|
|
447
|
+
// Raw SDK tools, not ToolDefs: the metadata re-prime below needs fields
|
|
448
|
+
// (task support) that a ToolDef deliberately does not carry.
|
|
449
|
+
const listed = [];
|
|
450
|
+
const names = new Set();
|
|
451
|
+
const spent = new Set();
|
|
452
|
+
let cursor;
|
|
453
|
+
/** Consecutive pages that advertised a successor but added nothing. */
|
|
454
|
+
let barren = 0;
|
|
455
|
+
let complete = false;
|
|
456
|
+
for (let page = 0; page < MAX_TOOL_PAGES; page++) {
|
|
457
|
+
// The scope can end between pages (probe timeout, teardown). Stop
|
|
458
|
+
// rather than keep paging into a transport that is being closed.
|
|
459
|
+
if (state.closed)
|
|
460
|
+
throw scopeEndedError();
|
|
461
|
+
// Page one sends no params at all, so a non-paginated server sees
|
|
462
|
+
// exactly the request it saw before pagination existed.
|
|
463
|
+
const res = await listPage(client, cursor);
|
|
464
|
+
let added = 0;
|
|
465
|
+
for (const t of res.tools) {
|
|
466
|
+
// First page wins. An unstable cursor can serve the same tool on two
|
|
467
|
+
// pages — a failure mode that did not exist while only page one was
|
|
468
|
+
// read — and a duplicate would inflate `toolCount`, double the tool's
|
|
469
|
+
// `search_tools` row, and churn the registry's catalog-changed
|
|
470
|
+
// comparison into a persistence write on every refresh.
|
|
471
|
+
if (names.has(t.name))
|
|
472
|
+
continue;
|
|
473
|
+
names.add(t.name);
|
|
474
|
+
listed.push(t);
|
|
475
|
+
added++;
|
|
476
|
+
}
|
|
477
|
+
// Pagination ends when `nextCursor` is ABSENT — not when it is falsy.
|
|
478
|
+
// An empty string is a legal cursor and means "keep going"; `if
|
|
479
|
+
// (!next)` here would silently truncate that server's catalog.
|
|
480
|
+
const next = res.nextCursor;
|
|
481
|
+
if (typeof next !== "string") {
|
|
482
|
+
complete = true;
|
|
483
|
+
break;
|
|
484
|
+
}
|
|
485
|
+
// A page that adds nothing and still claims a successor made no
|
|
486
|
+
// progress. Allow exactly one: the widespread idiom is to advertise a
|
|
487
|
+
// cursor whenever a page came back full and then serve one empty page
|
|
488
|
+
// to terminate, and that server is conformant. Two in a row is a
|
|
489
|
+
// downstream going nowhere, and this kills a "fresh cursor forever, no
|
|
490
|
+
// tools" adversary in a couple of round trips instead of thousands.
|
|
491
|
+
if (added === 0 && ++barren > 1) {
|
|
492
|
+
throw new Error(`Connector "${id}" returned two consecutive tools/list pages that added no tools and still advertised another — the catalog is not advancing.`);
|
|
493
|
+
}
|
|
494
|
+
if (added > 0)
|
|
495
|
+
barren = 0;
|
|
496
|
+
// A cursor handed back a second time is not a slow server, it is a
|
|
497
|
+
// loop. Fail now rather than walking it until a ceiling notices.
|
|
498
|
+
if (spent.has(next)) {
|
|
499
|
+
throw new Error(`Connector "${id}" handed back a tools/list cursor it had already issued — the pagination chain loops.`);
|
|
500
|
+
}
|
|
501
|
+
// Checked here rather than on arrival: this bounds what a *walk* may
|
|
502
|
+
// accumulate, and a server that answers in one page was always free to
|
|
503
|
+
// send whatever it sends.
|
|
504
|
+
if (listed.length > MAX_TOOLS) {
|
|
505
|
+
throw new Error(`Connector "${id}" advertised further tools/list pages past ${listed.length} tools, over the ${MAX_TOOLS}-tool ceiling one catalog refresh will collect.`);
|
|
506
|
+
}
|
|
507
|
+
// Opaque by contract: handed straight back, never parsed, rewritten,
|
|
508
|
+
// or persisted.
|
|
509
|
+
spent.add(next);
|
|
510
|
+
cursor = next;
|
|
511
|
+
}
|
|
512
|
+
// Fail the refresh outright. Returning what we have would publish a
|
|
513
|
+
// partial catalog that looks complete; throwing lets the registry keep
|
|
514
|
+
// serving the last complete one via its stale fallback.
|
|
515
|
+
if (!complete) {
|
|
516
|
+
throw new Error(`Connector "${id}" kept advertising more tools/list pages after ${MAX_TOOL_PAGES} — refusing to page further.`);
|
|
517
|
+
}
|
|
518
|
+
// Repair what the per-page listTools calls left behind before any of
|
|
519
|
+
// these tools can be called. See primeToolMetadata.
|
|
520
|
+
primeToolMetadata(client, listed);
|
|
521
|
+
return listed.map((t) => ({
|
|
172
522
|
name: t.name,
|
|
173
523
|
description: t.description,
|
|
174
524
|
inputSchema: t.inputSchema,
|
|
@@ -199,6 +549,37 @@ export function remoteMcp(id, opts) {
|
|
|
199
549
|
throw err;
|
|
200
550
|
}
|
|
201
551
|
},
|
|
552
|
+
async closeScope(ctx) {
|
|
553
|
+
const scope = ctx.requestScope ?? ctx;
|
|
554
|
+
const state = states.get(scope);
|
|
555
|
+
if (!state)
|
|
556
|
+
return;
|
|
557
|
+
// Delete before awaiting: a duplicate teardown is a no-op, and no later
|
|
558
|
+
// lookup can reuse the state while its client is closing.
|
|
559
|
+
states.delete(scope);
|
|
560
|
+
state.closed = true;
|
|
561
|
+
const client = state.client;
|
|
562
|
+
const transport = state.transport;
|
|
563
|
+
state.client = null;
|
|
564
|
+
state.transport = null;
|
|
565
|
+
state.connecting = null;
|
|
566
|
+
state.authRequired = false;
|
|
567
|
+
state.connectedGeneration = null;
|
|
568
|
+
// Ask the downstream to drop its session first — closing only aborts our
|
|
569
|
+
// side, and the DELETE that frees the server's rides on the very
|
|
570
|
+
// AbortSignal the close is about to trip.
|
|
571
|
+
if (transport)
|
|
572
|
+
await terminateSession(transport);
|
|
573
|
+
// Client.close() owns its connected transport. During an unfinished or
|
|
574
|
+
// failed connect there is no cached client yet, so close the transport
|
|
575
|
+
// directly to abort/release that half-open session.
|
|
576
|
+
if (client) {
|
|
577
|
+
await client.close();
|
|
578
|
+
}
|
|
579
|
+
else {
|
|
580
|
+
await transport?.close();
|
|
581
|
+
}
|
|
582
|
+
},
|
|
202
583
|
async status(ctx) {
|
|
203
584
|
const state = stateFor(ctx);
|
|
204
585
|
try {
|