@mcp-z/client 1.0.7 → 1.0.8
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/dist/cjs/auth/capability-discovery.js +2 -5
- package/dist/cjs/auth/capability-discovery.js.map +1 -1
- package/dist/cjs/auth/index.js.map +1 -1
- package/dist/cjs/auth/interactive-oauth-flow.js +13 -30
- package/dist/cjs/auth/interactive-oauth-flow.js.map +1 -1
- package/dist/cjs/auth/oauth-callback-listener.js +3 -8
- package/dist/cjs/auth/oauth-callback-listener.js.map +1 -1
- package/dist/cjs/auth/pkce.js +2 -5
- package/dist/cjs/auth/pkce.js.map +1 -1
- package/dist/cjs/auth/rfc9728-discovery.js +2 -5
- package/dist/cjs/auth/rfc9728-discovery.js.map +1 -1
- package/dist/cjs/auth/types.js.map +1 -1
- package/dist/cjs/client-helpers.js +4 -6
- package/dist/cjs/client-helpers.js.map +1 -1
- package/dist/cjs/config/server-loader.js +8 -19
- package/dist/cjs/config/server-loader.js.map +1 -1
- package/dist/cjs/config/validate-config.js +8 -19
- package/dist/cjs/config/validate-config.js.map +1 -1
- package/dist/cjs/connection/connect-client.js +5 -11
- package/dist/cjs/connection/connect-client.js.map +1 -1
- package/dist/cjs/connection/existing-process-transport.js +3 -8
- package/dist/cjs/connection/existing-process-transport.js.map +1 -1
- package/dist/cjs/connection/types.d.cts +1 -1
- package/dist/cjs/connection/types.d.ts +1 -1
- package/dist/cjs/connection/types.js.map +1 -1
- package/dist/cjs/connection/wait-for-http-ready.js +2 -5
- package/dist/cjs/connection/wait-for-http-ready.js.map +1 -1
- package/dist/cjs/constants.js.map +1 -1
- package/dist/cjs/dcr/dcr-authenticator.js +13 -30
- package/dist/cjs/dcr/dcr-authenticator.js.map +1 -1
- package/dist/cjs/dcr/dynamic-client-registrar.js +3 -8
- package/dist/cjs/dcr/dynamic-client-registrar.js.map +1 -1
- package/dist/cjs/dcr/index.js.map +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/lib/url-utils.js.map +1 -1
- package/dist/cjs/monkey-patches.js +11 -14
- package/dist/cjs/monkey-patches.js.map +1 -1
- package/dist/cjs/response-wrappers.js +24 -31
- package/dist/cjs/response-wrappers.js.map +1 -1
- package/dist/cjs/search/index.js.map +1 -1
- package/dist/cjs/search/search.js +15 -18
- package/dist/cjs/search/search.js.map +1 -1
- package/dist/cjs/search/types.js.map +1 -1
- package/dist/cjs/spawn/spawn-server.js +22 -38
- package/dist/cjs/spawn/spawn-server.js.map +1 -1
- package/dist/cjs/spawn/spawn-servers.js +29 -47
- package/dist/cjs/spawn/spawn-servers.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/utils/logger.js +1 -1
- package/dist/cjs/utils/logger.js.map +1 -1
- package/dist/cjs/utils/path-utils.js +9 -20
- package/dist/cjs/utils/path-utils.js.map +1 -1
- package/dist/cjs/utils/sanitizer.js +4 -7
- package/dist/cjs/utils/sanitizer.js.map +1 -1
- package/dist/esm/auth/capability-discovery.js.map +1 -1
- package/dist/esm/auth/index.js.map +1 -1
- package/dist/esm/auth/interactive-oauth-flow.js.map +1 -1
- package/dist/esm/auth/oauth-callback-listener.js.map +1 -1
- package/dist/esm/auth/pkce.js.map +1 -1
- package/dist/esm/auth/rfc9728-discovery.js.map +1 -1
- package/dist/esm/auth/types.js.map +1 -1
- package/dist/esm/client-helpers.js.map +1 -1
- package/dist/esm/config/server-loader.js.map +1 -1
- package/dist/esm/config/validate-config.js.map +1 -1
- package/dist/esm/connection/connect-client.js.map +1 -1
- package/dist/esm/connection/existing-process-transport.js.map +1 -1
- package/dist/esm/connection/types.d.ts +1 -1
- package/dist/esm/connection/types.js.map +1 -1
- package/dist/esm/connection/wait-for-http-ready.js.map +1 -1
- package/dist/esm/constants.js.map +1 -1
- package/dist/esm/dcr/dcr-authenticator.js.map +1 -1
- package/dist/esm/dcr/dynamic-client-registrar.js.map +1 -1
- package/dist/esm/dcr/index.js.map +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/lib/url-utils.js.map +1 -1
- package/dist/esm/monkey-patches.js.map +1 -1
- package/dist/esm/response-wrappers.js +6 -3
- package/dist/esm/response-wrappers.js.map +1 -1
- package/dist/esm/search/index.js.map +1 -1
- package/dist/esm/search/search.js.map +1 -1
- package/dist/esm/search/types.js.map +1 -1
- package/dist/esm/spawn/spawn-server.js.map +1 -1
- package/dist/esm/spawn/spawn-servers.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/utils/logger.js.map +1 -1
- package/dist/esm/utils/path-utils.js.map +1 -1
- package/dist/esm/utils/sanitizer.js.map +1 -1
- package/package.json +9 -3
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/index.ts"],"sourcesContent":["/**\n * @mcp-z/client - MCP Client Library\n */\n\n// Config types (from schema)\nexport type { McpServerEntry, StartConfig } from '../schemas/servers.d.ts';\n// Auth - OAuth utilities\nexport { probeAuthCapabilities } from './auth/capability-discovery.ts';\nexport type { AuthCapabilities, CallbackResult, OAuthCallbackListenerOptions, OAuthFlowOptions, TokenSet } from './auth/index.ts';\nexport { InteractiveOAuthFlow } from './auth/interactive-oauth-flow.ts';\nexport { OAuthCallbackListener } from './auth/oauth-callback-listener.ts';\n// Client helpers and lightweight overloads\nexport { decorateClient, type ManagedClient, type PromptArguments, type WrappedCallToolReturn, type WrappedGetPromptReturn, type WrappedReadResourceReturn } from './client-helpers.ts';\n// Config - Configuration validation\nexport { type ValidationResult, validateServers } from './config/validate-config.ts';\n// Connection - MCP client connection utilities (internal helpers exposed for advanced use)\nexport type { JsonValue, PromptArgument, ToolArguments } from './connection/types.ts';\n// DCR - Dynamic Client Registration utilities\nexport { DcrAuthenticator } from './dcr/dcr-authenticator.ts';\nexport { DynamicClientRegistrar } from './dcr/dynamic-client-registrar.ts';\nexport type { ClientCredentials, DcrAuthenticatorOptions, DcrRegistrationOptions } from './dcr/index.ts';\nexport {\n type JsonValidator,\n type NativeCallToolResponse,\n type NativeGetPromptResponse,\n type NativeReadResourceResponse,\n PromptResponseError,\n PromptResponseWrapper,\n ResourceResponseError,\n ResourceResponseWrapper,\n ToolResponseError,\n ToolResponseWrapper,\n} from './response-wrappers.ts';\nexport type { CapabilityClient, CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './search/index.ts';\n// Search - Capability discovery\nexport { buildCapabilityIndex, search, searchCapabilities } from './search/index.ts';\n// Spawn - Server registry (v3 API)\nexport { type CloseResult, type CreateServerRegistryOptions, createServerRegistry, type Dialect, type ServerRegistry, type ServersConfig } from './spawn/spawn-servers.ts';\nexport type { TransportType } from './types.ts';\n// Utils - Shared utilities\nexport { getLogLevel, type Logger, type LogLevel, logger, setLogLevel } from './utils/logger.ts';\nexport { resolveArgsPaths, resolvePath } from './utils/path-utils.ts';\n"],"names":["DcrAuthenticator","DynamicClientRegistrar","InteractiveOAuthFlow","OAuthCallbackListener","PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","buildCapabilityIndex","createServerRegistry","decorateClient","getLogLevel","logger","probeAuthCapabilities","resolveArgsPaths","resolvePath","search","searchCapabilities","setLogLevel","validateServers"],"mappings":"AAAA;;CAEC,GAED,6BAA6B;;;;;;;;;;;;QAcpBA;eAAAA,oCAAgB;;QAChBC;eAAAA,gDAAsB;;QAVtBC;eAAAA,4CAAoB;;QACpBC;eAAAA,8CAAqB;;QAgB5BC;eAAAA,uCAAmB;;QACnBC;eAAAA,yCAAqB;;QACrBC;eAAAA,yCAAqB;;QACrBC;eAAAA,2CAAuB;;QACvBC;eAAAA,qCAAiB;;QACjBC;eAAAA,uCAAmB;;QAIZC;eAAAA,6BAAoB;;QAEgCC;eAAAA,oCAAoB;;QAzBxEC;eAAAA,+BAAc;;QA4BdC;eAAAA,qBAAW;;QAA8BC;eAAAA,gBAAM;;QAjC/CC;eAAAA,4CAAqB;;QAkCrBC;eAAAA,6BAAgB;;QAAEC;eAAAA,wBAAW;;QANPC;eAAAA,eAAM;;QAAEC;eAAAA,2BAAkB;;QAKCC;eAAAA,qBAAW;;QA1BrCC;eAAAA,iCAAe;;;qCAPT;sCAED;uCACC;+BAE4H;gCAE3G;kCAItB;wCACM;kCAahC;uBAG0D;8BAE+E;wBAGnE;2BAC/B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/lib/url-utils.ts"],"sourcesContent":["export function normalizeUrl(input: string): string {\n try {\n const url = new URL(input);\n url.search = '';\n url.hash = '';\n url.pathname = url.pathname.replace(/\\/+$/, '');\n return url.origin + url.pathname;\n } catch {\n return input.replace(/\\/+$/, '');\n }\n}\n\nexport function joinWellKnown(baseUrl: string, suffix: string): string {\n return `${normalizeUrl(baseUrl)}${suffix}`;\n}\n"],"names":["joinWellKnown","normalizeUrl","input","url","URL","search","hash","pathname","replace","origin","baseUrl","suffix"],"mappings":";;;;;;;;;;;QAYgBA;eAAAA;;QAZAC;eAAAA;;;AAAT,SAASA,aAAaC,KAAa;IACxC,IAAI;QACF,IAAMC,MAAM,IAAIC,IAAIF;QACpBC,IAAIE,MAAM,GAAG;QACbF,IAAIG,IAAI,GAAG;QACXH,IAAII,QAAQ,GAAGJ,IAAII,QAAQ,CAACC,OAAO,CAAC,QAAQ;QAC5C,OAAOL,IAAIM,MAAM,GAAGN,IAAII,QAAQ;IAClC,EAAE,eAAM;QACN,OAAOL,MAAMM,OAAO,CAAC,QAAQ;IAC/B;AACF;AAEO,SAASR,cAAcU,OAAe,EAAEC,MAAc;IAC3D,OAAO,AAAC,GAA0BA,OAAxBV,aAAaS,UAAkB,OAAPC;AACpC"}
|
|
@@ -23,11 +23,8 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
|
23
23
|
reject(error);
|
|
24
24
|
return;
|
|
25
25
|
}
|
|
26
|
-
if (info.done)
|
|
27
|
-
|
|
28
|
-
} else {
|
|
29
|
-
Promise.resolve(value).then(_next, _throw);
|
|
30
|
-
}
|
|
26
|
+
if (info.done) resolve(value);
|
|
27
|
+
else Promise.resolve(value).then(_next, _throw);
|
|
31
28
|
}
|
|
32
29
|
function _async_to_generator(fn) {
|
|
33
30
|
return function() {
|
|
@@ -69,19 +66,11 @@ function _iterable_to_array_limit(arr, i) {
|
|
|
69
66
|
return _arr;
|
|
70
67
|
}
|
|
71
68
|
function _non_iterable_rest() {
|
|
72
|
-
throw new TypeError("Invalid attempt to destructure non-iterable instance
|
|
69
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
73
70
|
}
|
|
74
71
|
function _sliced_to_array(arr, i) {
|
|
75
72
|
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
|
|
76
73
|
}
|
|
77
|
-
function _unsupported_iterable_to_array(o, minLen) {
|
|
78
|
-
if (!o) return;
|
|
79
|
-
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
80
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
81
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
82
|
-
if (n === "Map" || n === "Set") return Array.from(n);
|
|
83
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
84
|
-
}
|
|
85
74
|
function _ts_generator(thisArg, body) {
|
|
86
75
|
var f, y, t, _ = {
|
|
87
76
|
label: 0,
|
|
@@ -181,6 +170,14 @@ function _ts_generator(thisArg, body) {
|
|
|
181
170
|
};
|
|
182
171
|
}
|
|
183
172
|
}
|
|
173
|
+
function _unsupported_iterable_to_array(o, minLen) {
|
|
174
|
+
if (!o) return;
|
|
175
|
+
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
176
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
177
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
178
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
179
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
180
|
+
}
|
|
184
181
|
/**
|
|
185
182
|
* FIX: Protocol.close() doesn't clear pending timeouts
|
|
186
183
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/monkey-patches.ts"],"sourcesContent":["/**\n * Monkey patches for MCP SDK bugs\n *\n * These patches fix bugs in dependencies that haven't been fixed upstream yet.\n */\n\nimport { Protocol } from '@modelcontextprotocol/sdk/shared/protocol.js';\n\n/**\n * FIX: Protocol.close() doesn't clear pending timeouts\n *\n * BUG: The MCP SDK's Protocol.close() only closes the transport but does NOT\n * clear pending timeouts from the internal _timeoutInfo Map. This causes Node.js\n * to hang until timeouts fire (default 60 seconds).\n *\n * PATCH: Wrap Protocol.close() to clear all pending timeouts before closing.\n *\n * TO TEST IF STILL NEEDED:\n * 1. Comment out this patch\n * 2. Run: npm run test:unit\n * 3. If tests hang ~60 seconds after completing, bug still exists\n * 4. If tests exit promptly, SDK is fixed and this can be removed\n *\n * UPSTREAM: https://github.com/modelcontextprotocol/typescript-sdk/issues/XXX\n */\nconst originalClose = Protocol.prototype.close;\nProtocol.prototype.close = async function () {\n const self = this as unknown as { _timeoutInfo?: Map<unknown, { timeoutId: ReturnType<typeof setTimeout> }> };\n if (self._timeoutInfo) {\n for (const [, info] of self._timeoutInfo) {\n clearTimeout(info.timeoutId);\n }\n self._timeoutInfo.clear();\n }\n return originalClose.call(this);\n};\n"],"names":["originalClose","Protocol","prototype","close","self","info","_timeoutInfo","clearTimeout","timeoutId","clear","call"],"mappings":"AAAA;;;;CAIC;;;;wBAEwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEzB;;;;;;;;;;;;;;;;CAgBC,GACD,IAAMA,gBAAgBC,kBAAQ,CAACC,SAAS,CAACC,KAAK;AAC9CF,kBAAQ,CAACC,SAAS,CAACC,KAAK,GAAG;;YACnBC,MAEC,2BAAA,mBAAA,gBAAA,WAAA,oBAASC;;YAFVD,OAAO,IAAI;YACjB,IAAIA,KAAKE,YAAY,EAAE;gBAChB,kCAAA,2BAAA;;oBAAL,IAAK,YAAkBF,KAAKE,YAAY,uBAAnC,6BAAA,QAAA,yBAAA,iCAAqC;uDAArC,iBAASD;wBACZE,aAAaF,KAAKG,SAAS;oBAC7B;;oBAFK;oBAAA;;;6BAAA,6BAAA;4BAAA;;;4BAAA;kCAAA;;;;gBAGLJ,KAAKE,YAAY,CAACG,KAAK;YACzB;YACA;;gBAAOT,cAAcU,IAAI,CAAC,IAAI;;;IAChC"}
|
|
@@ -38,9 +38,7 @@ function _array_with_holes(arr) {
|
|
|
38
38
|
if (Array.isArray(arr)) return arr;
|
|
39
39
|
}
|
|
40
40
|
function _assert_this_initialized(self) {
|
|
41
|
-
if (self === void 0)
|
|
42
|
-
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
|
43
|
-
}
|
|
41
|
+
if (self === void 0) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
|
44
42
|
return self;
|
|
45
43
|
}
|
|
46
44
|
function _call_super(_this, derived, args) {
|
|
@@ -48,14 +46,11 @@ function _call_super(_this, derived, args) {
|
|
|
48
46
|
return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
|
|
49
47
|
}
|
|
50
48
|
function _class_call_check(instance, Constructor) {
|
|
51
|
-
if (!(instance instanceof Constructor))
|
|
52
|
-
throw new TypeError("Cannot call a class as a function");
|
|
53
|
-
}
|
|
49
|
+
if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function");
|
|
54
50
|
}
|
|
55
51
|
function _construct(Parent, args, Class) {
|
|
56
|
-
if (_is_native_reflect_construct())
|
|
57
|
-
|
|
58
|
-
} else {
|
|
52
|
+
if (_is_native_reflect_construct()) _construct = Reflect.construct;
|
|
53
|
+
else {
|
|
59
54
|
_construct = function construct(Parent, args, Class) {
|
|
60
55
|
var a = [
|
|
61
56
|
null
|
|
@@ -89,15 +84,22 @@ function _inherits(subClass, superClass) {
|
|
|
89
84
|
if (superClass) _set_prototype_of(subClass, superClass);
|
|
90
85
|
}
|
|
91
86
|
function _instanceof(left, right) {
|
|
87
|
+
"@swc/helpers - instanceof";
|
|
92
88
|
if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
|
|
93
89
|
return !!right[Symbol.hasInstance](left);
|
|
94
|
-
} else
|
|
95
|
-
return left instanceof right;
|
|
96
|
-
}
|
|
90
|
+
} else return left instanceof right;
|
|
97
91
|
}
|
|
98
92
|
function _is_native_function(fn) {
|
|
99
93
|
return Function.toString.call(fn).indexOf("[native code]") !== -1;
|
|
100
94
|
}
|
|
95
|
+
function _is_native_reflect_construct() {
|
|
96
|
+
try {
|
|
97
|
+
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
|
|
98
|
+
} catch (_) {}
|
|
99
|
+
return (_is_native_reflect_construct = function() {
|
|
100
|
+
return !!result;
|
|
101
|
+
})();
|
|
102
|
+
}
|
|
101
103
|
function _iterable_to_array_limit(arr, i) {
|
|
102
104
|
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
|
|
103
105
|
if (_i == null) return;
|
|
@@ -123,12 +125,10 @@ function _iterable_to_array_limit(arr, i) {
|
|
|
123
125
|
return _arr;
|
|
124
126
|
}
|
|
125
127
|
function _non_iterable_rest() {
|
|
126
|
-
throw new TypeError("Invalid attempt to destructure non-iterable instance
|
|
128
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
127
129
|
}
|
|
128
130
|
function _possible_constructor_return(self, call) {
|
|
129
|
-
if (call && (_type_of(call) === "object" || typeof call === "function"))
|
|
130
|
-
return call;
|
|
131
|
-
}
|
|
131
|
+
if (call && (_type_of(call) === "object" || typeof call === "function")) return call;
|
|
132
132
|
return _assert_this_initialized(self);
|
|
133
133
|
}
|
|
134
134
|
function _set_prototype_of(o, p) {
|
|
@@ -155,11 +155,9 @@ function _unsupported_iterable_to_array(o, minLen) {
|
|
|
155
155
|
}
|
|
156
156
|
function _wrap_native_super(Class) {
|
|
157
157
|
var _cache = typeof Map === "function" ? new Map() : undefined;
|
|
158
|
-
_wrap_native_super = function
|
|
158
|
+
_wrap_native_super = function(Class) {
|
|
159
159
|
if (Class === null || !_is_native_function(Class)) return Class;
|
|
160
|
-
if (typeof Class !== "function")
|
|
161
|
-
throw new TypeError("Super expression must either be null or a function");
|
|
162
|
-
}
|
|
160
|
+
if (typeof Class !== "function") throw new TypeError("Super expression must either be null or a function");
|
|
163
161
|
if (typeof _cache !== "undefined") {
|
|
164
162
|
if (_cache.has(Class)) return _cache.get(Class);
|
|
165
163
|
_cache.set(Class, Wrapper);
|
|
@@ -179,14 +177,6 @@ function _wrap_native_super(Class) {
|
|
|
179
177
|
};
|
|
180
178
|
return _wrap_native_super(Class);
|
|
181
179
|
}
|
|
182
|
-
function _is_native_reflect_construct() {
|
|
183
|
-
try {
|
|
184
|
-
var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
|
|
185
|
-
} catch (_) {}
|
|
186
|
-
return (_is_native_reflect_construct = function() {
|
|
187
|
-
return !!result;
|
|
188
|
-
})();
|
|
189
|
-
}
|
|
190
180
|
var ToolResponseError = /*#__PURE__*/ function(Error1) {
|
|
191
181
|
"use strict";
|
|
192
182
|
_inherits(ToolResponseError, Error1);
|
|
@@ -215,7 +205,8 @@ var ToolResponseWrapper = /*#__PURE__*/ function() {
|
|
|
215
205
|
_proto.json = function json(validator) {
|
|
216
206
|
var value = this.resolveJsonPayload();
|
|
217
207
|
if (validator) {
|
|
218
|
-
validator
|
|
208
|
+
var assertValid = validator;
|
|
209
|
+
assertValid(value);
|
|
219
210
|
}
|
|
220
211
|
return value;
|
|
221
212
|
};
|
|
@@ -308,7 +299,8 @@ var PromptResponseWrapper = /*#__PURE__*/ function() {
|
|
|
308
299
|
try {
|
|
309
300
|
var parsed = JSON.parse(textValue);
|
|
310
301
|
if (validator) {
|
|
311
|
-
validator
|
|
302
|
+
var assertValid = validator;
|
|
303
|
+
assertValid(parsed);
|
|
312
304
|
}
|
|
313
305
|
return parsed;
|
|
314
306
|
} catch (error) {
|
|
@@ -363,7 +355,8 @@ var ResourceResponseWrapper = /*#__PURE__*/ function() {
|
|
|
363
355
|
try {
|
|
364
356
|
var parsed = JSON.parse(textValue);
|
|
365
357
|
if (validator) {
|
|
366
|
-
validator
|
|
358
|
+
var assertValid = validator;
|
|
359
|
+
assertValid(parsed);
|
|
367
360
|
}
|
|
368
361
|
return parsed;
|
|
369
362
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/client/src/response-wrappers.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { ContentBlock, PromptMessage, TextContent } from '@modelcontextprotocol/sdk/types.js';\n\nexport type NativeCallToolResponse = Awaited<ReturnType<Client['callTool']>>;\nexport type NativeGetPromptResponse = Awaited<ReturnType<Client['getPrompt']>>;\nexport type NativeReadResourceResponse = Awaited<ReturnType<Client['readResource']>>;\n\nexport type JsonValidator<T> = (value: unknown) => asserts value is T;\n\nexport class ToolResponseError extends Error {\n readonly response: NativeCallToolResponse;\n\n constructor(message: string, response: NativeCallToolResponse) {\n super(message);\n this.name = 'ToolResponseError';\n this.response = response;\n }\n}\n\nexport class ToolResponseWrapper {\n private readonly payload: NativeCallToolResponse;\n\n constructor(payload: NativeCallToolResponse) {\n this.payload = payload;\n }\n\n raw(): NativeCallToolResponse {\n return this.payload;\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const value = this.resolveJsonPayload();\n if (validator) {\n validator(value);\n }\n return value as T;\n }\n\n text(): string {\n if (isCompatibilityResult(this.payload)) {\n if (typeof this.payload.toolResult === 'string') {\n return this.payload.toolResult;\n }\n throw new ToolResponseError('Compatibility tool result is not text', this.payload);\n }\n\n this.throwIfError();\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include text content', this.payload);\n }\n\n return textBlock.text;\n }\n\n private resolveJsonPayload(): unknown {\n if (isCompatibilityResult(this.payload)) {\n return this.payload.toolResult;\n }\n\n this.throwIfError();\n\n if (hasStructuredContent(this.payload)) {\n return this.payload.structuredContent;\n }\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include structuredContent or text content', this.payload);\n }\n\n try {\n return JSON.parse(textBlock.text) as unknown;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ToolResponseError(`Failed to parse tool text content as JSON: ${reason}`, this.payload);\n }\n }\n\n private throwIfError(): void {\n if ('isError' in this.payload && this.payload.isError) {\n let detail = typeof this.payload.error === 'object' && this.payload.error && 'message' in this.payload.error ? String((this.payload.error as { message?: unknown }).message ?? '') : '';\n if (!detail) {\n const textBlock = findFirstTextBlock((this.payload.content ?? []) as ContentBlock[]);\n if (textBlock?.text) {\n detail = textBlock.text;\n }\n }\n const message = detail ? `Tool invocation returned an error result: ${detail}` : 'Tool invocation returned an error result';\n throw new ToolResponseError(message, this.payload);\n }\n }\n}\n\nexport class PromptResponseError extends Error {\n readonly response: NativeGetPromptResponse;\n\n constructor(message: string, response: NativeGetPromptResponse) {\n super(message);\n this.name = 'PromptResponseError';\n this.response = response;\n }\n}\n\nexport class PromptResponseWrapper {\n private readonly payload: NativeGetPromptResponse;\n\n constructor(payload: NativeGetPromptResponse) {\n this.payload = payload;\n }\n\n raw(): NativeGetPromptResponse {\n return this.payload;\n }\n\n text(): string {\n const segments = collectPromptText(this.payload.messages);\n if (!segments.length) {\n throw new PromptResponseError('Prompt response did not include text content', this.payload);\n }\n return segments.join('\\n\\n');\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n validator(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new PromptResponseError(`Failed to parse prompt text as JSON: ${reason}`, this.payload);\n }\n }\n}\n\nexport class ResourceResponseError extends Error {\n readonly response: NativeReadResourceResponse;\n\n constructor(message: string, response: NativeReadResourceResponse) {\n super(message);\n this.name = 'ResourceResponseError';\n this.response = response;\n }\n}\n\nexport class ResourceResponseWrapper {\n private readonly payload: NativeReadResourceResponse;\n\n constructor(payload: NativeReadResourceResponse) {\n this.payload = payload;\n }\n\n raw(): NativeReadResourceResponse {\n return this.payload;\n }\n\n text(): string {\n const entry = this.firstEntry();\n if ('text' in entry && typeof entry.text === 'string') {\n return entry.text;\n }\n if ('blob' in entry && typeof entry.blob === 'string') {\n try {\n return Buffer.from(entry.blob, 'base64').toString('utf8');\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to decode resource blob as UTF-8 text: ${reason}`, this.payload);\n }\n }\n throw new ResourceResponseError('Resource content does not include text or blob data', this.payload);\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n validator(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to parse resource text as JSON: ${reason}`, this.payload);\n }\n }\n\n private firstEntry(): NativeReadResourceResponse['contents'][number] {\n const [entry] = this.payload.contents ?? [];\n if (!entry) {\n throw new ResourceResponseError('Resource response did not include any contents', this.payload);\n }\n return entry;\n }\n}\n\nfunction hasStructuredContent(response: NativeCallToolResponse): response is NativeCallToolResponse & { structuredContent: Record<string, unknown> } {\n return Boolean((response as { structuredContent?: unknown }).structuredContent);\n}\n\nfunction isCompatibilityResult(response: NativeCallToolResponse): response is NativeCallToolResponse & { toolResult: unknown } {\n return hasOwn(response, 'toolResult');\n}\n\nfunction findFirstTextBlock(blocks: ContentBlock[] | undefined): TextContent | undefined {\n if (!Array.isArray(blocks)) {\n return undefined;\n }\n return blocks.find(isTextContent);\n}\n\nfunction collectPromptText(messages: PromptMessage[]): string[] {\n const segments: string[] = [];\n for (const message of messages) {\n const textBlock = isTextContent(message.content) ? message.content : undefined;\n if (textBlock) {\n segments.push(textBlock.text);\n }\n }\n return segments;\n}\n\nfunction isTextContent(block: unknown): block is TextContent {\n return Boolean(block) && typeof block === 'object' && (block as { type?: string }).type === 'text';\n}\n\nconst protoHasOwn = Object.prototype.hasOwnProperty;\n\nfunction hasOwn(target: object, key: PropertyKey): boolean {\n return protoHasOwn.call(target, key);\n}\n\nfunction formatErrorReason(error: unknown): string {\n if (error instanceof Error && typeof error.message === 'string') {\n return error.message;\n }\n if (typeof error === 'string') {\n return error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n"],"names":["PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","message","response","name","Error","payload","raw","json","validator","value","resolveJsonPayload","text","isCompatibilityResult","toolResult","throwIfError","textBlock","findFirstTextBlock","content","hasStructuredContent","structuredContent","JSON","parse","error","reason","formatErrorReason","isError","detail","String","segments","collectPromptText","messages","length","join","textValue","parsed","entry","firstEntry","blob","Buffer","from","toString","contents","Boolean","hasOwn","blocks","Array","isArray","undefined","find","isTextContent","push","block","type","protoHasOwn","Object","prototype","hasOwnProperty","target","key","call","stringify"],"mappings":";;;;;;;;;;;QAgGaA;eAAAA;;QAUAC;eAAAA;;QAkCAC;eAAAA;;QAUAC;eAAAA;;QA5IAC;eAAAA;;QAUAC;eAAAA;;;0BApBU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUhB,IAAA,AAAMD,kCAAN;;cAAMA;aAAAA,kBAGCE,OAAe,EAAEC,QAAgC;gCAHlDH;;gBAIT,kBAJSA;YAIHE;;QACN,MAAKE,IAAI,GAAG;QACZ,MAAKD,QAAQ,GAAGA;;;WANPH;qBAA0BK;AAUhC,IAAA,AAAMJ,oCAAN;;aAAMA,oBAGCK,OAA+B;gCAHhCL;QAIT,IAAI,CAACK,OAAO,GAAGA;;iBAJNL;IAOXM,OAAAA,GAEC,GAFDA,SAAAA;QACE,OAAO,IAAI,CAACD,OAAO;IACrB;IAEAE,OAAAA,IAMC,GANDA,SAAAA,KAAkBC,SAA4B;QAC5C,IAAMC,QAAQ,IAAI,CAACC,kBAAkB;QACrC,IAAIF,WAAW;YACbA,UAAUC;QACZ;QACA,OAAOA;IACT;IAEAE,OAAAA,IAgBC,GAhBDA,SAAAA;YAUuC;QATrC,IAAIC,sBAAsB,IAAI,CAACP,OAAO,GAAG;YACvC,IAAI,OAAO,IAAI,CAACA,OAAO,CAACQ,UAAU,KAAK,UAAU;gBAC/C,OAAO,IAAI,CAACR,OAAO,C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Ac,EAAEC,GAAgB;IAC9C,OAAOL,YAAYM,IAAI,CAACF,QAAQC;AAClC;AAEA,SAASlC,kBAAkBF,KAAc;IACvC,IAAIA,AAAK,YAALA,OAAiBlB,UAAS,OAAOkB,MAAMrB,OAAO,KAAK,UAAU;QAC/D,OAAOqB,MAAMrB,OAAO;IACtB;IACA,IAAI,OAAOqB,UAAU,UAAU;QAC7B,OAAOA;IACT;IACA,IAAI;QACF,OAAOF,KAAKwC,SAAS,CAACtC;IACxB,EAAE,eAAM;QACN,OAAOK,OAAOL;IAChB;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/response-wrappers.ts"],"sourcesContent":["import { Buffer } from 'node:buffer';\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { ContentBlock, PromptMessage, TextContent } from '@modelcontextprotocol/sdk/types.js';\n\nexport type NativeCallToolResponse = Awaited<ReturnType<Client['callTool']>>;\nexport type NativeGetPromptResponse = Awaited<ReturnType<Client['getPrompt']>>;\nexport type NativeReadResourceResponse = Awaited<ReturnType<Client['readResource']>>;\n\nexport type JsonValidator<T> = (value: unknown) => asserts value is T;\n\nexport class ToolResponseError extends Error {\n readonly response: NativeCallToolResponse;\n\n constructor(message: string, response: NativeCallToolResponse) {\n super(message);\n this.name = 'ToolResponseError';\n this.response = response;\n }\n}\n\nexport class ToolResponseWrapper {\n private readonly payload: NativeCallToolResponse;\n\n constructor(payload: NativeCallToolResponse) {\n this.payload = payload;\n }\n\n raw(): NativeCallToolResponse {\n return this.payload;\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const value = this.resolveJsonPayload();\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(value);\n }\n return value as T;\n }\n\n text(): string {\n if (isCompatibilityResult(this.payload)) {\n if (typeof this.payload.toolResult === 'string') {\n return this.payload.toolResult;\n }\n throw new ToolResponseError('Compatibility tool result is not text', this.payload);\n }\n\n this.throwIfError();\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include text content', this.payload);\n }\n\n return textBlock.text;\n }\n\n private resolveJsonPayload(): unknown {\n if (isCompatibilityResult(this.payload)) {\n return this.payload.toolResult;\n }\n\n this.throwIfError();\n\n if (hasStructuredContent(this.payload)) {\n return this.payload.structuredContent;\n }\n\n const textBlock = findFirstTextBlock(this.payload.content ?? []);\n if (!textBlock) {\n throw new ToolResponseError('Tool response did not include structuredContent or text content', this.payload);\n }\n\n try {\n return JSON.parse(textBlock.text) as unknown;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ToolResponseError(`Failed to parse tool text content as JSON: ${reason}`, this.payload);\n }\n }\n\n private throwIfError(): void {\n if ('isError' in this.payload && this.payload.isError) {\n let detail = typeof this.payload.error === 'object' && this.payload.error && 'message' in this.payload.error ? String((this.payload.error as { message?: unknown }).message ?? '') : '';\n if (!detail) {\n const textBlock = findFirstTextBlock((this.payload.content ?? []) as ContentBlock[]);\n if (textBlock?.text) {\n detail = textBlock.text;\n }\n }\n const message = detail ? `Tool invocation returned an error result: ${detail}` : 'Tool invocation returned an error result';\n throw new ToolResponseError(message, this.payload);\n }\n }\n}\n\nexport class PromptResponseError extends Error {\n readonly response: NativeGetPromptResponse;\n\n constructor(message: string, response: NativeGetPromptResponse) {\n super(message);\n this.name = 'PromptResponseError';\n this.response = response;\n }\n}\n\nexport class PromptResponseWrapper {\n private readonly payload: NativeGetPromptResponse;\n\n constructor(payload: NativeGetPromptResponse) {\n this.payload = payload;\n }\n\n raw(): NativeGetPromptResponse {\n return this.payload;\n }\n\n text(): string {\n const segments = collectPromptText(this.payload.messages);\n if (!segments.length) {\n throw new PromptResponseError('Prompt response did not include text content', this.payload);\n }\n return segments.join('\\n\\n');\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new PromptResponseError(`Failed to parse prompt text as JSON: ${reason}`, this.payload);\n }\n }\n}\n\nexport class ResourceResponseError extends Error {\n readonly response: NativeReadResourceResponse;\n\n constructor(message: string, response: NativeReadResourceResponse) {\n super(message);\n this.name = 'ResourceResponseError';\n this.response = response;\n }\n}\n\nexport class ResourceResponseWrapper {\n private readonly payload: NativeReadResourceResponse;\n\n constructor(payload: NativeReadResourceResponse) {\n this.payload = payload;\n }\n\n raw(): NativeReadResourceResponse {\n return this.payload;\n }\n\n text(): string {\n const entry = this.firstEntry();\n if ('text' in entry && typeof entry.text === 'string') {\n return entry.text;\n }\n if ('blob' in entry && typeof entry.blob === 'string') {\n try {\n return Buffer.from(entry.blob, 'base64').toString('utf8');\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to decode resource blob as UTF-8 text: ${reason}`, this.payload);\n }\n }\n throw new ResourceResponseError('Resource content does not include text or blob data', this.payload);\n }\n\n json<T = unknown>(validator?: JsonValidator<T>): T {\n const textValue = this.text();\n try {\n const parsed = JSON.parse(textValue) as unknown;\n if (validator) {\n const assertValid: JsonValidator<T> = validator;\n assertValid(parsed);\n }\n return parsed as T;\n } catch (error) {\n const reason = formatErrorReason(error);\n throw new ResourceResponseError(`Failed to parse resource text as JSON: ${reason}`, this.payload);\n }\n }\n\n private firstEntry(): NativeReadResourceResponse['contents'][number] {\n const [entry] = this.payload.contents ?? [];\n if (!entry) {\n throw new ResourceResponseError('Resource response did not include any contents', this.payload);\n }\n return entry;\n }\n}\n\nfunction hasStructuredContent(response: NativeCallToolResponse): response is NativeCallToolResponse & { structuredContent: Record<string, unknown> } {\n return Boolean((response as { structuredContent?: unknown }).structuredContent);\n}\n\nfunction isCompatibilityResult(response: NativeCallToolResponse): response is NativeCallToolResponse & { toolResult: unknown } {\n return hasOwn(response, 'toolResult');\n}\n\nfunction findFirstTextBlock(blocks: ContentBlock[] | undefined): TextContent | undefined {\n if (!Array.isArray(blocks)) {\n return undefined;\n }\n return blocks.find(isTextContent);\n}\n\nfunction collectPromptText(messages: PromptMessage[]): string[] {\n const segments: string[] = [];\n for (const message of messages) {\n const textBlock = isTextContent(message.content) ? message.content : undefined;\n if (textBlock) {\n segments.push(textBlock.text);\n }\n }\n return segments;\n}\n\nfunction isTextContent(block: unknown): block is TextContent {\n return Boolean(block) && typeof block === 'object' && (block as { type?: string }).type === 'text';\n}\n\nconst protoHasOwn = Object.prototype.hasOwnProperty;\n\nfunction hasOwn(target: object, key: PropertyKey): boolean {\n return protoHasOwn.call(target, key);\n}\n\nfunction formatErrorReason(error: unknown): string {\n if (error instanceof Error && typeof error.message === 'string') {\n return error.message;\n }\n if (typeof error === 'string') {\n return error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n"],"names":["PromptResponseError","PromptResponseWrapper","ResourceResponseError","ResourceResponseWrapper","ToolResponseError","ToolResponseWrapper","message","response","name","Error","payload","raw","json","validator","value","resolveJsonPayload","assertValid","text","isCompatibilityResult","toolResult","throwIfError","textBlock","findFirstTextBlock","content","hasStructuredContent","structuredContent","JSON","parse","error","reason","formatErrorReason","isError","detail","String","segments","collectPromptText","messages","length","join","textValue","parsed","entry","firstEntry","blob","Buffer","from","toString","contents","Boolean","hasOwn","blocks","Array","isArray","undefined","find","isTextContent","push","block","type","protoHasOwn","Object","prototype","hasOwnProperty","target","key","call","stringify"],"mappings":";;;;;;;;;;;QAiGaA;eAAAA;;QAUAC;eAAAA;;QAmCAC;eAAAA;;QAUAC;eAAAA;;QA9IAC;eAAAA;;QAUAC;eAAAA;;;0BApBU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUhB,IAAA,AAAMD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,UAAU;AAC1B;AAEA,SAASe,mBAAmB4B,MAAkC;IAC5D,IAAI,CAACC,MAAMC,OAAO,CAACF,SAAS;QAC1B,OAAOG;IACT;IACA,OAAOH,OAAOI,IAAI,CAACC;AACrB;AAEA,SAASpB,kBAAkBC,QAAyB;IAClD,IAAMF,WAAqB,EAAE;QACxB,kCAAA,2BAAA;;QAAL,QAAK,YAAiBE,6BAAjB,SAAA,6BAAA,QAAA,yBAAA,iCAA2B;YAA3B,IAAM9B,UAAN;YACH,IAAMe,YAAYkC,cAAcjD,QAAQiB,OAAO,IAAIjB,QAAQiB,OAAO,GAAG8B;YACrE,IAAIhC,WAAW;gBACba,SAASsB,IAAI,CAACnC,UAAUJ,IAAI;YAC9B;QACF;;QALK;QAAA;;;iBAAA,6BAAA;gBAAA;;;gBAAA;sBAAA;;;;IAML,OAAOiB;AACT;AAEA,SAASqB,cAAcE,KAAc;IACnC,OAAOT,QAAQS,UAAU,CAAA,OAAOA,sCAAP,SAAOA,MAAI,MAAM,YAAY,AAACA,MAA4BC,IAAI,KAAK;AAC9F;AAEA,IAAMC,cAAcC,OAAOC,SAAS,CAACC,cAAc;AAEnD,SAASb,OAAOc,MAAc,EAAEC,GAAgB;IAC9C,OAAOL,YAAYM,IAAI,CAACF,QAAQC;AAClC;AAEA,SAASlC,kBAAkBF,KAAc;IACvC,IAAIA,AAAK,YAALA,OAAiBnB,UAAS,OAAOmB,MAAMtB,OAAO,KAAK,UAAU;QAC/D,OAAOsB,MAAMtB,OAAO;IACtB;IACA,IAAI,OAAOsB,UAAU,UAAU;QAC7B,OAAOA;IACT;IACA,IAAI;QACF,OAAOF,KAAKwC,SAAS,CAACtC;IACxB,EAAE,eAAM;QACN,OAAOK,OAAOL;IAChB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/search/index.ts"],"sourcesContent":["/**\n * Search module for MCP capability discovery\n */\n\nexport type { CapabilityClient } from './search.ts';\nexport { buildCapabilityIndex, search, searchCapabilities } from './search.ts';\nexport type {\n CapabilityIndex,\n CapabilityType,\n IndexedCapability,\n IndexedPrompt,\n IndexedResource,\n IndexedTool,\n SearchField,\n SearchOptions,\n SearchResponse,\n SearchResult,\n} from './types.ts';\n"],"names":["buildCapabilityIndex","search","searchCapabilities"],"mappings":"AAAA;;CAEC;;;;;;;;;;;QAGQA;eAAAA,8BAAoB;;QAAEC;eAAAA,gBAAM;;QAAEC;eAAAA,4BAAkB;;;wBAAQ"}
|
|
@@ -40,11 +40,8 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
|
40
40
|
reject(error);
|
|
41
41
|
return;
|
|
42
42
|
}
|
|
43
|
-
if (info.done)
|
|
44
|
-
|
|
45
|
-
} else {
|
|
46
|
-
Promise.resolve(value).then(_next, _throw);
|
|
47
|
-
}
|
|
43
|
+
if (info.done) resolve(value);
|
|
44
|
+
else Promise.resolve(value).then(_next, _throw);
|
|
48
45
|
}
|
|
49
46
|
function _async_to_generator(fn) {
|
|
50
47
|
return function() {
|
|
@@ -86,23 +83,11 @@ function _iterable_to_array_limit(arr, i) {
|
|
|
86
83
|
return _arr;
|
|
87
84
|
}
|
|
88
85
|
function _non_iterable_rest() {
|
|
89
|
-
throw new TypeError("Invalid attempt to destructure non-iterable instance
|
|
86
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
90
87
|
}
|
|
91
88
|
function _sliced_to_array(arr, i) {
|
|
92
89
|
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
|
|
93
90
|
}
|
|
94
|
-
function _type_of(obj) {
|
|
95
|
-
"@swc/helpers - typeof";
|
|
96
|
-
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
97
|
-
}
|
|
98
|
-
function _unsupported_iterable_to_array(o, minLen) {
|
|
99
|
-
if (!o) return;
|
|
100
|
-
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
101
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
102
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
103
|
-
if (n === "Map" || n === "Set") return Array.from(n);
|
|
104
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
105
|
-
}
|
|
106
91
|
function _ts_generator(thisArg, body) {
|
|
107
92
|
var f, y, t, _ = {
|
|
108
93
|
label: 0,
|
|
@@ -202,6 +187,18 @@ function _ts_generator(thisArg, body) {
|
|
|
202
187
|
};
|
|
203
188
|
}
|
|
204
189
|
}
|
|
190
|
+
function _type_of(obj) {
|
|
191
|
+
"@swc/helpers - typeof";
|
|
192
|
+
return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
|
|
193
|
+
}
|
|
194
|
+
function _unsupported_iterable_to_array(o, minLen) {
|
|
195
|
+
if (!o) return;
|
|
196
|
+
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
197
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
198
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
199
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
200
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
201
|
+
}
|
|
205
202
|
var DEFAULT_LIMIT = 20;
|
|
206
203
|
var DEFAULT_THRESHOLD = 0;
|
|
207
204
|
var DEFAULT_TYPES = [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/Projects/mcp-z/client/src/search/search.ts"],"sourcesContent":["/**\n * Search implementation for MCP capability discovery\n *\n * Provides text-based search across tools, prompts, and resources\n * from connected MCP servers.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { PromptArgument } from '../connection/types.ts';\nimport type { CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './types.ts';\n\nexport type CapabilityClient = Pick<Client, 'listTools' | 'listPrompts' | 'listResources'>;\n\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_THRESHOLD = 0;\nconst DEFAULT_TYPES: CapabilityType[] = ['tool', 'prompt', 'resource'];\nconst DEFAULT_SEARCH_FIELDS: SearchField[] = ['name', 'description', 'schema'];\n\n/**\n * Extract searchable text from a JSON Schema's property descriptions\n */\nfunction extractSchemaText(inputSchema: unknown): string {\n if (!inputSchema || typeof inputSchema !== 'object') {\n return '';\n }\n\n const schema = inputSchema as {\n properties?: Record<string, { description?: string; name?: string }>;\n description?: string;\n };\n\n const parts: string[] = [];\n\n // Add schema-level description if present\n if (schema.description) {\n parts.push(schema.description);\n }\n\n // Add property names and descriptions\n if (schema.properties) {\n for (const [propName, prop] of Object.entries(schema.properties)) {\n parts.push(propName);\n if (prop && typeof prop === 'object' && prop.description) {\n parts.push(prop.description);\n }\n }\n }\n\n return parts.join(' ');\n}\n\n/**\n * Extract searchable text from prompt arguments\n */\nfunction extractArgumentsText(args: PromptArgument[] | undefined): string {\n if (!args || !Array.isArray(args)) {\n return '';\n }\n\n return args\n .map((arg) => {\n const parts = [arg.name];\n if (arg.description) {\n parts.push(arg.description);\n }\n return parts.join(' ');\n })\n .join(' ');\n}\n\n/**\n * Build an index of capabilities from connected MCP clients\n */\nexport async function buildCapabilityIndex(clients: Map<string, CapabilityClient>): Promise<CapabilityIndex> {\n const capabilities: IndexedCapability[] = [];\n const servers: string[] = [];\n\n for (const [serverName, client] of clients) {\n servers.push(serverName);\n\n // Fetch all capabilities in parallel, handling errors gracefully\n const [toolsResult, promptsResult, resourcesResult] = await Promise.all([client.listTools().catch(() => null), client.listPrompts().catch(() => null), client.listResources().catch(() => null)]);\n\n // Index tools\n if (toolsResult?.tools) {\n for (const tool of toolsResult.tools) {\n capabilities.push({\n type: 'tool',\n server: serverName,\n name: tool.name,\n description: tool.description,\n schemaText: extractSchemaText(tool.inputSchema),\n } satisfies IndexedTool);\n }\n }\n\n // Index prompts\n if (promptsResult?.prompts) {\n for (const prompt of promptsResult.prompts) {\n capabilities.push({\n type: 'prompt',\n server: serverName,\n name: prompt.name,\n description: prompt.description,\n argumentsText: extractArgumentsText(prompt.arguments as PromptArgument[] | undefined),\n arguments: prompt.arguments as PromptArgument[] | undefined,\n } satisfies IndexedPrompt);\n }\n }\n\n // Index resources\n if (resourcesResult?.resources) {\n for (const resource of resourcesResult.resources) {\n capabilities.push({\n type: 'resource',\n server: serverName,\n name: resource.name,\n description: resource.description,\n uri: resource.uri,\n mimeType: resource.mimeType,\n } satisfies IndexedResource);\n }\n }\n }\n\n return {\n capabilities,\n servers,\n indexedAt: new Date(),\n };\n}\n\n/**\n * Calculate relevance score and matched fields for a capability against a query\n */\nfunction scoreCapability(capability: IndexedCapability, queryTerms: string[], searchFields: SearchField[]): { score: number; matchedOn: string[] } {\n const matchedOn: string[] = [];\n let totalScore = 0;\n\n // Weights for different match types\n const EXACT_NAME_WEIGHT = 1.0;\n const PARTIAL_NAME_WEIGHT = 0.8;\n const DESCRIPTION_WEIGHT = 0.6;\n const SCHEMA_WEIGHT = 0.4;\n const SERVER_WEIGHT = 0.3;\n\n const nameLower = capability.name.toLowerCase();\n const descLower = (capability.description || '').toLowerCase();\n const serverLower = capability.server.toLowerCase();\n\n // Get schema/arguments text based on type\n let schemaTextLower = '';\n if (capability.type === 'tool') {\n schemaTextLower = capability.schemaText.toLowerCase();\n } else if (capability.type === 'prompt') {\n schemaTextLower = capability.argumentsText.toLowerCase();\n } else if (capability.type === 'resource') {\n // For resources, include URI and mimeType in searchable text\n schemaTextLower = `${capability.uri} ${capability.mimeType || ''}`.toLowerCase();\n }\n\n for (const term of queryTerms) {\n const termLower = term.toLowerCase();\n\n // Check name matches\n if (searchFields.includes('name')) {\n if (nameLower === termLower) {\n totalScore += EXACT_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n } else if (nameLower.includes(termLower)) {\n totalScore += PARTIAL_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n }\n }\n\n // Check description matches\n if (searchFields.includes('description') && descLower.includes(termLower)) {\n totalScore += DESCRIPTION_WEIGHT;\n if (!matchedOn.includes('description')) matchedOn.push('description');\n }\n\n // Check schema/arguments matches\n if (searchFields.includes('schema') && schemaTextLower.includes(termLower)) {\n totalScore += SCHEMA_WEIGHT;\n const fieldName = capability.type === 'tool' ? 'inputSchema' : capability.type === 'prompt' ? 'arguments' : 'uri';\n if (!matchedOn.includes(fieldName)) matchedOn.push(fieldName);\n }\n\n // Check server name matches\n if (searchFields.includes('server') && serverLower.includes(termLower)) {\n totalScore += SERVER_WEIGHT;\n if (!matchedOn.includes('server')) matchedOn.push('server');\n }\n }\n\n // Normalize score to 0-1 range based on number of terms\n const normalizedScore = queryTerms.length > 0 ? Math.min(1, totalScore / queryTerms.length) : 0;\n\n return { score: normalizedScore, matchedOn };\n}\n\n/**\n * Search for capabilities matching a query string\n */\nexport function searchCapabilities(index: CapabilityIndex, query: string, options: SearchOptions = {}): SearchResponse {\n const { types = DEFAULT_TYPES, servers, searchFields = DEFAULT_SEARCH_FIELDS, limit = DEFAULT_LIMIT, threshold = DEFAULT_THRESHOLD } = options;\n\n // Tokenize query into search terms\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0);\n\n // If empty query, return empty results\n if (queryTerms.length === 0) {\n return { query, results: [], total: 0 };\n }\n\n // Filter and score capabilities\n const scoredResults: Array<{ capability: IndexedCapability; score: number; matchedOn: string[] }> = [];\n\n for (const capability of index.capabilities) {\n // Filter by type\n if (!types.includes(capability.type)) {\n continue;\n }\n\n // Filter by server\n if (servers && servers.length > 0 && !servers.includes(capability.server)) {\n continue;\n }\n\n // Score the capability\n const { score, matchedOn } = scoreCapability(capability, queryTerms, searchFields);\n\n // Apply threshold filter\n if (score >= threshold && matchedOn.length > 0) {\n scoredResults.push({ capability, score, matchedOn });\n }\n }\n\n // Sort by score descending\n scoredResults.sort((a, b) => b.score - a.score);\n\n // Get total before limiting\n const total = scoredResults.length;\n\n // Apply limit and transform to SearchResult\n const results: SearchResult[] = scoredResults.slice(0, limit).map(({ capability, score, matchedOn }) => ({\n type: capability.type,\n server: capability.server,\n name: capability.name,\n description: capability.description,\n matchedOn,\n score,\n }));\n\n return { query, results, total };\n}\n\n/**\n * Convenience function to search directly from connected clients\n * Builds index and performs search in one call\n */\nexport async function search(clients: Map<string, CapabilityClient>, query: string, options: SearchOptions = {}): Promise<SearchResponse> {\n const index = await buildCapabilityIndex(clients);\n return searchCapabilities(index, query, options);\n}\n"],"names":["buildCapabilityIndex","search","searchCapabilities","DEFAULT_LIMIT","DEFAULT_THRESHOLD","DEFAULT_TYPES","DEFAULT_SEARCH_FIELDS","extractSchemaText","inputSchema","schema","parts","description","push","properties","Object","entries","propName","prop","join","extractArgumentsText","args","Array","isArray","map","arg","name","clients","capabilities","servers","serverName","client","toolsResult","promptsResult","resourcesResult","tool","prompt","resource","Promise","all","listTools","catch","listPrompts","listResources","tools","type","server","schemaText","prompts","argumentsText","arguments","resources","uri","mimeType","indexedAt","Date","scoreCapability","capability","queryTerms","searchFields","matchedOn","totalScore","EXACT_NAME_WEIGHT","PARTIAL_NAME_WEIGHT","DESCRIPTION_WEIGHT","SCHEMA_WEIGHT","SERVER_WEIGHT","nameLower","toLowerCase","descLower","serverLower","schemaTextLower","term","termLower","includes","fieldName","normalizedScore","length","Math","min","score","index","query","options","types","limit","threshold","split","filter","results","total","scoredResults","sort","a","b","slice"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAoEqBA;eAAAA;;QA+LAC;eAAAA;;QA5DNC;eAAAA;;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AM;AACjC;AAMO,SAAexF;wCAAOyB,OAAsC,EAAEuD,KAAa;YAAEC,SAC5EF;;;;;oBAD4EE,UAAAA,oEAAyB,CAAC;oBAC9F;;wBAAMlF,qBAAqB0B;;;oBAAnCsD,QAAQ;oBACd;;wBAAO9E,mBAAmB8E,OAAOC,OAAOC;;;;IAC1C"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/search/search.ts"],"sourcesContent":["/**\n * Search implementation for MCP capability discovery\n *\n * Provides text-based search across tools, prompts, and resources\n * from connected MCP servers.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js';\nimport type { PromptArgument } from '../connection/types.ts';\nimport type { CapabilityIndex, CapabilityType, IndexedCapability, IndexedPrompt, IndexedResource, IndexedTool, SearchField, SearchOptions, SearchResponse, SearchResult } from './types.ts';\n\nexport type CapabilityClient = Pick<Client, 'listTools' | 'listPrompts' | 'listResources'>;\n\nconst DEFAULT_LIMIT = 20;\nconst DEFAULT_THRESHOLD = 0;\nconst DEFAULT_TYPES: CapabilityType[] = ['tool', 'prompt', 'resource'];\nconst DEFAULT_SEARCH_FIELDS: SearchField[] = ['name', 'description', 'schema'];\n\n/**\n * Extract searchable text from a JSON Schema's property descriptions\n */\nfunction extractSchemaText(inputSchema: unknown): string {\n if (!inputSchema || typeof inputSchema !== 'object') {\n return '';\n }\n\n const schema = inputSchema as {\n properties?: Record<string, { description?: string; name?: string }>;\n description?: string;\n };\n\n const parts: string[] = [];\n\n // Add schema-level description if present\n if (schema.description) {\n parts.push(schema.description);\n }\n\n // Add property names and descriptions\n if (schema.properties) {\n for (const [propName, prop] of Object.entries(schema.properties)) {\n parts.push(propName);\n if (prop && typeof prop === 'object' && prop.description) {\n parts.push(prop.description);\n }\n }\n }\n\n return parts.join(' ');\n}\n\n/**\n * Extract searchable text from prompt arguments\n */\nfunction extractArgumentsText(args: PromptArgument[] | undefined): string {\n if (!args || !Array.isArray(args)) {\n return '';\n }\n\n return args\n .map((arg) => {\n const parts = [arg.name];\n if (arg.description) {\n parts.push(arg.description);\n }\n return parts.join(' ');\n })\n .join(' ');\n}\n\n/**\n * Build an index of capabilities from connected MCP clients\n */\nexport async function buildCapabilityIndex(clients: Map<string, CapabilityClient>): Promise<CapabilityIndex> {\n const capabilities: IndexedCapability[] = [];\n const servers: string[] = [];\n\n for (const [serverName, client] of clients) {\n servers.push(serverName);\n\n // Fetch all capabilities in parallel, handling errors gracefully\n const [toolsResult, promptsResult, resourcesResult] = await Promise.all([client.listTools().catch(() => null), client.listPrompts().catch(() => null), client.listResources().catch(() => null)]);\n\n // Index tools\n if (toolsResult?.tools) {\n for (const tool of toolsResult.tools) {\n capabilities.push({\n type: 'tool',\n server: serverName,\n name: tool.name,\n description: tool.description,\n schemaText: extractSchemaText(tool.inputSchema),\n } satisfies IndexedTool);\n }\n }\n\n // Index prompts\n if (promptsResult?.prompts) {\n for (const prompt of promptsResult.prompts) {\n capabilities.push({\n type: 'prompt',\n server: serverName,\n name: prompt.name,\n description: prompt.description,\n argumentsText: extractArgumentsText(prompt.arguments as PromptArgument[] | undefined),\n arguments: prompt.arguments as PromptArgument[] | undefined,\n } satisfies IndexedPrompt);\n }\n }\n\n // Index resources\n if (resourcesResult?.resources) {\n for (const resource of resourcesResult.resources) {\n capabilities.push({\n type: 'resource',\n server: serverName,\n name: resource.name,\n description: resource.description,\n uri: resource.uri,\n mimeType: resource.mimeType,\n } satisfies IndexedResource);\n }\n }\n }\n\n return {\n capabilities,\n servers,\n indexedAt: new Date(),\n };\n}\n\n/**\n * Calculate relevance score and matched fields for a capability against a query\n */\nfunction scoreCapability(capability: IndexedCapability, queryTerms: string[], searchFields: SearchField[]): { score: number; matchedOn: string[] } {\n const matchedOn: string[] = [];\n let totalScore = 0;\n\n // Weights for different match types\n const EXACT_NAME_WEIGHT = 1.0;\n const PARTIAL_NAME_WEIGHT = 0.8;\n const DESCRIPTION_WEIGHT = 0.6;\n const SCHEMA_WEIGHT = 0.4;\n const SERVER_WEIGHT = 0.3;\n\n const nameLower = capability.name.toLowerCase();\n const descLower = (capability.description || '').toLowerCase();\n const serverLower = capability.server.toLowerCase();\n\n // Get schema/arguments text based on type\n let schemaTextLower = '';\n if (capability.type === 'tool') {\n schemaTextLower = capability.schemaText.toLowerCase();\n } else if (capability.type === 'prompt') {\n schemaTextLower = capability.argumentsText.toLowerCase();\n } else if (capability.type === 'resource') {\n // For resources, include URI and mimeType in searchable text\n schemaTextLower = `${capability.uri} ${capability.mimeType || ''}`.toLowerCase();\n }\n\n for (const term of queryTerms) {\n const termLower = term.toLowerCase();\n\n // Check name matches\n if (searchFields.includes('name')) {\n if (nameLower === termLower) {\n totalScore += EXACT_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n } else if (nameLower.includes(termLower)) {\n totalScore += PARTIAL_NAME_WEIGHT;\n if (!matchedOn.includes('name')) matchedOn.push('name');\n }\n }\n\n // Check description matches\n if (searchFields.includes('description') && descLower.includes(termLower)) {\n totalScore += DESCRIPTION_WEIGHT;\n if (!matchedOn.includes('description')) matchedOn.push('description');\n }\n\n // Check schema/arguments matches\n if (searchFields.includes('schema') && schemaTextLower.includes(termLower)) {\n totalScore += SCHEMA_WEIGHT;\n const fieldName = capability.type === 'tool' ? 'inputSchema' : capability.type === 'prompt' ? 'arguments' : 'uri';\n if (!matchedOn.includes(fieldName)) matchedOn.push(fieldName);\n }\n\n // Check server name matches\n if (searchFields.includes('server') && serverLower.includes(termLower)) {\n totalScore += SERVER_WEIGHT;\n if (!matchedOn.includes('server')) matchedOn.push('server');\n }\n }\n\n // Normalize score to 0-1 range based on number of terms\n const normalizedScore = queryTerms.length > 0 ? Math.min(1, totalScore / queryTerms.length) : 0;\n\n return { score: normalizedScore, matchedOn };\n}\n\n/**\n * Search for capabilities matching a query string\n */\nexport function searchCapabilities(index: CapabilityIndex, query: string, options: SearchOptions = {}): SearchResponse {\n const { types = DEFAULT_TYPES, servers, searchFields = DEFAULT_SEARCH_FIELDS, limit = DEFAULT_LIMIT, threshold = DEFAULT_THRESHOLD } = options;\n\n // Tokenize query into search terms\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0);\n\n // If empty query, return empty results\n if (queryTerms.length === 0) {\n return { query, results: [], total: 0 };\n }\n\n // Filter and score capabilities\n const scoredResults: Array<{ capability: IndexedCapability; score: number; matchedOn: string[] }> = [];\n\n for (const capability of index.capabilities) {\n // Filter by type\n if (!types.includes(capability.type)) {\n continue;\n }\n\n // Filter by server\n if (servers && servers.length > 0 && !servers.includes(capability.server)) {\n continue;\n }\n\n // Score the capability\n const { score, matchedOn } = scoreCapability(capability, queryTerms, searchFields);\n\n // Apply threshold filter\n if (score >= threshold && matchedOn.length > 0) {\n scoredResults.push({ capability, score, matchedOn });\n }\n }\n\n // Sort by score descending\n scoredResults.sort((a, b) => b.score - a.score);\n\n // Get total before limiting\n const total = scoredResults.length;\n\n // Apply limit and transform to SearchResult\n const results: SearchResult[] = scoredResults.slice(0, limit).map(({ capability, score, matchedOn }) => ({\n type: capability.type,\n server: capability.server,\n name: capability.name,\n description: capability.description,\n matchedOn,\n score,\n }));\n\n return { query, results, total };\n}\n\n/**\n * Convenience function to search directly from connected clients\n * Builds index and performs search in one call\n */\nexport async function search(clients: Map<string, CapabilityClient>, query: string, options: SearchOptions = {}): Promise<SearchResponse> {\n const index = await buildCapabilityIndex(clients);\n return searchCapabilities(index, query, options);\n}\n"],"names":["buildCapabilityIndex","search","searchCapabilities","DEFAULT_LIMIT","DEFAULT_THRESHOLD","DEFAULT_TYPES","DEFAULT_SEARCH_FIELDS","extractSchemaText","inputSchema","schema","parts","description","push","properties","Object","entries","propName","prop","join","extractArgumentsText","args","Array","isArray","map","arg","name","clients","capabilities","servers","serverName","client","toolsResult","promptsResult","resourcesResult","tool","prompt","resource","Promise","all","listTools","catch","listPrompts","listResources","tools","type","server","schemaText","prompts","argumentsText","arguments","resources","uri","mimeType","indexedAt","Date","scoreCapability","capability","queryTerms","searchFields","matchedOn","totalScore","EXACT_NAME_WEIGHT","PARTIAL_NAME_WEIGHT","DESCRIPTION_WEIGHT","SCHEMA_WEIGHT","SERVER_WEIGHT","nameLower","toLowerCase","descLower","serverLower","schemaTextLower","term","termLower","includes","fieldName","normalizedScore","length","Math","min","score","index","query","options","types","limit","threshold","split","filter","results","total","scoredResults","sort","a","b","slice"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;QAoEqBA;eAAAA;;QA+LAC;eAAAA;;QA5DNC;eAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA/LhB,IAAMC,gBAAgB;AACtB,IAAMC,oBAAoB;AAC1B,IAAMC,gBAAkC;IAAC;IAAQ;IAAU;CAAW;AACtE,IAAMC,wBAAuC;IAAC;IAAQ;IAAe;CAAS;AAE9E;;CAEC,GACD,SAASC,kBAAkBC,WAAoB;IAC7C,IAAI,CAACA,eAAe,CAAA,OAAOA,4CAAP,SAAOA,YAAU,MAAM,UAAU;QACnD,OAAO;IACT;IAEA,IAAMC,SAASD;IAKf,IAAME,QAAkB,EAAE;IAE1B,0CAA0C;IAC1C,IAAID,OAAOE,WAAW,EAAE;QACtBD,MAAME,IAAI,CAACH,OAAOE,WAAW;IAC/B;IAEA,sCAAsC;IACtC,IAAIF,OAAOI,UAAU,EAAE;YAChB,kCAAA,2BAAA;;YAAL,QAAK,YAA0BC,OAAOC,OAAO,CAACN,OAAOI,UAAU,sBAA1D,SAAA,6BAAA,QAAA,yBAAA,iCAA6D;gBAA7D,mCAAA,iBAAOG,2BAAUC;gBACpBP,MAAME,IAAI,CAACI;gBACX,IAAIC,QAAQ,CAAA,OAAOA,qCAAP,SAAOA,KAAG,MA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AMY,UAA0BE,cAAcI,KAAK,CAAC,GAAGV,OAAO7D,GAAG,CAAC;YAAGiC,mBAAAA,YAAYuB,cAAAA,OAAOpB,kBAAAA;eAAiB;YACvGf,MAAMY,WAAWZ,IAAI;YACrBC,QAAQW,WAAWX,MAAM;YACzBpB,MAAM+B,WAAW/B,IAAI;YACrBd,aAAa6C,WAAW7C,WAAW;YACnCgD,WAAAA;YACAoB,OAAAA;QACF;;IAEA,OAAO;QAAEE,OAAAA;QAAOO,SAAAA;QAASC,OAAAA;IAAM;AACjC;AAMO,SAAexF;wCAAOyB,OAAsC,EAAEuD,KAAa;YAAEC,SAC5EF;;;;;oBAD4EE,UAAAA,oEAAyB,CAAC;oBAC9F;;wBAAMlF,qBAAqB0B;;;oBAAnCsD,QAAQ;oBACd;;wBAAO9E,mBAAmB8E,OAAOC,OAAOC;;;;IAC1C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/mcp-z/client/src/search/types.ts"],"sourcesContent":["/**\n * Search types for MCP capability discovery\n *\n * Enables agents to discover tools, prompts, and resources without\n * loading full schemas into context.\n */\n\nimport type { PromptArgument } from '../connection/types.ts';\n\n/**\n * Types of MCP capabilities that can be searched\n */\nexport type CapabilityType = 'tool' | 'prompt' | 'resource';\n\n/**\n * Fields that can be searched within capabilities\n */\nexport type SearchField = 'name' | 'description' | 'schema' | 'server';\n\n/**\n * Options for configuring search behavior\n */\nexport interface SearchOptions {\n /**\n * Filter to specific capability types\n * @default ['tool', 'prompt', 'resource']\n */\n types?: CapabilityType[];\n\n /**\n * Filter to specific servers by name\n * @default all servers in config\n */\n servers?: string[];\n\n /**\n * Which fields to search within\n * @default ['name', 'description', 'schema']\n */\n searchFields?: SearchField[];\n\n /**\n * Maximum number of results to return\n * @default 20\n */\n limit?: number;\n\n /**\n * Minimum relevance score (0-1) for results\n * @default 0\n */\n threshold?: number;\n}\n\n/**\n * A single search result representing a matched capability\n */\nexport interface SearchResult {\n /** The type of capability */\n type: CapabilityType;\n\n /** The server that provides this capability */\n server: string;\n\n /** The name of the capability */\n name: string;\n\n /** Human-readable description (may be truncated) */\n description: string | undefined;\n\n /** Which fields matched the search query */\n matchedOn: string[];\n\n /** Relevance score from 0 (low) to 1 (high) */\n score: number;\n}\n\n/**\n * Complete search response\n */\nexport interface SearchResponse {\n /** The original search query */\n query: string;\n\n /** Matching results, sorted by relevance */\n results: SearchResult[];\n\n /** Total number of matches before limit was applied */\n total: number;\n}\n\n/**\n * Internal representation of a tool for indexing\n */\nexport interface IndexedTool {\n type: 'tool';\n server: string;\n name: string;\n description: string | undefined;\n /** Flattened searchable text from inputSchema property descriptions */\n schemaText: string;\n}\n\n/**\n * Internal representation of a prompt for indexing\n */\nexport interface IndexedPrompt {\n type: 'prompt';\n server: string;\n name: string;\n description: string | undefined;\n /** Flattened searchable text from arguments */\n argumentsText: string;\n arguments: PromptArgument[] | undefined;\n}\n\n/**\n * Internal representation of a resource for indexing\n */\nexport interface IndexedResource {\n type: 'resource';\n server: string;\n name: string;\n description: string | undefined;\n uri: string;\n mimeType: string | undefined;\n}\n\n/**\n * Union of all indexed capability types\n */\nexport type IndexedCapability = IndexedTool | IndexedPrompt | IndexedResource;\n\n/**\n * Index containing all capabilities from connected servers\n */\nexport interface CapabilityIndex {\n /** All indexed capabilities */\n capabilities: IndexedCapability[];\n\n /** Servers that were indexed */\n servers: string[];\n\n /** When the index was created */\n indexedAt: Date;\n}\n"],"names":[],"mappings":"AAAA;;;;;CAKC"}
|
|
@@ -31,11 +31,8 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
|
31
31
|
reject(error);
|
|
32
32
|
return;
|
|
33
33
|
}
|
|
34
|
-
if (info.done)
|
|
35
|
-
|
|
36
|
-
} else {
|
|
37
|
-
Promise.resolve(value).then(_next, _throw);
|
|
38
|
-
}
|
|
34
|
+
if (info.done) resolve(value);
|
|
35
|
+
else Promise.resolve(value).then(_next, _throw);
|
|
39
36
|
}
|
|
40
37
|
function _async_to_generator(fn) {
|
|
41
38
|
return function() {
|
|
@@ -60,9 +57,7 @@ function _define_property(obj, key, value) {
|
|
|
60
57
|
configurable: true,
|
|
61
58
|
writable: true
|
|
62
59
|
});
|
|
63
|
-
} else
|
|
64
|
-
obj[key] = value;
|
|
65
|
-
}
|
|
60
|
+
} else obj[key] = value;
|
|
66
61
|
return obj;
|
|
67
62
|
}
|
|
68
63
|
function _getRequireWildcardCache(nodeInterop) {
|
|
@@ -74,18 +69,12 @@ function _getRequireWildcardCache(nodeInterop) {
|
|
|
74
69
|
})(nodeInterop);
|
|
75
70
|
}
|
|
76
71
|
function _interop_require_wildcard(obj, nodeInterop) {
|
|
77
|
-
if (!nodeInterop && obj && obj.__esModule)
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
return {
|
|
82
|
-
default: obj
|
|
83
|
-
};
|
|
84
|
-
}
|
|
72
|
+
if (!nodeInterop && obj && obj.__esModule) return obj;
|
|
73
|
+
if (obj === null || typeof obj !== "object" && typeof obj !== "function") return {
|
|
74
|
+
default: obj
|
|
75
|
+
};
|
|
85
76
|
var cache = _getRequireWildcardCache(nodeInterop);
|
|
86
|
-
if (cache && cache.has(obj))
|
|
87
|
-
return cache.get(obj);
|
|
88
|
-
}
|
|
77
|
+
if (cache && cache.has(obj)) return cache.get(obj);
|
|
89
78
|
var newObj = {
|
|
90
79
|
__proto__: null
|
|
91
80
|
};
|
|
@@ -93,17 +82,12 @@ function _interop_require_wildcard(obj, nodeInterop) {
|
|
|
93
82
|
for(var key in obj){
|
|
94
83
|
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
95
84
|
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
|
|
96
|
-
if (desc && (desc.get || desc.set))
|
|
97
|
-
|
|
98
|
-
} else {
|
|
99
|
-
newObj[key] = obj[key];
|
|
100
|
-
}
|
|
85
|
+
if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);
|
|
86
|
+
else newObj[key] = obj[key];
|
|
101
87
|
}
|
|
102
88
|
}
|
|
103
89
|
newObj.default = obj;
|
|
104
|
-
if (cache)
|
|
105
|
-
cache.set(obj, newObj);
|
|
106
|
-
}
|
|
90
|
+
if (cache) cache.set(obj, newObj);
|
|
107
91
|
return newObj;
|
|
108
92
|
}
|
|
109
93
|
function _iterable_to_array_limit(arr, i) {
|
|
@@ -131,7 +115,7 @@ function _iterable_to_array_limit(arr, i) {
|
|
|
131
115
|
return _arr;
|
|
132
116
|
}
|
|
133
117
|
function _non_iterable_rest() {
|
|
134
|
-
throw new TypeError("Invalid attempt to destructure non-iterable instance
|
|
118
|
+
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
|
135
119
|
}
|
|
136
120
|
function _object_spread(target) {
|
|
137
121
|
for(var i = 1; i < arguments.length; i++){
|
|
@@ -151,14 +135,6 @@ function _object_spread(target) {
|
|
|
151
135
|
function _sliced_to_array(arr, i) {
|
|
152
136
|
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
|
|
153
137
|
}
|
|
154
|
-
function _unsupported_iterable_to_array(o, minLen) {
|
|
155
|
-
if (!o) return;
|
|
156
|
-
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
157
|
-
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
158
|
-
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
159
|
-
if (n === "Map" || n === "Set") return Array.from(n);
|
|
160
|
-
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
161
|
-
}
|
|
162
138
|
function _ts_generator(thisArg, body) {
|
|
163
139
|
var f, y, t, _ = {
|
|
164
140
|
label: 0,
|
|
@@ -258,6 +234,14 @@ function _ts_generator(thisArg, body) {
|
|
|
258
234
|
};
|
|
259
235
|
}
|
|
260
236
|
}
|
|
237
|
+
function _unsupported_iterable_to_array(o, minLen) {
|
|
238
|
+
if (!o) return;
|
|
239
|
+
if (typeof o === "string") return _array_like_to_array(o, minLen);
|
|
240
|
+
var n = Object.prototype.toString.call(o).slice(8, -1);
|
|
241
|
+
if (n === "Object" && o.constructor) n = o.constructor.name;
|
|
242
|
+
if (n === "Map" || n === "Set") return Array.from(n);
|
|
243
|
+
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
|
|
244
|
+
}
|
|
261
245
|
/**
|
|
262
246
|
* Normalize environment variables by merging with process.env and filtering undefined values.
|
|
263
247
|
*/ function normalizeEnv(env) {
|
|
@@ -330,7 +314,7 @@ function spawnProcess(opts) {
|
|
|
330
314
|
return _loggerts.logger.info("[".concat(name, "] process error: ").concat(err.message));
|
|
331
315
|
});
|
|
332
316
|
// Create stop function with graceful shutdown
|
|
333
|
-
var stop = function() {
|
|
317
|
+
var stop = function stop() {
|
|
334
318
|
var signal = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : 'SIGINT', _$opts = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
|
|
335
319
|
return _async_to_generator(function() {
|
|
336
320
|
var _opts_timeoutMs, timeoutMs, closePromise;
|
|
@@ -351,7 +335,7 @@ function spawnProcess(opts) {
|
|
|
351
335
|
closePromise = new Promise(function(resolve) {
|
|
352
336
|
var isResolved = false;
|
|
353
337
|
var wasKilled = false;
|
|
354
|
-
var resolveOnce = function(timedOut) {
|
|
338
|
+
var resolveOnce = function resolveOnce(timedOut) {
|
|
355
339
|
if (isResolved) return;
|
|
356
340
|
isResolved = true;
|
|
357
341
|
clearTimeout(timeout);
|