@introspection-ai/recipes 0.36.2 → 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ask-user-question.d.ts +82 -0
- package/dist/ask-user-question.d.ts.map +1 -0
- package/dist/ask-user-question.js +314 -0
- package/dist/ask-user-question.js.map +1 -0
- package/dist/connector-tools.d.ts.map +1 -1
- package/dist/connector-tools.js +10 -2
- package/dist/connector-tools.js.map +1 -1
- package/dist/documents/index.d.ts +7 -0
- package/dist/documents/index.d.ts.map +1 -0
- package/dist/documents/index.js +4 -0
- package/dist/documents/index.js.map +1 -0
- package/dist/documents/module.d.ts +61 -0
- package/dist/documents/module.d.ts.map +1 -0
- package/dist/documents/module.js +133 -0
- package/dist/documents/module.js.map +1 -0
- package/dist/documents/profile.d.ts +34 -0
- package/dist/documents/profile.d.ts.map +1 -0
- package/dist/documents/profile.js +94 -0
- package/dist/documents/profile.js.map +1 -0
- package/dist/documents/tools.d.ts +40 -0
- package/dist/documents/tools.d.ts.map +1 -0
- package/dist/documents/tools.js +327 -0
- package/dist/documents/tools.js.map +1 -0
- package/dist/documents/types.d.ts +144 -0
- package/dist/documents/types.d.ts.map +1 -0
- package/dist/documents/types.js +10 -0
- package/dist/documents/types.js.map +1 -0
- package/dist/extensions.d.ts +2 -0
- package/dist/extensions.d.ts.map +1 -1
- package/dist/extensions.js +3 -0
- package/dist/extensions.js.map +1 -1
- package/dist/interaction-tui.d.ts +1 -1
- package/dist/interaction-tui.d.ts.map +1 -1
- package/dist/interaction-tui.js +2 -2
- package/dist/interaction-tui.js.map +1 -1
- package/dist/mcp-chunks/{auth-command-GMMLBU24.js → auth-command-M7TQE3AL.js} +26 -23
- package/dist/mcp-chunks/call-arguments-GCXZA4HC.js +16 -0
- package/dist/mcp-chunks/{call-command-2VF6IKAZ.js → call-command-7LD7UEFK.js} +33 -33
- package/dist/mcp-chunks/{chunk-TYL2NVXI.js → chunk-2AKSS7WR.js} +2 -2
- package/dist/mcp-chunks/{chunk-LZUKBEQZ.js → chunk-2YV72LUA.js} +12 -12
- package/dist/mcp-chunks/{chunk-2JTXIMGE.js → chunk-3ETUDW7N.js} +1 -1
- package/dist/mcp-chunks/{chunk-5UK2JLTN.js → chunk-3FRLDHVD.js} +5 -5
- package/dist/mcp-chunks/{chunk-ENBJFQ6H.js → chunk-3HSC6NHZ.js} +1 -1
- package/dist/mcp-chunks/{chunk-IHOU2BEL.js → chunk-3LENTPGE.js} +2 -2
- package/dist/mcp-chunks/{chunk-ZJWZY54X.js → chunk-3P3KGT4H.js} +2 -2
- package/dist/mcp-chunks/{chunk-IMXPLUKE.js → chunk-3SXP4S2A.js} +2 -2
- package/dist/mcp-chunks/{chunk-22WCLO4D.js → chunk-5Z6WSV5D.js} +5 -5
- package/dist/mcp-chunks/{chunk-QNZGFUKC.js → chunk-63L6SHK3.js} +2 -2
- package/dist/mcp-chunks/{chunk-OI3RTQXY.js → chunk-66VSGFXA.js} +1 -1
- package/dist/mcp-chunks/{chunk-DUBQHYW4.js → chunk-6O42UGLI.js} +9 -9
- package/dist/mcp-chunks/{chunk-R4OYHQ4V.js → chunk-6P3KAQ5N.js} +1 -1
- package/dist/mcp-chunks/{chunk-5OO6WVPL.js → chunk-7U5NSQ5T.js} +1 -1
- package/dist/mcp-chunks/{chunk-O2C3HXGS.js → chunk-B6S43WID.js} +1 -1
- package/dist/mcp-chunks/{chunk-VWPKJFK4.js → chunk-BHXCAVFP.js} +1 -1
- package/dist/mcp-chunks/{chunk-WXNGATQ7.js → chunk-BUOGKTKK.js} +2 -1
- package/dist/mcp-chunks/{chunk-4U4BUXQD.js → chunk-CXST5CVH.js} +33 -17
- package/dist/mcp-chunks/{chunk-YWFQPA4D.js → chunk-DU4SDPEV.js} +2 -2
- package/dist/mcp-chunks/{chunk-ZI5XYM4C.js → chunk-E76ZUBOJ.js} +4 -4
- package/dist/mcp-chunks/{chunk-D2SZ7KRY.js → chunk-ELHS763C.js} +1 -1
- package/dist/mcp-chunks/chunk-EQCSXVQ7.js +10650 -0
- package/dist/mcp-chunks/{chunk-RHXZKYM7.js → chunk-F2X4Y2TQ.js} +1 -1
- package/dist/mcp-chunks/{chunk-6XC5JJWD.js → chunk-GTETFUPQ.js} +28 -25
- package/dist/mcp-chunks/{chunk-UQUM7ICD.js → chunk-GZ53GNFP.js} +10 -10
- package/dist/mcp-chunks/{chunk-LUVLTUKR.js → chunk-H5PBSJP3.js} +1 -1
- package/dist/mcp-chunks/{chunk-FLUF2FRN.js → chunk-HNQSUT44.js} +3 -3
- package/dist/mcp-chunks/{chunk-CN5KSNWG.js → chunk-I6UFV7RW.js} +1 -1
- package/dist/mcp-chunks/{chunk-OSTHIELS.js → chunk-IRARVOUM.js} +1 -1
- package/dist/mcp-chunks/{webapi-NNCZGUMZ.js → chunk-IRSL7JRH.js} +255 -249
- package/dist/mcp-chunks/{chunk-ZXIF7MKN.js → chunk-IWCVZ46B.js} +2 -2
- package/dist/mcp-chunks/{chunk-RZZO3ZD4.js → chunk-JEHI2YU4.js} +3 -3
- package/dist/mcp-chunks/{chunk-ANNJGB6F.js → chunk-JTPTAO4M.js} +13 -13
- package/dist/mcp-chunks/{chunk-U5QZHPCC.js → chunk-KJ5FPQF6.js} +1 -1
- package/dist/mcp-chunks/{chunk-7IVXKYTI.js → chunk-L2MSWQDL.js} +1 -1
- package/dist/mcp-chunks/{chunk-DBNBEWRX.js → chunk-MEQXX43K.js} +1 -1
- package/dist/mcp-chunks/{chunk-3AAF3FSI.js → chunk-MHUMLEBO.js} +1 -1
- package/dist/mcp-chunks/{chunk-HFHIY5TO.js → chunk-N2U2FODH.js} +4 -4
- package/dist/mcp-chunks/{chunk-YFCNRWLV.js → chunk-N6YUOYDS.js} +2 -2
- package/dist/mcp-chunks/{chunk-C4TJGC4F.js → chunk-O3RTM5HD.js} +1 -1
- package/dist/mcp-chunks/{chunk-35LLRCRA.js → chunk-O7SIXJM6.js} +1308 -912
- package/dist/mcp-chunks/{chunk-QDFL757K.js → chunk-PSE442BC.js} +91 -77
- package/dist/mcp-chunks/{chunk-YPSODIQX.js → chunk-QNXOIF5U.js} +15 -14
- package/dist/mcp-chunks/{chunk-RKQC2EE6.js → chunk-RUF27IUF.js} +2 -2
- package/dist/mcp-chunks/{chunk-SS7V7GVT.js → chunk-S2F7DDP5.js} +4 -4
- package/dist/mcp-chunks/{chunk-D65GOMYV.js → chunk-TC2JPBFB.js} +2 -2
- package/dist/mcp-chunks/{chunk-7BVYBZ4J.js → chunk-THRMUZZD.js} +39 -14
- package/dist/mcp-chunks/{chunk-P5YLK5G2.js → chunk-UFV6SVQG.js} +11 -11
- package/dist/mcp-chunks/{chunk-LISNXOIQ.js → chunk-US63Y6XE.js} +1 -1
- package/dist/mcp-chunks/{chunk-HI6VG5LR.js → chunk-UVRJ3AAD.js} +2 -2
- package/dist/mcp-chunks/{chunk-6TIU2CDB.js → chunk-V42T3QNK.js} +456 -64
- package/dist/mcp-chunks/{chunk-347GOMV4.js → chunk-WDWSA7RL.js} +4 -4
- package/dist/mcp-chunks/{chunk-4PN2J74H.js → chunk-WQL7FJQ3.js} +4 -4
- package/dist/mcp-chunks/{chunk-LRGMFF5S.js → chunk-ZEA3Y5ZD.js} +7 -7
- package/dist/mcp-chunks/{cli-4OQD3H4N.js → cli-IYD7Y7MO.js} +67 -67
- package/dist/mcp-chunks/client-5MNBV3Z7.js +32 -0
- package/dist/mcp-chunks/{config-command-72TCIWPV.js → config-command-6DXILFNO.js} +129 -34
- package/dist/mcp-chunks/daemon-command-V3B3EMXD.js +32 -0
- package/dist/mcp-chunks/{dist-74UCKZK5.js → dist-Q7WSCBBK.js} +74 -55
- package/dist/mcp-chunks/{emit-ts-command-KD4ON2SE.js → emit-ts-command-NDCDFDRM.js} +17 -17
- package/dist/mcp-chunks/{generate-cli-runner-HWGI6HPL.js → generate-cli-runner-PW5WJ7KI.js} +136 -92
- package/dist/mcp-chunks/generated-daemon-runtime-3C4NWGAU.js +32 -0
- package/dist/mcp-chunks/{inspect-cli-command-FT5JSB7V.js → inspect-cli-command-4MGF5CPP.js} +9 -9
- package/dist/mcp-chunks/{launch-AHLKP2VM.js → launch-UG7IH27P.js} +1 -1
- package/dist/mcp-chunks/{lifecycle-BJDITFWN.js → lifecycle-QBYGUHQ3.js} +1 -1
- package/dist/mcp-chunks/{list-command-YKF7RN6Y.js → list-command-SDITI3ZM.js} +36 -35
- package/dist/mcp-chunks/{output-utils-LYB5IJRD.js → output-utils-YTMZTA7J.js} +3 -3
- package/dist/mcp-chunks/{prompt-CH6TK0bC-B3USYOND.js → prompt-DkftHXS7-N7UENQ4C.js} +1 -1
- package/dist/mcp-chunks/{record-command-MJW3Z5E5.js → record-command-JGTMATYI.js} +5 -5
- package/dist/mcp-chunks/{replay-command-5ZHBUOLE.js → replay-command-S2VAC4RW.js} +6 -6
- package/dist/mcp-chunks/{resource-command-L4I24AX5.js → resource-command-SRFQQROJ.js} +9 -9
- package/dist/mcp-chunks/{result-utils-5WRI66KV.js → result-utils-JASGNHXK.js} +3 -3
- package/dist/mcp-chunks/runtime-RMI3XCYJ.js +39 -0
- package/dist/mcp-chunks/{runtime-wrapper-WFMNIHD5.js → runtime-wrapper-7HYO3NM5.js} +3 -3
- package/dist/mcp-chunks/{serve-command-KNCSJUXS.js → serve-command-UF5SVREV.js} +1111 -697
- package/dist/mcp-chunks/{timeouts-2ZHGSB3R.js → timeouts-BJWDJEMH.js} +3 -3
- package/dist/mcp-chunks/{vault-command-7EDL45AA.js → vault-command-EYOIFWEY.js} +5 -4
- package/dist/mcp-chunks/webapi-WMMA3OEC.js +82 -0
- package/dist/mcp-daemon.js +28 -27
- package/dist/mcp-run-worker.js +28 -27
- package/dist/pi-extension.d.ts.map +1 -1
- package/dist/pi-extension.js +6 -0
- package/dist/pi-extension.js.map +1 -1
- package/dist/recipe/package.d.ts +15 -0
- package/dist/recipe/package.d.ts.map +1 -1
- package/dist/recipe/package.js +96 -2
- package/dist/recipe/package.js.map +1 -1
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +6 -0
- package/dist/session.js.map +1 -1
- package/docs/documents.md +344 -0
- package/docs/index.md +1 -0
- package/docs/interactions.md +76 -8
- package/docs/mcp-configuration.md +10 -5
- package/docs/recipe-format.md +69 -1
- package/documents/SKILL.md +63 -0
- package/package.json +16 -11
- package/dist/mcp-chunks/call-arguments-WSURHOLV.js +0 -16
- package/dist/mcp-chunks/chunk-BIVX2WFX.js +0 -3349
- package/dist/mcp-chunks/client-LXKCCVMT.js +0 -31
- package/dist/mcp-chunks/daemon-command-QHS3ACBM.js +0 -31
- package/dist/mcp-chunks/generated-daemon-runtime-7ORS5KBR.js +0 -31
- package/dist/mcp-chunks/runtime-IKWDQLZF.js +0 -38
|
@@ -1,3349 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
-
import {
|
|
3
|
-
createCallResult,
|
|
4
|
-
describeConnectionIssue
|
|
5
|
-
} from "./chunk-IMXPLUKE.js";
|
|
6
|
-
import {
|
|
7
|
-
createRuntime
|
|
8
|
-
} from "./chunk-QDFL757K.js";
|
|
9
|
-
|
|
10
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/context.js
|
|
11
|
-
function createContextKey(description) {
|
|
12
|
-
return Symbol.for(description);
|
|
13
|
-
}
|
|
14
|
-
var BaseContext = class _BaseContext {
|
|
15
|
-
/**
|
|
16
|
-
* Construct a new context which inherits values from an optional parent context.
|
|
17
|
-
*
|
|
18
|
-
* @param parentContext a context from which to inherit values
|
|
19
|
-
*/
|
|
20
|
-
constructor(parentContext) {
|
|
21
|
-
const self2 = this;
|
|
22
|
-
self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
|
|
23
|
-
self2.getValue = (key) => self2._currentContext.get(key);
|
|
24
|
-
self2.setValue = (key, value) => {
|
|
25
|
-
const context2 = new _BaseContext(self2._currentContext);
|
|
26
|
-
context2._currentContext.set(key, value);
|
|
27
|
-
return context2;
|
|
28
|
-
};
|
|
29
|
-
self2.deleteValue = (key) => {
|
|
30
|
-
const context2 = new _BaseContext(self2._currentContext);
|
|
31
|
-
context2._currentContext.delete(key);
|
|
32
|
-
return context2;
|
|
33
|
-
};
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
var ROOT_CONTEXT = new BaseContext();
|
|
37
|
-
|
|
38
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
|
|
39
|
-
var NoopContextManager = class {
|
|
40
|
-
active() {
|
|
41
|
-
return ROOT_CONTEXT;
|
|
42
|
-
}
|
|
43
|
-
with(_context, fn, thisArg, ...args) {
|
|
44
|
-
return fn.call(thisArg, ...args);
|
|
45
|
-
}
|
|
46
|
-
bind(_context, target) {
|
|
47
|
-
return target;
|
|
48
|
-
}
|
|
49
|
-
enable() {
|
|
50
|
-
return this;
|
|
51
|
-
}
|
|
52
|
-
disable() {
|
|
53
|
-
return this;
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/version.js
|
|
58
|
-
var VERSION = "1.9.1";
|
|
59
|
-
|
|
60
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/semver.js
|
|
61
|
-
var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
|
|
62
|
-
function _makeCompatibilityCheck(ownVersion) {
|
|
63
|
-
const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
|
|
64
|
-
const rejectedVersions = /* @__PURE__ */ new Set();
|
|
65
|
-
const myVersionMatch = ownVersion.match(re);
|
|
66
|
-
if (!myVersionMatch) {
|
|
67
|
-
return () => false;
|
|
68
|
-
}
|
|
69
|
-
const ownVersionParsed = {
|
|
70
|
-
major: +myVersionMatch[1],
|
|
71
|
-
minor: +myVersionMatch[2],
|
|
72
|
-
patch: +myVersionMatch[3],
|
|
73
|
-
prerelease: myVersionMatch[4]
|
|
74
|
-
};
|
|
75
|
-
if (ownVersionParsed.prerelease != null) {
|
|
76
|
-
return function isExactmatch(globalVersion) {
|
|
77
|
-
return globalVersion === ownVersion;
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
function _reject(v) {
|
|
81
|
-
rejectedVersions.add(v);
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
|
-
function _accept(v) {
|
|
85
|
-
acceptedVersions.add(v);
|
|
86
|
-
return true;
|
|
87
|
-
}
|
|
88
|
-
return function isCompatible2(globalVersion) {
|
|
89
|
-
if (acceptedVersions.has(globalVersion)) {
|
|
90
|
-
return true;
|
|
91
|
-
}
|
|
92
|
-
if (rejectedVersions.has(globalVersion)) {
|
|
93
|
-
return false;
|
|
94
|
-
}
|
|
95
|
-
const globalVersionMatch = globalVersion.match(re);
|
|
96
|
-
if (!globalVersionMatch) {
|
|
97
|
-
return _reject(globalVersion);
|
|
98
|
-
}
|
|
99
|
-
const globalVersionParsed = {
|
|
100
|
-
major: +globalVersionMatch[1],
|
|
101
|
-
minor: +globalVersionMatch[2],
|
|
102
|
-
patch: +globalVersionMatch[3],
|
|
103
|
-
prerelease: globalVersionMatch[4]
|
|
104
|
-
};
|
|
105
|
-
if (globalVersionParsed.prerelease != null) {
|
|
106
|
-
return _reject(globalVersion);
|
|
107
|
-
}
|
|
108
|
-
if (ownVersionParsed.major !== globalVersionParsed.major) {
|
|
109
|
-
return _reject(globalVersion);
|
|
110
|
-
}
|
|
111
|
-
if (ownVersionParsed.major === 0) {
|
|
112
|
-
if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
|
|
113
|
-
return _accept(globalVersion);
|
|
114
|
-
}
|
|
115
|
-
return _reject(globalVersion);
|
|
116
|
-
}
|
|
117
|
-
if (ownVersionParsed.minor <= globalVersionParsed.minor) {
|
|
118
|
-
return _accept(globalVersion);
|
|
119
|
-
}
|
|
120
|
-
return _reject(globalVersion);
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
var isCompatible = _makeCompatibilityCheck(VERSION);
|
|
124
|
-
|
|
125
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
|
|
126
|
-
var major = VERSION.split(".")[0];
|
|
127
|
-
var GLOBAL_OPENTELEMETRY_API_KEY = /* @__PURE__ */ Symbol.for(`opentelemetry.js.api.${major}`);
|
|
128
|
-
var _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
|
|
129
|
-
function registerGlobal(type, instance, diag, allowOverride = false) {
|
|
130
|
-
var _a;
|
|
131
|
-
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
|
|
132
|
-
version: VERSION
|
|
133
|
-
};
|
|
134
|
-
if (!allowOverride && api[type]) {
|
|
135
|
-
const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
|
|
136
|
-
diag.error(err.stack || err.message);
|
|
137
|
-
return false;
|
|
138
|
-
}
|
|
139
|
-
if (api.version !== VERSION) {
|
|
140
|
-
const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`);
|
|
141
|
-
diag.error(err.stack || err.message);
|
|
142
|
-
return false;
|
|
143
|
-
}
|
|
144
|
-
api[type] = instance;
|
|
145
|
-
diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`);
|
|
146
|
-
return true;
|
|
147
|
-
}
|
|
148
|
-
function getGlobal(type) {
|
|
149
|
-
var _a, _b;
|
|
150
|
-
const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
|
|
151
|
-
if (!globalVersion || !isCompatible(globalVersion)) {
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
|
|
155
|
-
}
|
|
156
|
-
function unregisterGlobal(type, diag) {
|
|
157
|
-
diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`);
|
|
158
|
-
const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
|
|
159
|
-
if (api) {
|
|
160
|
-
delete api[type];
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
|
|
165
|
-
var DiagComponentLogger = class {
|
|
166
|
-
constructor(props) {
|
|
167
|
-
this._namespace = props.namespace || "DiagComponentLogger";
|
|
168
|
-
}
|
|
169
|
-
debug(...args) {
|
|
170
|
-
return logProxy("debug", this._namespace, args);
|
|
171
|
-
}
|
|
172
|
-
error(...args) {
|
|
173
|
-
return logProxy("error", this._namespace, args);
|
|
174
|
-
}
|
|
175
|
-
info(...args) {
|
|
176
|
-
return logProxy("info", this._namespace, args);
|
|
177
|
-
}
|
|
178
|
-
warn(...args) {
|
|
179
|
-
return logProxy("warn", this._namespace, args);
|
|
180
|
-
}
|
|
181
|
-
verbose(...args) {
|
|
182
|
-
return logProxy("verbose", this._namespace, args);
|
|
183
|
-
}
|
|
184
|
-
};
|
|
185
|
-
function logProxy(funcName, namespace, args) {
|
|
186
|
-
const logger = getGlobal("diag");
|
|
187
|
-
if (!logger) {
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
return logger[funcName](namespace, ...args);
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/types.js
|
|
194
|
-
var DiagLogLevel;
|
|
195
|
-
(function(DiagLogLevel2) {
|
|
196
|
-
DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
|
|
197
|
-
DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
|
|
198
|
-
DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
|
|
199
|
-
DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
|
|
200
|
-
DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
|
|
201
|
-
DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
|
|
202
|
-
DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
|
|
203
|
-
})(DiagLogLevel || (DiagLogLevel = {}));
|
|
204
|
-
|
|
205
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
|
|
206
|
-
function createLogLevelDiagLogger(maxLevel, logger) {
|
|
207
|
-
if (maxLevel < DiagLogLevel.NONE) {
|
|
208
|
-
maxLevel = DiagLogLevel.NONE;
|
|
209
|
-
} else if (maxLevel > DiagLogLevel.ALL) {
|
|
210
|
-
maxLevel = DiagLogLevel.ALL;
|
|
211
|
-
}
|
|
212
|
-
logger = logger || {};
|
|
213
|
-
function _filterFunc(funcName, theLevel) {
|
|
214
|
-
const theFunc = logger[funcName];
|
|
215
|
-
if (typeof theFunc === "function" && maxLevel >= theLevel) {
|
|
216
|
-
return theFunc.bind(logger);
|
|
217
|
-
}
|
|
218
|
-
return function() {
|
|
219
|
-
};
|
|
220
|
-
}
|
|
221
|
-
return {
|
|
222
|
-
error: _filterFunc("error", DiagLogLevel.ERROR),
|
|
223
|
-
warn: _filterFunc("warn", DiagLogLevel.WARN),
|
|
224
|
-
info: _filterFunc("info", DiagLogLevel.INFO),
|
|
225
|
-
debug: _filterFunc("debug", DiagLogLevel.DEBUG),
|
|
226
|
-
verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
|
|
227
|
-
};
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/diag.js
|
|
231
|
-
var API_NAME = "diag";
|
|
232
|
-
var DiagAPI = class _DiagAPI {
|
|
233
|
-
/** Get the singleton instance of the DiagAPI API */
|
|
234
|
-
static instance() {
|
|
235
|
-
if (!this._instance) {
|
|
236
|
-
this._instance = new _DiagAPI();
|
|
237
|
-
}
|
|
238
|
-
return this._instance;
|
|
239
|
-
}
|
|
240
|
-
/**
|
|
241
|
-
* Private internal constructor
|
|
242
|
-
* @private
|
|
243
|
-
*/
|
|
244
|
-
constructor() {
|
|
245
|
-
function _logProxy(funcName) {
|
|
246
|
-
return function(...args) {
|
|
247
|
-
const logger = getGlobal("diag");
|
|
248
|
-
if (!logger)
|
|
249
|
-
return;
|
|
250
|
-
return logger[funcName](...args);
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
const self2 = this;
|
|
254
|
-
const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => {
|
|
255
|
-
var _a, _b, _c;
|
|
256
|
-
if (logger === self2) {
|
|
257
|
-
const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
|
|
258
|
-
self2.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
|
|
259
|
-
return false;
|
|
260
|
-
}
|
|
261
|
-
if (typeof optionsOrLogLevel === "number") {
|
|
262
|
-
optionsOrLogLevel = {
|
|
263
|
-
logLevel: optionsOrLogLevel
|
|
264
|
-
};
|
|
265
|
-
}
|
|
266
|
-
const oldLogger = getGlobal("diag");
|
|
267
|
-
const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
|
|
268
|
-
if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
|
|
269
|
-
const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
|
|
270
|
-
oldLogger.warn(`Current logger will be overwritten from ${stack}`);
|
|
271
|
-
newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
|
|
272
|
-
}
|
|
273
|
-
return registerGlobal("diag", newLogger, self2, true);
|
|
274
|
-
};
|
|
275
|
-
self2.setLogger = setLogger;
|
|
276
|
-
self2.disable = () => {
|
|
277
|
-
unregisterGlobal(API_NAME, self2);
|
|
278
|
-
};
|
|
279
|
-
self2.createComponentLogger = (options) => {
|
|
280
|
-
return new DiagComponentLogger(options);
|
|
281
|
-
};
|
|
282
|
-
self2.verbose = _logProxy("verbose");
|
|
283
|
-
self2.debug = _logProxy("debug");
|
|
284
|
-
self2.info = _logProxy("info");
|
|
285
|
-
self2.warn = _logProxy("warn");
|
|
286
|
-
self2.error = _logProxy("error");
|
|
287
|
-
}
|
|
288
|
-
};
|
|
289
|
-
|
|
290
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/context.js
|
|
291
|
-
var API_NAME2 = "context";
|
|
292
|
-
var NOOP_CONTEXT_MANAGER = new NoopContextManager();
|
|
293
|
-
var ContextAPI = class _ContextAPI {
|
|
294
|
-
/** Empty private constructor prevents end users from constructing a new instance of the API */
|
|
295
|
-
constructor() {
|
|
296
|
-
}
|
|
297
|
-
/** Get the singleton instance of the Context API */
|
|
298
|
-
static getInstance() {
|
|
299
|
-
if (!this._instance) {
|
|
300
|
-
this._instance = new _ContextAPI();
|
|
301
|
-
}
|
|
302
|
-
return this._instance;
|
|
303
|
-
}
|
|
304
|
-
/**
|
|
305
|
-
* Set the current context manager.
|
|
306
|
-
*
|
|
307
|
-
* @returns true if the context manager was successfully registered, else false
|
|
308
|
-
*/
|
|
309
|
-
setGlobalContextManager(contextManager) {
|
|
310
|
-
return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
|
|
311
|
-
}
|
|
312
|
-
/**
|
|
313
|
-
* Get the currently active context
|
|
314
|
-
*/
|
|
315
|
-
active() {
|
|
316
|
-
return this._getContextManager().active();
|
|
317
|
-
}
|
|
318
|
-
/**
|
|
319
|
-
* Execute a function with an active context
|
|
320
|
-
*
|
|
321
|
-
* @param context context to be active during function execution
|
|
322
|
-
* @param fn function to execute in a context
|
|
323
|
-
* @param thisArg optional receiver to be used for calling fn
|
|
324
|
-
* @param args optional arguments forwarded to fn
|
|
325
|
-
*/
|
|
326
|
-
with(context2, fn, thisArg, ...args) {
|
|
327
|
-
return this._getContextManager().with(context2, fn, thisArg, ...args);
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Bind a context to a target function or event emitter
|
|
331
|
-
*
|
|
332
|
-
* @param context context to bind to the event emitter or function. Defaults to the currently active context
|
|
333
|
-
* @param target function or event emitter to bind
|
|
334
|
-
*/
|
|
335
|
-
bind(context2, target) {
|
|
336
|
-
return this._getContextManager().bind(context2, target);
|
|
337
|
-
}
|
|
338
|
-
_getContextManager() {
|
|
339
|
-
return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
|
|
340
|
-
}
|
|
341
|
-
/** Disable and remove the global context manager */
|
|
342
|
-
disable() {
|
|
343
|
-
this._getContextManager().disable();
|
|
344
|
-
unregisterGlobal(API_NAME2, DiagAPI.instance());
|
|
345
|
-
}
|
|
346
|
-
};
|
|
347
|
-
|
|
348
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/context-api.js
|
|
349
|
-
var context = ContextAPI.getInstance();
|
|
350
|
-
|
|
351
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js
|
|
352
|
-
var TraceFlags;
|
|
353
|
-
(function(TraceFlags2) {
|
|
354
|
-
TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
|
|
355
|
-
TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
|
|
356
|
-
})(TraceFlags || (TraceFlags = {}));
|
|
357
|
-
|
|
358
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js
|
|
359
|
-
var INVALID_SPANID = "0000000000000000";
|
|
360
|
-
var INVALID_TRACEID = "00000000000000000000000000000000";
|
|
361
|
-
var INVALID_SPAN_CONTEXT = {
|
|
362
|
-
traceId: INVALID_TRACEID,
|
|
363
|
-
spanId: INVALID_SPANID,
|
|
364
|
-
traceFlags: TraceFlags.NONE
|
|
365
|
-
};
|
|
366
|
-
|
|
367
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js
|
|
368
|
-
var NonRecordingSpan = class {
|
|
369
|
-
constructor(spanContext = INVALID_SPAN_CONTEXT) {
|
|
370
|
-
this._spanContext = spanContext;
|
|
371
|
-
}
|
|
372
|
-
// Returns a SpanContext.
|
|
373
|
-
spanContext() {
|
|
374
|
-
return this._spanContext;
|
|
375
|
-
}
|
|
376
|
-
// By default does nothing
|
|
377
|
-
setAttribute(_key, _value) {
|
|
378
|
-
return this;
|
|
379
|
-
}
|
|
380
|
-
// By default does nothing
|
|
381
|
-
setAttributes(_attributes) {
|
|
382
|
-
return this;
|
|
383
|
-
}
|
|
384
|
-
// By default does nothing
|
|
385
|
-
addEvent(_name, _attributes) {
|
|
386
|
-
return this;
|
|
387
|
-
}
|
|
388
|
-
addLink(_link) {
|
|
389
|
-
return this;
|
|
390
|
-
}
|
|
391
|
-
addLinks(_links) {
|
|
392
|
-
return this;
|
|
393
|
-
}
|
|
394
|
-
// By default does nothing
|
|
395
|
-
setStatus(_status) {
|
|
396
|
-
return this;
|
|
397
|
-
}
|
|
398
|
-
// By default does nothing
|
|
399
|
-
updateName(_name) {
|
|
400
|
-
return this;
|
|
401
|
-
}
|
|
402
|
-
// By default does nothing
|
|
403
|
-
end(_endTime) {
|
|
404
|
-
}
|
|
405
|
-
// isRecording always returns false for NonRecordingSpan.
|
|
406
|
-
isRecording() {
|
|
407
|
-
return false;
|
|
408
|
-
}
|
|
409
|
-
// By default does nothing
|
|
410
|
-
recordException(_exception, _time) {
|
|
411
|
-
}
|
|
412
|
-
};
|
|
413
|
-
|
|
414
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js
|
|
415
|
-
var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
|
|
416
|
-
function getSpan(context2) {
|
|
417
|
-
return context2.getValue(SPAN_KEY) || void 0;
|
|
418
|
-
}
|
|
419
|
-
function getActiveSpan() {
|
|
420
|
-
return getSpan(ContextAPI.getInstance().active());
|
|
421
|
-
}
|
|
422
|
-
function setSpan(context2, span) {
|
|
423
|
-
return context2.setValue(SPAN_KEY, span);
|
|
424
|
-
}
|
|
425
|
-
function deleteSpan(context2) {
|
|
426
|
-
return context2.deleteValue(SPAN_KEY);
|
|
427
|
-
}
|
|
428
|
-
function setSpanContext(context2, spanContext) {
|
|
429
|
-
return setSpan(context2, new NonRecordingSpan(spanContext));
|
|
430
|
-
}
|
|
431
|
-
function getSpanContext(context2) {
|
|
432
|
-
var _a;
|
|
433
|
-
return (_a = getSpan(context2)) === null || _a === void 0 ? void 0 : _a.spanContext();
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js
|
|
437
|
-
var isHex = new Uint8Array([
|
|
438
|
-
0,
|
|
439
|
-
0,
|
|
440
|
-
0,
|
|
441
|
-
0,
|
|
442
|
-
0,
|
|
443
|
-
0,
|
|
444
|
-
0,
|
|
445
|
-
0,
|
|
446
|
-
0,
|
|
447
|
-
0,
|
|
448
|
-
0,
|
|
449
|
-
0,
|
|
450
|
-
0,
|
|
451
|
-
0,
|
|
452
|
-
0,
|
|
453
|
-
0,
|
|
454
|
-
0,
|
|
455
|
-
0,
|
|
456
|
-
0,
|
|
457
|
-
0,
|
|
458
|
-
0,
|
|
459
|
-
0,
|
|
460
|
-
0,
|
|
461
|
-
0,
|
|
462
|
-
0,
|
|
463
|
-
0,
|
|
464
|
-
0,
|
|
465
|
-
0,
|
|
466
|
-
0,
|
|
467
|
-
0,
|
|
468
|
-
0,
|
|
469
|
-
0,
|
|
470
|
-
0,
|
|
471
|
-
0,
|
|
472
|
-
0,
|
|
473
|
-
0,
|
|
474
|
-
0,
|
|
475
|
-
0,
|
|
476
|
-
0,
|
|
477
|
-
0,
|
|
478
|
-
0,
|
|
479
|
-
0,
|
|
480
|
-
0,
|
|
481
|
-
0,
|
|
482
|
-
0,
|
|
483
|
-
0,
|
|
484
|
-
0,
|
|
485
|
-
0,
|
|
486
|
-
1,
|
|
487
|
-
1,
|
|
488
|
-
1,
|
|
489
|
-
1,
|
|
490
|
-
1,
|
|
491
|
-
1,
|
|
492
|
-
1,
|
|
493
|
-
1,
|
|
494
|
-
1,
|
|
495
|
-
1,
|
|
496
|
-
0,
|
|
497
|
-
0,
|
|
498
|
-
0,
|
|
499
|
-
0,
|
|
500
|
-
0,
|
|
501
|
-
0,
|
|
502
|
-
0,
|
|
503
|
-
1,
|
|
504
|
-
1,
|
|
505
|
-
1,
|
|
506
|
-
1,
|
|
507
|
-
1,
|
|
508
|
-
1,
|
|
509
|
-
0,
|
|
510
|
-
0,
|
|
511
|
-
0,
|
|
512
|
-
0,
|
|
513
|
-
0,
|
|
514
|
-
0,
|
|
515
|
-
0,
|
|
516
|
-
0,
|
|
517
|
-
0,
|
|
518
|
-
0,
|
|
519
|
-
0,
|
|
520
|
-
0,
|
|
521
|
-
0,
|
|
522
|
-
0,
|
|
523
|
-
0,
|
|
524
|
-
0,
|
|
525
|
-
0,
|
|
526
|
-
0,
|
|
527
|
-
0,
|
|
528
|
-
0,
|
|
529
|
-
0,
|
|
530
|
-
0,
|
|
531
|
-
0,
|
|
532
|
-
0,
|
|
533
|
-
0,
|
|
534
|
-
0,
|
|
535
|
-
1,
|
|
536
|
-
1,
|
|
537
|
-
1,
|
|
538
|
-
1,
|
|
539
|
-
1,
|
|
540
|
-
1
|
|
541
|
-
]);
|
|
542
|
-
function isValidHex(id, length) {
|
|
543
|
-
if (typeof id !== "string" || id.length !== length)
|
|
544
|
-
return false;
|
|
545
|
-
let r = 0;
|
|
546
|
-
for (let i = 0; i < id.length; i += 4) {
|
|
547
|
-
r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0);
|
|
548
|
-
}
|
|
549
|
-
return r === length;
|
|
550
|
-
}
|
|
551
|
-
function isValidTraceId(traceId) {
|
|
552
|
-
return isValidHex(traceId, 32) && traceId !== INVALID_TRACEID;
|
|
553
|
-
}
|
|
554
|
-
function isValidSpanId(spanId) {
|
|
555
|
-
return isValidHex(spanId, 16) && spanId !== INVALID_SPANID;
|
|
556
|
-
}
|
|
557
|
-
function isSpanContextValid(spanContext) {
|
|
558
|
-
return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
|
|
559
|
-
}
|
|
560
|
-
function wrapSpanContext(spanContext) {
|
|
561
|
-
return new NonRecordingSpan(spanContext);
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js
|
|
565
|
-
var contextApi = ContextAPI.getInstance();
|
|
566
|
-
var NoopTracer = class {
|
|
567
|
-
// startSpan starts a noop span.
|
|
568
|
-
startSpan(name, options, context2 = contextApi.active()) {
|
|
569
|
-
const root = Boolean(options === null || options === void 0 ? void 0 : options.root);
|
|
570
|
-
if (root) {
|
|
571
|
-
return new NonRecordingSpan();
|
|
572
|
-
}
|
|
573
|
-
const parentFromContext = context2 && getSpanContext(context2);
|
|
574
|
-
if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
|
|
575
|
-
return new NonRecordingSpan(parentFromContext);
|
|
576
|
-
} else {
|
|
577
|
-
return new NonRecordingSpan();
|
|
578
|
-
}
|
|
579
|
-
}
|
|
580
|
-
startActiveSpan(name, arg2, arg3, arg4) {
|
|
581
|
-
let opts;
|
|
582
|
-
let ctx;
|
|
583
|
-
let fn;
|
|
584
|
-
if (arguments.length < 2) {
|
|
585
|
-
return;
|
|
586
|
-
} else if (arguments.length === 2) {
|
|
587
|
-
fn = arg2;
|
|
588
|
-
} else if (arguments.length === 3) {
|
|
589
|
-
opts = arg2;
|
|
590
|
-
fn = arg3;
|
|
591
|
-
} else {
|
|
592
|
-
opts = arg2;
|
|
593
|
-
ctx = arg3;
|
|
594
|
-
fn = arg4;
|
|
595
|
-
}
|
|
596
|
-
const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
|
|
597
|
-
const span = this.startSpan(name, opts, parentContext);
|
|
598
|
-
const contextWithSpanSet = setSpan(parentContext, span);
|
|
599
|
-
return contextApi.with(contextWithSpanSet, fn, void 0, span);
|
|
600
|
-
}
|
|
601
|
-
};
|
|
602
|
-
function isSpanContext(spanContext) {
|
|
603
|
-
return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number";
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js
|
|
607
|
-
var NOOP_TRACER = new NoopTracer();
|
|
608
|
-
var ProxyTracer = class {
|
|
609
|
-
constructor(provider, name, version, options) {
|
|
610
|
-
this._provider = provider;
|
|
611
|
-
this.name = name;
|
|
612
|
-
this.version = version;
|
|
613
|
-
this.options = options;
|
|
614
|
-
}
|
|
615
|
-
startSpan(name, options, context2) {
|
|
616
|
-
return this._getTracer().startSpan(name, options, context2);
|
|
617
|
-
}
|
|
618
|
-
startActiveSpan(_name, _options, _context, _fn) {
|
|
619
|
-
const tracer = this._getTracer();
|
|
620
|
-
return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
|
|
621
|
-
}
|
|
622
|
-
/**
|
|
623
|
-
* Try to get a tracer from the proxy tracer provider.
|
|
624
|
-
* If the proxy tracer provider has no delegate, return a noop tracer.
|
|
625
|
-
*/
|
|
626
|
-
_getTracer() {
|
|
627
|
-
if (this._delegate) {
|
|
628
|
-
return this._delegate;
|
|
629
|
-
}
|
|
630
|
-
const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);
|
|
631
|
-
if (!tracer) {
|
|
632
|
-
return NOOP_TRACER;
|
|
633
|
-
}
|
|
634
|
-
this._delegate = tracer;
|
|
635
|
-
return this._delegate;
|
|
636
|
-
}
|
|
637
|
-
};
|
|
638
|
-
|
|
639
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js
|
|
640
|
-
var NoopTracerProvider = class {
|
|
641
|
-
getTracer(_name, _version, _options) {
|
|
642
|
-
return new NoopTracer();
|
|
643
|
-
}
|
|
644
|
-
};
|
|
645
|
-
|
|
646
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js
|
|
647
|
-
var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
|
|
648
|
-
var ProxyTracerProvider = class {
|
|
649
|
-
/**
|
|
650
|
-
* Get a {@link ProxyTracer}
|
|
651
|
-
*/
|
|
652
|
-
getTracer(name, version, options) {
|
|
653
|
-
var _a;
|
|
654
|
-
return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
|
|
655
|
-
}
|
|
656
|
-
getDelegate() {
|
|
657
|
-
var _a;
|
|
658
|
-
return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
|
|
659
|
-
}
|
|
660
|
-
/**
|
|
661
|
-
* Set the delegate tracer provider
|
|
662
|
-
*/
|
|
663
|
-
setDelegate(delegate) {
|
|
664
|
-
this._delegate = delegate;
|
|
665
|
-
}
|
|
666
|
-
getDelegateTracer(name, version, options) {
|
|
667
|
-
var _a;
|
|
668
|
-
return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
|
|
669
|
-
}
|
|
670
|
-
};
|
|
671
|
-
|
|
672
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js
|
|
673
|
-
var VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]";
|
|
674
|
-
var VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`;
|
|
675
|
-
var VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`;
|
|
676
|
-
var VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`);
|
|
677
|
-
var VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/;
|
|
678
|
-
var INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/;
|
|
679
|
-
function validateKey(key) {
|
|
680
|
-
return VALID_KEY_REGEX.test(key);
|
|
681
|
-
}
|
|
682
|
-
function validateValue(value) {
|
|
683
|
-
return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value);
|
|
684
|
-
}
|
|
685
|
-
|
|
686
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js
|
|
687
|
-
var MAX_TRACE_STATE_ITEMS = 32;
|
|
688
|
-
var MAX_TRACE_STATE_LEN = 512;
|
|
689
|
-
var LIST_MEMBERS_SEPARATOR = ",";
|
|
690
|
-
var LIST_MEMBER_KEY_VALUE_SPLITTER = "=";
|
|
691
|
-
var TraceStateImpl = class _TraceStateImpl {
|
|
692
|
-
constructor(rawTraceState) {
|
|
693
|
-
this._internalState = /* @__PURE__ */ new Map();
|
|
694
|
-
if (rawTraceState)
|
|
695
|
-
this._parse(rawTraceState);
|
|
696
|
-
}
|
|
697
|
-
set(key, value) {
|
|
698
|
-
const traceState = this._clone();
|
|
699
|
-
if (traceState._internalState.has(key)) {
|
|
700
|
-
traceState._internalState.delete(key);
|
|
701
|
-
}
|
|
702
|
-
traceState._internalState.set(key, value);
|
|
703
|
-
return traceState;
|
|
704
|
-
}
|
|
705
|
-
unset(key) {
|
|
706
|
-
const traceState = this._clone();
|
|
707
|
-
traceState._internalState.delete(key);
|
|
708
|
-
return traceState;
|
|
709
|
-
}
|
|
710
|
-
get(key) {
|
|
711
|
-
return this._internalState.get(key);
|
|
712
|
-
}
|
|
713
|
-
serialize() {
|
|
714
|
-
return Array.from(this._internalState.keys()).reduceRight((agg, key) => {
|
|
715
|
-
agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key));
|
|
716
|
-
return agg;
|
|
717
|
-
}, []).join(LIST_MEMBERS_SEPARATOR);
|
|
718
|
-
}
|
|
719
|
-
_parse(rawTraceState) {
|
|
720
|
-
if (rawTraceState.length > MAX_TRACE_STATE_LEN)
|
|
721
|
-
return;
|
|
722
|
-
this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reduceRight((agg, part) => {
|
|
723
|
-
const listMember = part.trim();
|
|
724
|
-
const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER);
|
|
725
|
-
if (i !== -1) {
|
|
726
|
-
const key = listMember.slice(0, i);
|
|
727
|
-
const value = listMember.slice(i + 1, part.length);
|
|
728
|
-
if (validateKey(key) && validateValue(value)) {
|
|
729
|
-
agg.set(key, value);
|
|
730
|
-
} else {
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
return agg;
|
|
734
|
-
}, /* @__PURE__ */ new Map());
|
|
735
|
-
if (this._internalState.size > MAX_TRACE_STATE_ITEMS) {
|
|
736
|
-
this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS));
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
// @ts-expect-error TS6133 Accessed in tests only.
|
|
740
|
-
_keys() {
|
|
741
|
-
return Array.from(this._internalState.keys()).reverse();
|
|
742
|
-
}
|
|
743
|
-
_clone() {
|
|
744
|
-
const traceState = new _TraceStateImpl();
|
|
745
|
-
traceState._internalState = new Map(this._internalState);
|
|
746
|
-
return traceState;
|
|
747
|
-
}
|
|
748
|
-
};
|
|
749
|
-
|
|
750
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js
|
|
751
|
-
function createTraceState(rawTraceState) {
|
|
752
|
-
return new TraceStateImpl(rawTraceState);
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/api/trace.js
|
|
756
|
-
var API_NAME3 = "trace";
|
|
757
|
-
var TraceAPI = class _TraceAPI {
|
|
758
|
-
/** Empty private constructor prevents end users from constructing a new instance of the API */
|
|
759
|
-
constructor() {
|
|
760
|
-
this._proxyTracerProvider = new ProxyTracerProvider();
|
|
761
|
-
this.wrapSpanContext = wrapSpanContext;
|
|
762
|
-
this.isSpanContextValid = isSpanContextValid;
|
|
763
|
-
this.deleteSpan = deleteSpan;
|
|
764
|
-
this.getSpan = getSpan;
|
|
765
|
-
this.getActiveSpan = getActiveSpan;
|
|
766
|
-
this.getSpanContext = getSpanContext;
|
|
767
|
-
this.setSpan = setSpan;
|
|
768
|
-
this.setSpanContext = setSpanContext;
|
|
769
|
-
}
|
|
770
|
-
/** Get the singleton instance of the Trace API */
|
|
771
|
-
static getInstance() {
|
|
772
|
-
if (!this._instance) {
|
|
773
|
-
this._instance = new _TraceAPI();
|
|
774
|
-
}
|
|
775
|
-
return this._instance;
|
|
776
|
-
}
|
|
777
|
-
/**
|
|
778
|
-
* Set the current global tracer.
|
|
779
|
-
*
|
|
780
|
-
* @returns true if the tracer provider was successfully registered, else false
|
|
781
|
-
*/
|
|
782
|
-
setGlobalTracerProvider(provider) {
|
|
783
|
-
const success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
|
|
784
|
-
if (success) {
|
|
785
|
-
this._proxyTracerProvider.setDelegate(provider);
|
|
786
|
-
}
|
|
787
|
-
return success;
|
|
788
|
-
}
|
|
789
|
-
/**
|
|
790
|
-
* Returns the global tracer provider.
|
|
791
|
-
*/
|
|
792
|
-
getTracerProvider() {
|
|
793
|
-
return getGlobal(API_NAME3) || this._proxyTracerProvider;
|
|
794
|
-
}
|
|
795
|
-
/**
|
|
796
|
-
* Returns a tracer from the global tracer provider.
|
|
797
|
-
*/
|
|
798
|
-
getTracer(name, version) {
|
|
799
|
-
return this.getTracerProvider().getTracer(name, version);
|
|
800
|
-
}
|
|
801
|
-
/** Remove the global tracer provider */
|
|
802
|
-
disable() {
|
|
803
|
-
unregisterGlobal(API_NAME3, DiagAPI.instance());
|
|
804
|
-
this._proxyTracerProvider = new ProxyTracerProvider();
|
|
805
|
-
}
|
|
806
|
-
};
|
|
807
|
-
|
|
808
|
-
// node_modules/.pnpm/@opentelemetry+api@1.9.1/node_modules/@opentelemetry/api/build/esm/trace-api.js
|
|
809
|
-
var trace = TraceAPI.getInstance();
|
|
810
|
-
|
|
811
|
-
// src/mcp/cli/command-context.ts
|
|
812
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
813
|
-
var storage = new AsyncLocalStorage();
|
|
814
|
-
function currentMcpCommandContext() {
|
|
815
|
-
return storage.getStore();
|
|
816
|
-
}
|
|
817
|
-
function runWithMcpCommandContext(context2, task) {
|
|
818
|
-
return storage.run(context2, task);
|
|
819
|
-
}
|
|
820
|
-
function installMcpCommandIoRouting() {
|
|
821
|
-
const stdoutWrite = process.stdout.write.bind(process.stdout);
|
|
822
|
-
const stderrWrite = process.stderr.write.bind(process.stderr);
|
|
823
|
-
process.stdout.write = ((chunk, ...args) => {
|
|
824
|
-
const target = currentMcpCommandContext()?.stdout;
|
|
825
|
-
return target ? target.write(chunk) : stdoutWrite(chunk, ...args);
|
|
826
|
-
});
|
|
827
|
-
process.stderr.write = ((chunk, ...args) => {
|
|
828
|
-
const target = currentMcpCommandContext()?.stderr;
|
|
829
|
-
return target ? target.write(chunk) : stderrWrite(chunk, ...args);
|
|
830
|
-
});
|
|
831
|
-
return () => {
|
|
832
|
-
process.stdout.write = stdoutWrite;
|
|
833
|
-
process.stderr.write = stderrWrite;
|
|
834
|
-
};
|
|
835
|
-
}
|
|
836
|
-
|
|
837
|
-
// src/mcp/daemon/protocol.ts
|
|
838
|
-
var MCP_DAEMON_SOCKET_ENV = "PI_RECIPES_MCP_DAEMON_SOCKET";
|
|
839
|
-
var MCP_DAEMON_TOKEN_ENV = "PI_RECIPES_MCP_DAEMON_TOKEN";
|
|
840
|
-
var MCP_DAEMON_FINGERPRINT_ENV = "PI_RECIPES_MCP_DAEMON_FINGERPRINT";
|
|
841
|
-
var MCP_DAEMON_PARENT_PID_ENV = "PI_RECIPES_MCP_DAEMON_PARENT_PID";
|
|
842
|
-
var MCP_DAEMON_MAX_FRAME_BYTES = 10 * 1024 * 1024;
|
|
843
|
-
function serializeMcpDaemonEnvelope(envelope, maxBytes = MCP_DAEMON_MAX_FRAME_BYTES) {
|
|
844
|
-
let estimatedBytes = 0;
|
|
845
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
846
|
-
const serialized = JSON.stringify(envelope, (key, value) => {
|
|
847
|
-
estimatedBytes += Buffer.byteLength(key, "utf8") + 4;
|
|
848
|
-
if (typeof value === "string") {
|
|
849
|
-
estimatedBytes += Buffer.byteLength(value, "utf8") + 2;
|
|
850
|
-
} else if (typeof value === "number" || typeof value === "boolean" || value === null) {
|
|
851
|
-
estimatedBytes += 16;
|
|
852
|
-
} else if (value && typeof value === "object") {
|
|
853
|
-
if (seen.has(value)) {
|
|
854
|
-
throw new Error("MCP daemon envelope contains a circular value.");
|
|
855
|
-
}
|
|
856
|
-
seen.add(value);
|
|
857
|
-
}
|
|
858
|
-
if (estimatedBytes > maxBytes) {
|
|
859
|
-
throw new Error("MCP daemon envelope exceeded the frame limit.");
|
|
860
|
-
}
|
|
861
|
-
return value;
|
|
862
|
-
});
|
|
863
|
-
if (Buffer.byteLength(serialized, "utf8") > maxBytes) {
|
|
864
|
-
throw new Error("MCP daemon envelope exceeded the frame limit.");
|
|
865
|
-
}
|
|
866
|
-
return `${serialized}
|
|
867
|
-
`;
|
|
868
|
-
}
|
|
869
|
-
|
|
870
|
-
// src/mcp/trace-context.ts
|
|
871
|
-
var TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
|
|
872
|
-
function mcpDaemonRequestContext(carrier, base = ROOT_CONTEXT) {
|
|
873
|
-
const match = carrier?.traceparent.match(TRACEPARENT);
|
|
874
|
-
if (!match) return base;
|
|
875
|
-
const [, version, traceId, spanId, flags] = match;
|
|
876
|
-
if (version?.toLowerCase() === "ff" || traceId === "0".repeat(32) || spanId === "0".repeat(16)) {
|
|
877
|
-
return base;
|
|
878
|
-
}
|
|
879
|
-
return trace.setSpanContext(base, {
|
|
880
|
-
traceId: traceId.toLowerCase(),
|
|
881
|
-
spanId: spanId.toLowerCase(),
|
|
882
|
-
traceFlags: Number.parseInt(flags, 16),
|
|
883
|
-
isRemote: true,
|
|
884
|
-
...carrier?.tracestate ? { traceState: createTraceState(carrier.tracestate) } : {}
|
|
885
|
-
});
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
// src/mcp/cli/core.ts
|
|
889
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
890
|
-
import { existsSync } from "node:fs";
|
|
891
|
-
import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
892
|
-
import { dirname as dirname2, join as join2 } from "node:path";
|
|
893
|
-
import { setTimeout as delay } from "node:timers/promises";
|
|
894
|
-
import { stdin as input, stderr, stdout } from "node:process";
|
|
895
|
-
import { inspect, parseArgs } from "node:util";
|
|
896
|
-
import { isMainThread, Worker } from "node:worker_threads";
|
|
897
|
-
|
|
898
|
-
// src/mcp/contract.ts
|
|
899
|
-
var MAX_EXAMPLE_ARRAY_ITEMS = 3;
|
|
900
|
-
var SAFE_CLI_KEY = /^[A-Za-z_][A-Za-z0-9_.-]*$/;
|
|
901
|
-
var SAFE_SHELL_TOKEN = /^[A-Za-z0-9_./:@+-]+$/;
|
|
902
|
-
function record(value) {
|
|
903
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
904
|
-
}
|
|
905
|
-
function number(value) {
|
|
906
|
-
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
907
|
-
}
|
|
908
|
-
function quoted(value) {
|
|
909
|
-
return JSON.stringify(value);
|
|
910
|
-
}
|
|
911
|
-
function renderSchema(value) {
|
|
912
|
-
const schema = record(value);
|
|
913
|
-
if (!schema || !Array.isArray(schema.allOf)) return schema;
|
|
914
|
-
const branches = schema.allOf.map(renderSchema).filter((branch) => Boolean(branch));
|
|
915
|
-
const baseProperties = record(schema.properties) ?? {};
|
|
916
|
-
const objectLike = branches.every(
|
|
917
|
-
(branch) => branch.type === "object" || Boolean(record(branch.properties))
|
|
918
|
-
);
|
|
919
|
-
if (!objectLike) return { ...schema, allOf: branches };
|
|
920
|
-
const properties = Object.assign(
|
|
921
|
-
{},
|
|
922
|
-
baseProperties,
|
|
923
|
-
...branches.map((branch) => record(branch.properties) ?? {})
|
|
924
|
-
);
|
|
925
|
-
const required = new Set(
|
|
926
|
-
Array.isArray(schema.required) ? schema.required.filter((entry) => typeof entry === "string") : []
|
|
927
|
-
);
|
|
928
|
-
for (const branch of branches) {
|
|
929
|
-
if (!Array.isArray(branch.required)) continue;
|
|
930
|
-
for (const entry of branch.required) {
|
|
931
|
-
if (typeof entry === "string") required.add(entry);
|
|
932
|
-
}
|
|
933
|
-
}
|
|
934
|
-
const { allOf: _allOf, ...rest } = schema;
|
|
935
|
-
return {
|
|
936
|
-
...rest,
|
|
937
|
-
type: "object",
|
|
938
|
-
properties,
|
|
939
|
-
...required.size > 0 ? { required: [...required] } : {}
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
function constraintSuffix(schema) {
|
|
943
|
-
const constraints = [];
|
|
944
|
-
const minimum = number(schema.minimum);
|
|
945
|
-
const maximum = number(schema.maximum);
|
|
946
|
-
if (minimum !== void 0 || maximum !== void 0) {
|
|
947
|
-
constraints.push(`${minimum ?? ""}..${maximum ?? ""}`);
|
|
948
|
-
}
|
|
949
|
-
const minLength = number(schema.minLength);
|
|
950
|
-
const maxLength = number(schema.maxLength);
|
|
951
|
-
if (minLength !== void 0) constraints.push(`minLength=${minLength}`);
|
|
952
|
-
if (maxLength !== void 0) constraints.push(`maxLength=${maxLength}`);
|
|
953
|
-
const minItems = number(schema.minItems);
|
|
954
|
-
const maxItems = number(schema.maxItems);
|
|
955
|
-
if (minItems !== void 0) constraints.push(`minItems=${minItems}`);
|
|
956
|
-
if (maxItems !== void 0) constraints.push(`maxItems=${maxItems}`);
|
|
957
|
-
if (schema.default !== void 0) constraints.push(`default=${quoted(schema.default)}`);
|
|
958
|
-
return constraints.length > 0 ? ` [${constraints.join(", ")}]` : "";
|
|
959
|
-
}
|
|
960
|
-
function compactSchemaType(value) {
|
|
961
|
-
const schema = renderSchema(value);
|
|
962
|
-
if (!schema) return "unknown";
|
|
963
|
-
if (Array.isArray(schema.allOf)) {
|
|
964
|
-
return schema.allOf.map(compactSchemaType).join(" & ");
|
|
965
|
-
}
|
|
966
|
-
if (schema.const !== void 0) return quoted(schema.const);
|
|
967
|
-
if (Array.isArray(schema.enum)) return schema.enum.map(quoted).join(" | ");
|
|
968
|
-
const union = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : void 0;
|
|
969
|
-
if (union) return union.map(compactSchemaType).join(" | ");
|
|
970
|
-
if (schema.type === "array") {
|
|
971
|
-
return `${compactSchemaType(schema.items)}[]${constraintSuffix(schema)}`;
|
|
972
|
-
}
|
|
973
|
-
if (schema.type === "object" || record(schema.properties)) {
|
|
974
|
-
const properties = record(schema.properties);
|
|
975
|
-
if (!properties || Object.keys(properties).length === 0) return "object";
|
|
976
|
-
const required = new Set(
|
|
977
|
-
Array.isArray(schema.required) ? schema.required.filter((entry) => typeof entry === "string") : []
|
|
978
|
-
);
|
|
979
|
-
const fields = Object.entries(properties).map(
|
|
980
|
-
([name, descriptor]) => `${name}${required.has(name) ? "" : "?"}: ${compactSchemaType(descriptor)}`
|
|
981
|
-
);
|
|
982
|
-
return `{${fields.join(", ")}}`;
|
|
983
|
-
}
|
|
984
|
-
const type = schema.type === "number" ? "number" : schema.type;
|
|
985
|
-
return `${typeof type === "string" ? type : "unknown"}${constraintSuffix(schema)}`;
|
|
986
|
-
}
|
|
987
|
-
function descriptionText(value, verbose) {
|
|
988
|
-
if (typeof value !== "string" || !value.trim()) return "";
|
|
989
|
-
const normalized = value.trim().replace(/\s+/g, " ");
|
|
990
|
-
if (verbose || normalized.length <= 160) return normalized;
|
|
991
|
-
return `${normalized.slice(0, 159).trimEnd()}\u2026`;
|
|
992
|
-
}
|
|
993
|
-
function hasLongDescription(value) {
|
|
994
|
-
if (Array.isArray(value)) return value.some(hasLongDescription);
|
|
995
|
-
const object = record(value);
|
|
996
|
-
if (!object) return false;
|
|
997
|
-
if (typeof object.description === "string" && object.description.trim().replace(/\s+/g, " ").length > 160) {
|
|
998
|
-
return true;
|
|
999
|
-
}
|
|
1000
|
-
return Object.entries(object).some(
|
|
1001
|
-
([key, nested]) => key !== "description" && hasLongDescription(nested)
|
|
1002
|
-
);
|
|
1003
|
-
}
|
|
1004
|
-
function schemaLines(value, indent, options = {}) {
|
|
1005
|
-
const schema = renderSchema(value);
|
|
1006
|
-
if (!schema) return [`${indent}unknown`];
|
|
1007
|
-
const properties = record(schema.properties);
|
|
1008
|
-
if (!properties) return [`${indent}${compactSchemaType(schema)}`];
|
|
1009
|
-
const required = new Set(
|
|
1010
|
-
Array.isArray(schema.required) ? schema.required.filter((entry) => typeof entry === "string") : []
|
|
1011
|
-
);
|
|
1012
|
-
const lines = [];
|
|
1013
|
-
for (const [name, descriptorValue] of Object.entries(properties)) {
|
|
1014
|
-
const descriptor = record(descriptorValue) ?? {};
|
|
1015
|
-
const optional = required.has(name) ? "" : "?";
|
|
1016
|
-
const compactDescription = descriptionText(
|
|
1017
|
-
descriptor.description,
|
|
1018
|
-
options.verboseDescriptions === true
|
|
1019
|
-
);
|
|
1020
|
-
const description = compactDescription ? ` \u2014 ${compactDescription}` : "";
|
|
1021
|
-
const nested = record(descriptor.properties);
|
|
1022
|
-
if (nested) {
|
|
1023
|
-
lines.push(`${indent}${name}${optional}: {`);
|
|
1024
|
-
lines.push(...schemaLines(descriptor, `${indent} `, options));
|
|
1025
|
-
lines.push(`${indent}}${description}`);
|
|
1026
|
-
} else {
|
|
1027
|
-
lines.push(`${indent}${name}${optional}: ${compactSchemaType(descriptor)}${description}`);
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
return lines.length > 0 ? lines : [`${indent}{}`];
|
|
1031
|
-
}
|
|
1032
|
-
function schemaObject(value) {
|
|
1033
|
-
return record(value);
|
|
1034
|
-
}
|
|
1035
|
-
function shellQuote(value) {
|
|
1036
|
-
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
1037
|
-
}
|
|
1038
|
-
function shellToken(value) {
|
|
1039
|
-
return SAFE_SHELL_TOKEN.test(value) ? value : shellQuote(value);
|
|
1040
|
-
}
|
|
1041
|
-
function toolSelector(server, tool) {
|
|
1042
|
-
return shellToken(`${server}.${tool}`);
|
|
1043
|
-
}
|
|
1044
|
-
function exampleValue(value, name) {
|
|
1045
|
-
const schema = renderSchema(value) ?? {};
|
|
1046
|
-
const union = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : void 0;
|
|
1047
|
-
if (union?.length) return exampleValue(union[0], name);
|
|
1048
|
-
if (schema.const !== void 0) return schema.const;
|
|
1049
|
-
if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum[0];
|
|
1050
|
-
if (schema.type === "boolean") return true;
|
|
1051
|
-
if (schema.type === "number" || schema.type === "integer") {
|
|
1052
|
-
return number(schema.minimum) ?? 1;
|
|
1053
|
-
}
|
|
1054
|
-
if (schema.type === "array") {
|
|
1055
|
-
const count = Math.min(
|
|
1056
|
-
MAX_EXAMPLE_ARRAY_ITEMS,
|
|
1057
|
-
Math.max(1, number(schema.minItems) ?? 1)
|
|
1058
|
-
);
|
|
1059
|
-
return Array.from({ length: count }, () => exampleValue(schema.items, "value"));
|
|
1060
|
-
}
|
|
1061
|
-
if (schema.type === "object" || record(schema.properties)) {
|
|
1062
|
-
const properties = record(schema.properties) ?? {};
|
|
1063
|
-
const required = Array.isArray(schema.required) ? schema.required.filter((entry) => typeof entry === "string") : [];
|
|
1064
|
-
return Object.fromEntries(
|
|
1065
|
-
required.map((field) => [field, exampleValue(properties[field], field)])
|
|
1066
|
-
);
|
|
1067
|
-
}
|
|
1068
|
-
return `<${name}>`;
|
|
1069
|
-
}
|
|
1070
|
-
function callValue(value, name) {
|
|
1071
|
-
const example = exampleValue(value, name);
|
|
1072
|
-
return typeof example === "string" ? shellQuote(example) : typeof example === "object" ? shellQuote(JSON.stringify(example)) : String(example);
|
|
1073
|
-
}
|
|
1074
|
-
function callExample(server, tool) {
|
|
1075
|
-
const schema = renderSchema(tool.inputSchema);
|
|
1076
|
-
const properties = record(schema?.properties) ?? {};
|
|
1077
|
-
const required = Array.isArray(schema?.required) ? schema.required.filter((entry) => typeof entry === "string") : [];
|
|
1078
|
-
if (required.some(
|
|
1079
|
-
(name) => !SAFE_CLI_KEY.test(name) || Boolean(
|
|
1080
|
-
structuredBranch(properties[name], "object") ?? structuredBranch(properties[name], "array")
|
|
1081
|
-
)
|
|
1082
|
-
)) {
|
|
1083
|
-
const json = JSON.stringify(
|
|
1084
|
-
Object.fromEntries(required.map((name) => [name, exampleValue(properties[name], name)]))
|
|
1085
|
-
);
|
|
1086
|
-
return `mcp call ${toolSelector(server, tool.name)} --json ${shellQuote(json)}`;
|
|
1087
|
-
}
|
|
1088
|
-
const args = required.map((name) => {
|
|
1089
|
-
const descriptor = record(properties[name]) ?? {};
|
|
1090
|
-
return `${name}=${callValue(descriptor, name)}`;
|
|
1091
|
-
});
|
|
1092
|
-
return `mcp call ${toolSelector(server, tool.name)}${args.length > 0 ? ` ${args.join(" ")}` : ""}`;
|
|
1093
|
-
}
|
|
1094
|
-
function structuredBranch(value, kind) {
|
|
1095
|
-
const schema = renderSchema(value);
|
|
1096
|
-
if (!schema) return void 0;
|
|
1097
|
-
if (kind === "array" && schema.type === "array" || kind === "object" && (schema.type === "object" || record(schema.properties))) {
|
|
1098
|
-
return schema;
|
|
1099
|
-
}
|
|
1100
|
-
const union = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : [];
|
|
1101
|
-
return union.map((branch) => structuredBranch(branch, kind)).find(Boolean);
|
|
1102
|
-
}
|
|
1103
|
-
function structuredCallExample(server, tool) {
|
|
1104
|
-
const schema = renderSchema(tool.inputSchema);
|
|
1105
|
-
const properties = record(schema?.properties) ?? {};
|
|
1106
|
-
const required = new Set(
|
|
1107
|
-
Array.isArray(schema?.required) ? schema.required.filter((entry) => typeof entry === "string") : []
|
|
1108
|
-
);
|
|
1109
|
-
const requiredValues = Object.fromEntries(
|
|
1110
|
-
[...required].map((name) => [name, exampleValue(properties[name], name)])
|
|
1111
|
-
);
|
|
1112
|
-
for (const kind of ["object", "array"]) {
|
|
1113
|
-
for (const [name, descriptor] of Object.entries(properties)) {
|
|
1114
|
-
const branch = structuredBranch(descriptor, kind);
|
|
1115
|
-
if (!branch) continue;
|
|
1116
|
-
const json = JSON.stringify({
|
|
1117
|
-
...requiredValues,
|
|
1118
|
-
...!required.has(name) ? { [name]: exampleValue(branch, name) } : {}
|
|
1119
|
-
});
|
|
1120
|
-
return `mcp call ${toolSelector(server, tool.name)} --json ${shellQuote(json)}`;
|
|
1121
|
-
}
|
|
1122
|
-
}
|
|
1123
|
-
return void 0;
|
|
1124
|
-
}
|
|
1125
|
-
function renderToolContract(server, tool, options = {}) {
|
|
1126
|
-
const lines = [`${server}.${tool.name}`];
|
|
1127
|
-
const description = descriptionText(
|
|
1128
|
-
tool.description,
|
|
1129
|
-
options.verboseDescriptions === true
|
|
1130
|
-
);
|
|
1131
|
-
if (description) {
|
|
1132
|
-
lines.push(description);
|
|
1133
|
-
}
|
|
1134
|
-
if (!options.verboseDescriptions && (descriptionText(tool.description, true).length > 160 || hasLongDescription(tool.inputSchema) || hasLongDescription(tool.outputSchema))) {
|
|
1135
|
-
lines.push("Descriptions shortened; use --verbose for full text.");
|
|
1136
|
-
}
|
|
1137
|
-
lines.push("", "input", ...schemaLines(tool.inputSchema, " ", options));
|
|
1138
|
-
lines.push(
|
|
1139
|
-
"",
|
|
1140
|
-
"output",
|
|
1141
|
-
...schemaObject(tool.outputSchema) ? schemaLines(tool.outputSchema, " ", options) : [" unspecified"]
|
|
1142
|
-
);
|
|
1143
|
-
lines.push("", "call", ` ${callExample(server, tool)}`);
|
|
1144
|
-
const structured = structuredCallExample(server, tool);
|
|
1145
|
-
if (structured) lines.push(` structured: ${structured}`);
|
|
1146
|
-
return `${lines.join("\n")}
|
|
1147
|
-
`;
|
|
1148
|
-
}
|
|
1149
|
-
function renderToolSignature(server, tool, options = {}) {
|
|
1150
|
-
const schema = renderSchema(tool.inputSchema);
|
|
1151
|
-
const properties = record(schema?.properties) ?? {};
|
|
1152
|
-
const required = new Set(
|
|
1153
|
-
Array.isArray(schema?.required) ? schema.required.filter((entry) => typeof entry === "string") : []
|
|
1154
|
-
);
|
|
1155
|
-
const entries = Object.entries(properties);
|
|
1156
|
-
const included = new Set(
|
|
1157
|
-
entries.filter(([name]) => required.has(name)).map(([name]) => name)
|
|
1158
|
-
);
|
|
1159
|
-
if (!options.allParameters) {
|
|
1160
|
-
for (const [name] of entries) {
|
|
1161
|
-
if (included.size >= 5) break;
|
|
1162
|
-
included.add(name);
|
|
1163
|
-
}
|
|
1164
|
-
}
|
|
1165
|
-
const visible = options.allParameters ? entries : entries.filter(([name]) => included.has(name));
|
|
1166
|
-
const parameters = visible.map(([name, descriptor]) => {
|
|
1167
|
-
const optional = required.has(name) ? "" : "?";
|
|
1168
|
-
return `${name}${optional}: ${compactSchemaType(descriptor)}`;
|
|
1169
|
-
});
|
|
1170
|
-
const hidden = entries.length - visible.length;
|
|
1171
|
-
if (hidden > 0) parameters.push(`\u2026 +${hidden} optional`);
|
|
1172
|
-
return `${server}.${tool.name}(${parameters.join(", ")})`;
|
|
1173
|
-
}
|
|
1174
|
-
function catalogOutputSchema(tool) {
|
|
1175
|
-
return tool?.output_schema;
|
|
1176
|
-
}
|
|
1177
|
-
|
|
1178
|
-
// src/mcp/cli/help.ts
|
|
1179
|
-
function mcpCliHelpText() {
|
|
1180
|
-
return [
|
|
1181
|
-
"mcp - use available MCP tools",
|
|
1182
|
-
"Supported: search, list, call, and run.",
|
|
1183
|
-
"Run `mcp <command> --help` for complete command syntax.",
|
|
1184
|
-
"Use this session-local `mcp` command, not `mcporter` or `npx mcporter`; it enforces the materialized recipe capabilities.",
|
|
1185
|
-
"",
|
|
1186
|
-
"Flow:",
|
|
1187
|
-
' mcp search "what you need" Matches with their input and output contracts.',
|
|
1188
|
-
" mcp call <server>.<tool> --json '{...}' One call.",
|
|
1189
|
-
" mcp run <<'JS' ... JS Two or more calls, in one script.",
|
|
1190
|
-
" Metadata is compact text; actual structured tool results are JSON.",
|
|
1191
|
-
"",
|
|
1192
|
-
"Batch or compose multiple calls in JavaScript:",
|
|
1193
|
-
" mcp run <<'JS'",
|
|
1194
|
-
' const ids = ["id-1", "id-2", "id-3"]',
|
|
1195
|
-
' const settled = await Promise.allSettled(ids.map(id => tools["server"]["tool"]({ id })))',
|
|
1196
|
-
' console.log(JSON.stringify(Object.fromEntries(settled.map((s, i) => [ids[i], s.status === "fulfilled" ? s.value : { error: String(s.reason) }])), null, 2))',
|
|
1197
|
-
" JS",
|
|
1198
|
-
" Keep the heredoc quoted (<<'JS'). Never chain mcp call in the shell; one script prints one JSON value.",
|
|
1199
|
-
" When a tool declares no output contract and you have not seen its result, print that result whole and read its fields in the next command.",
|
|
1200
|
-
"",
|
|
1201
|
-
"Notes:",
|
|
1202
|
-
" mcp list <server> --schema shows every tool on one server; mcp list browses the inventory.",
|
|
1203
|
-
" Run `mcp call --help` or `mcp run --help` for advanced argument, output, and workflow options.",
|
|
1204
|
-
" Tool commands are always headless. If authentication is required, ask the user to authenticate the MCP connection outside the agent session, then retry.",
|
|
1205
|
-
"",
|
|
1206
|
-
"Availability:",
|
|
1207
|
-
" Search and list expose only tools callable in this session.",
|
|
1208
|
-
" Only exact tool names returned by mcp list are callable.",
|
|
1209
|
-
" Descriptions may mention related tools that are not exposed; mentions do not grant access.",
|
|
1210
|
-
" If no listed tool supports an action, report that the connected capability is unavailable.",
|
|
1211
|
-
" MCP resources and administrative or ad-hoc connection commands are not exposed."
|
|
1212
|
-
].join("\n");
|
|
1213
|
-
}
|
|
1214
|
-
function mcpListHelpText() {
|
|
1215
|
-
return [
|
|
1216
|
-
"Usage: mcp list [server | server.tool] [flags]",
|
|
1217
|
-
"",
|
|
1218
|
-
"Shows a compact view of tools materialized in this recipe session.",
|
|
1219
|
-
"",
|
|
1220
|
-
"Flags:",
|
|
1221
|
-
" --all-parameters Include every optional parameter.",
|
|
1222
|
-
" --schema Show the input/output contract of one tool, or of every tool on a server.",
|
|
1223
|
-
" --verbose Include full tool and parameter descriptions.",
|
|
1224
|
-
" --status Show concise status for an exact server target.",
|
|
1225
|
-
" --quiet, --exit-code Health checks for an exact server target.",
|
|
1226
|
-
" --timeout <ms> Override discovery timeout for an exact target.",
|
|
1227
|
-
" JSON is reserved for actual tool results; metadata is compact text.",
|
|
1228
|
-
"",
|
|
1229
|
-
"URLs, ad-hoc transports, config overrides, and persistence are unavailable in recipe sessions."
|
|
1230
|
-
].join("\n");
|
|
1231
|
-
}
|
|
1232
|
-
function mcpCallHelpText() {
|
|
1233
|
-
return [
|
|
1234
|
-
"Usage: mcp call <server>.<tool> [arguments] [flags]",
|
|
1235
|
-
"",
|
|
1236
|
-
"Calls exact tools materialized in this recipe session.",
|
|
1237
|
-
"",
|
|
1238
|
-
"Arguments:",
|
|
1239
|
-
" key=value Named arguments with schema-aware coercion.",
|
|
1240
|
-
" key=@path Read an exact UTF-8 string; use @@ for a literal @.",
|
|
1241
|
-
" --json <json|-> Supply a structured JSON object directly or from stdin.",
|
|
1242
|
-
` Array example: mcp call server.tool --json '{"tags":["a","b"]}'.`,
|
|
1243
|
-
" Quote argument tokens containing shell operators such as |, <, >, &, or ;. JSON stdin avoids nested shell quoting.",
|
|
1244
|
-
"",
|
|
1245
|
-
"Output/runtime flags:",
|
|
1246
|
-
" --output text|markdown|json|raw",
|
|
1247
|
-
" --timeout <ms>",
|
|
1248
|
-
" Machine-readable output is forwarded unchanged.",
|
|
1249
|
-
" When parsing JSON, keep stderr separate and do not truncate stdout with head or sed.",
|
|
1250
|
-
"",
|
|
1251
|
-
"URLs, ad-hoc transports, config overrides, and persistence are unavailable in recipe sessions."
|
|
1252
|
-
].join("\n");
|
|
1253
|
-
}
|
|
1254
|
-
function mcpSearchHelpText() {
|
|
1255
|
-
return [
|
|
1256
|
-
'Usage: mcp search "what you need" [--limit N] [--regex]',
|
|
1257
|
-
"",
|
|
1258
|
-
"Searches only MCP tools available in this session.",
|
|
1259
|
-
"The best matches show their full contract (description, input, output, call example); past about 4,000 characters the rest are one-line signatures.",
|
|
1260
|
-
"Call a match with a contract directly; no separate schema lookup is needed. Default limit is 5.",
|
|
1261
|
-
"Try broader or alternate terms when no result matches."
|
|
1262
|
-
].join("\n");
|
|
1263
|
-
}
|
|
1264
|
-
function mcpRunHelpText() {
|
|
1265
|
-
return [
|
|
1266
|
-
"Usage: mcp run [--var KEY=value] [--json-errors] [file]",
|
|
1267
|
-
"",
|
|
1268
|
-
'Runs a short JavaScript workflow with available MCP tools such as `tools["server"]["tool"]`.',
|
|
1269
|
-
"With no file, code is read from stdin. Keep heredocs quoted and pass dynamic values with --var.",
|
|
1270
|
-
"Scripts are killed after 120s by default (override with PI_RECIPES_MCP_RUN_TIMEOUT_MS).",
|
|
1271
|
-
"Each tool call is capped at 60s; workflows allow at most 100 calls and run 16 at a time by default.",
|
|
1272
|
-
"Extra calls wait in a FIFO queue and inherit the remaining workflow deadline.",
|
|
1273
|
-
"Always await or return tool-call chains.",
|
|
1274
|
-
"Detached .then/.catch calls fail if still pending when the script exits.",
|
|
1275
|
-
"Structured MCP errors retain code, retryable, action, request_id, and outcome fields when supplied.",
|
|
1276
|
-
"Calls return decoded JSON by default, so read response fields directly from the awaited value.",
|
|
1277
|
-
"Only when a tool documents another response type, call the format on the tool itself: tool.text(args), tool.markdown(args), tool.images(args), tool.content(args), tool.structuredContent(args), or tool.raw(args).",
|
|
1278
|
-
"Use Promise.allSettled for independent reads, so one failed call keeps the others' results. Await dependent calls and mutations in order.",
|
|
1279
|
-
"Do not loop over or chain mcp call in the shell. Print one JSON value, keyed by call.",
|
|
1280
|
-
"When a tool declares no output contract and you have not seen its result, print that result whole; read its fields in the next run.",
|
|
1281
|
-
"A refused connection handshake (HTTP 5xx before the call starts) is retried automatically; any other failure is reported, since the call may have run.",
|
|
1282
|
-
"Use --var/vars for dynamic input; process.argv is intentionally unavailable inside workflows.",
|
|
1283
|
-
"--json-errors emits a structured error object on stderr while preserving the nonzero exit code.",
|
|
1284
|
-
"MCP calls are always headless. If authentication is required, ask the user to authenticate the connection outside the agent session, then retry.",
|
|
1285
|
-
"A synchronous busy-loop is force-killed at the deadline.",
|
|
1286
|
-
"Code runs with the same OS privileges as the active shell sandbox; mcp run is not a separate security boundary.",
|
|
1287
|
-
"",
|
|
1288
|
-
"Example \u2014 batch or compose multiple calls:",
|
|
1289
|
-
" mcp run <<'JS'",
|
|
1290
|
-
' const ids = ["id-1", "id-2", "id-3"]',
|
|
1291
|
-
' const settled = await Promise.allSettled(ids.map(id => tools["server"]["tool"]({ id })))',
|
|
1292
|
-
' console.log(JSON.stringify(Object.fromEntries(settled.map((s, i) => [ids[i], s.status === "fulfilled" ? s.value : { error: String(s.reason) }])), null, 2))',
|
|
1293
|
-
" JS"
|
|
1294
|
-
].join("\n");
|
|
1295
|
-
}
|
|
1296
|
-
|
|
1297
|
-
// src/mcp/index.ts
|
|
1298
|
-
import { delimiter, dirname, join, resolve } from "node:path";
|
|
1299
|
-
|
|
1300
|
-
// src/recipe/package.ts
|
|
1301
|
-
var RESOURCE_KEYS = [
|
|
1302
|
-
"agents",
|
|
1303
|
-
"extensions",
|
|
1304
|
-
"skills",
|
|
1305
|
-
"prompts"
|
|
1306
|
-
];
|
|
1307
|
-
var PI_KEYS = /* @__PURE__ */ new Set([
|
|
1308
|
-
...RESOURCE_KEYS,
|
|
1309
|
-
"channels",
|
|
1310
|
-
"mcp",
|
|
1311
|
-
"runtime"
|
|
1312
|
-
]);
|
|
1313
|
-
|
|
1314
|
-
// src/mcp/policy.ts
|
|
1315
|
-
function mcpSelectionAllowsTool(selection, toolName) {
|
|
1316
|
-
const included = selection.include?.some((selector) => {
|
|
1317
|
-
const trimmed = selector.trim();
|
|
1318
|
-
return trimmed === "*" || trimmed === toolName;
|
|
1319
|
-
}) ?? false;
|
|
1320
|
-
if (!included) return false;
|
|
1321
|
-
return !(selection.exclude ?? []).some(
|
|
1322
|
-
(selector) => selector.trim() === toolName
|
|
1323
|
-
);
|
|
1324
|
-
}
|
|
1325
|
-
|
|
1326
|
-
// src/mcp/daemon/client.ts
|
|
1327
|
-
var MAX_DAEMON_FRAME_BYTES = 10 * 1024 * 1024;
|
|
1328
|
-
|
|
1329
|
-
// src/mcp/index.ts
|
|
1330
|
-
var RECIPE_ENV_PREFIX = "PI_RECIPES_";
|
|
1331
|
-
var MCP_SESSION_ENV = `${RECIPE_ENV_PREFIX}MCP_SESSION`;
|
|
1332
|
-
var MCP_LOCAL_CONFIG_ENV = `${RECIPE_ENV_PREFIX}MCP_LOCAL_CONFIG`;
|
|
1333
|
-
var MCP_BIN_DIR_ENV = `${RECIPE_ENV_PREFIX}MCP_BIN_DIR`;
|
|
1334
|
-
function defaultMcpSessionPath(cwd) {
|
|
1335
|
-
return join(cwd, ".pi", "mcp-session.json");
|
|
1336
|
-
}
|
|
1337
|
-
function defaultMcporterConfigPath(cwd) {
|
|
1338
|
-
return join(cwd, ".pi", "mcporter.json");
|
|
1339
|
-
}
|
|
1340
|
-
function mcpSessionAllowsTool(server, toolName) {
|
|
1341
|
-
return mcpSelectionAllowsTool(server.package_tools, toolName) && server.agent_tools.some(
|
|
1342
|
-
(selection) => mcpSelectionAllowsTool(selection, toolName)
|
|
1343
|
-
);
|
|
1344
|
-
}
|
|
1345
|
-
function escapeRegExp(value) {
|
|
1346
|
-
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1347
|
-
}
|
|
1348
|
-
function filterMcpCatalog(server, catalog) {
|
|
1349
|
-
const allowed = catalog.filter(
|
|
1350
|
-
(tool) => mcpSessionAllowsTool(server, tool.name)
|
|
1351
|
-
);
|
|
1352
|
-
const hiddenNames = catalog.filter((tool) => !mcpSessionAllowsTool(server, tool.name)).map((tool) => tool.name).filter(Boolean).sort((left, right) => right.length - left.length);
|
|
1353
|
-
if (hiddenNames.length === 0) return allowed;
|
|
1354
|
-
return allowed.map((tool) => ({
|
|
1355
|
-
...tool,
|
|
1356
|
-
...tool.description ? {
|
|
1357
|
-
description: hiddenNames.reduce(
|
|
1358
|
-
(description, name) => description.replace(
|
|
1359
|
-
new RegExp(
|
|
1360
|
-
`(^|[^A-Za-z0-9_-])${escapeRegExp(name)}(?=$|[^A-Za-z0-9_-])`,
|
|
1361
|
-
"g"
|
|
1362
|
-
),
|
|
1363
|
-
"$1[unavailable MCP tool]"
|
|
1364
|
-
),
|
|
1365
|
-
tool.description
|
|
1366
|
-
)
|
|
1367
|
-
} : {}
|
|
1368
|
-
}));
|
|
1369
|
-
}
|
|
1370
|
-
|
|
1371
|
-
// src/mcp/cli/policy.ts
|
|
1372
|
-
var FORBIDDEN_DELEGATED_FLAGS = /* @__PURE__ */ new Set([
|
|
1373
|
-
"--config",
|
|
1374
|
-
"--root",
|
|
1375
|
-
"--log-level",
|
|
1376
|
-
"--http-url",
|
|
1377
|
-
"--sse",
|
|
1378
|
-
"--stdio",
|
|
1379
|
-
"--stdio-bin",
|
|
1380
|
-
"--stdio-arg",
|
|
1381
|
-
"--header",
|
|
1382
|
-
"--env",
|
|
1383
|
-
"--cwd",
|
|
1384
|
-
"--name",
|
|
1385
|
-
"--description",
|
|
1386
|
-
"--persist",
|
|
1387
|
-
"--allow-http",
|
|
1388
|
-
"--insecure",
|
|
1389
|
-
"--yes",
|
|
1390
|
-
"--server",
|
|
1391
|
-
"--tool",
|
|
1392
|
-
"--tail-log",
|
|
1393
|
-
"--brief",
|
|
1394
|
-
"--signatures",
|
|
1395
|
-
"--args",
|
|
1396
|
-
"--no-oauth",
|
|
1397
|
-
"--oauth-timeout",
|
|
1398
|
-
"--raw-strings",
|
|
1399
|
-
"--no-coerce"
|
|
1400
|
-
]);
|
|
1401
|
-
var LIST_OUTPUT_MODES = /* @__PURE__ */ new Map([
|
|
1402
|
-
["--schema", "schema"],
|
|
1403
|
-
["--all-parameters", "all-parameters"],
|
|
1404
|
-
["--status", "status"]
|
|
1405
|
-
]);
|
|
1406
|
-
function flagName(value) {
|
|
1407
|
-
const equals = value.indexOf("=");
|
|
1408
|
-
return equals === -1 ? value : value.slice(0, equals);
|
|
1409
|
-
}
|
|
1410
|
-
function toolSelector2(value) {
|
|
1411
|
-
const ref = value.trim();
|
|
1412
|
-
if (/[()]/.test(ref)) return null;
|
|
1413
|
-
const dot = ref.indexOf(".");
|
|
1414
|
-
if (dot < 1 || dot === ref.length - 1) return null;
|
|
1415
|
-
return { server: ref.slice(0, dot), tool: ref.slice(dot + 1) };
|
|
1416
|
-
}
|
|
1417
|
-
function withNoOAuth(args) {
|
|
1418
|
-
const literalSeparator = args.indexOf("--");
|
|
1419
|
-
if (literalSeparator === -1) return [...args, "--no-oauth"];
|
|
1420
|
-
return [
|
|
1421
|
-
...args.slice(0, literalSeparator),
|
|
1422
|
-
"--no-oauth",
|
|
1423
|
-
...args.slice(literalSeparator)
|
|
1424
|
-
];
|
|
1425
|
-
}
|
|
1426
|
-
function forbiddenFlag(args) {
|
|
1427
|
-
const literalSeparator = args.indexOf("--");
|
|
1428
|
-
const options = literalSeparator === -1 ? args : args.slice(0, literalSeparator);
|
|
1429
|
-
return options.map(flagName).find((flag) => FORBIDDEN_DELEGATED_FLAGS.has(flag));
|
|
1430
|
-
}
|
|
1431
|
-
function listOutputModeError(args) {
|
|
1432
|
-
const literalSeparator = args.indexOf("--");
|
|
1433
|
-
const options = literalSeparator === -1 ? args : args.slice(0, literalSeparator);
|
|
1434
|
-
const modes = new Set(
|
|
1435
|
-
options.map((arg) => LIST_OUTPUT_MODES.get(flagName(arg))).filter((mode) => Boolean(mode))
|
|
1436
|
-
);
|
|
1437
|
-
return modes.size > 1 ? "mcp list accepts only one output mode: --schema, --all-parameters, or --status." : void 0;
|
|
1438
|
-
}
|
|
1439
|
-
function closestName(input2, candidates) {
|
|
1440
|
-
const normalize = (value) => value.replace(/[^a-z0-9]/gi, "").toLowerCase();
|
|
1441
|
-
const source = normalize(input2);
|
|
1442
|
-
const distance = (left, right) => {
|
|
1443
|
-
let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
1444
|
-
for (let i = 1; i <= left.length; i += 1) {
|
|
1445
|
-
const current = [i];
|
|
1446
|
-
for (let j = 1; j <= right.length; j += 1) {
|
|
1447
|
-
current[j] = Math.min(
|
|
1448
|
-
current[j - 1] + 1,
|
|
1449
|
-
previous[j] + 1,
|
|
1450
|
-
previous[j - 1] + (left[i - 1] === right[j - 1] ? 0 : 1)
|
|
1451
|
-
);
|
|
1452
|
-
}
|
|
1453
|
-
previous = current;
|
|
1454
|
-
}
|
|
1455
|
-
return previous[right.length];
|
|
1456
|
-
};
|
|
1457
|
-
let best;
|
|
1458
|
-
let bestDistance = Number.POSITIVE_INFINITY;
|
|
1459
|
-
for (const candidate of candidates) {
|
|
1460
|
-
const candidateDistance = distance(source, normalize(candidate));
|
|
1461
|
-
if (candidateDistance < bestDistance) {
|
|
1462
|
-
best = candidate;
|
|
1463
|
-
bestDistance = candidateDistance;
|
|
1464
|
-
}
|
|
1465
|
-
}
|
|
1466
|
-
if (!best) return void 0;
|
|
1467
|
-
const baseline = Math.max(source.length, normalize(best).length, 1);
|
|
1468
|
-
return bestDistance <= Math.max(2, Math.floor(baseline / 3)) ? best : void 0;
|
|
1469
|
-
}
|
|
1470
|
-
function validateExactTarget(policy, server, tool) {
|
|
1471
|
-
const configured = policy.servers.get(server);
|
|
1472
|
-
if (!configured) {
|
|
1473
|
-
const available = [...policy.servers.keys()];
|
|
1474
|
-
const suggestion = closestName(server, available);
|
|
1475
|
-
return available.length > 0 ? `MCP server '${server}' is not available in this session.${suggestion ? ` Did you mean '${suggestion}'?` : ""} Available servers: ${available.join(", ")}.` : `MCP server '${server}' is not available in this session. No MCP servers are configured.`;
|
|
1476
|
-
}
|
|
1477
|
-
if (tool !== void 0 && !mcpSessionAllowsTool(configured, tool)) {
|
|
1478
|
-
const known = configured.catalog?.map((entry) => entry.name) ?? [];
|
|
1479
|
-
const suggestion = closestName(tool, known);
|
|
1480
|
-
return `Tool '${tool}' is not available on server '${server}' in this session.${suggestion ? ` Did you mean '${suggestion}'?` : ""} Run \`mcp list ${server}\` to inspect the callable tools.`;
|
|
1481
|
-
}
|
|
1482
|
-
return null;
|
|
1483
|
-
}
|
|
1484
|
-
function validateList(args, policy) {
|
|
1485
|
-
const blocked = forbiddenFlag(args.slice(1));
|
|
1486
|
-
if (blocked) return { error: `mcp list option '${blocked}' is unavailable in recipe sessions.` };
|
|
1487
|
-
const outputModeError = listOutputModeError(args.slice(1));
|
|
1488
|
-
if (outputModeError) return { error: outputModeError };
|
|
1489
|
-
const adHocTarget = args.slice(1).find((arg) => !arg.startsWith("-") && /^(?:https?:\/\/|[^/]+\/)/i.test(arg));
|
|
1490
|
-
if (adHocTarget) {
|
|
1491
|
-
return { error: "mcp list accepts only servers materialized for this recipe session; URLs and ad-hoc servers are unavailable." };
|
|
1492
|
-
}
|
|
1493
|
-
const target = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
|
|
1494
|
-
if (target !== void 0) {
|
|
1495
|
-
const selector = toolSelector2(target);
|
|
1496
|
-
const server = selector?.server ?? target;
|
|
1497
|
-
const error = validateExactTarget(policy, server, selector?.tool);
|
|
1498
|
-
if (error) return { error };
|
|
1499
|
-
}
|
|
1500
|
-
return {
|
|
1501
|
-
command: {
|
|
1502
|
-
args: withNoOAuth(args)
|
|
1503
|
-
}
|
|
1504
|
-
};
|
|
1505
|
-
}
|
|
1506
|
-
var CALL_FLAGS_WITH_VALUE = /* @__PURE__ */ new Set([
|
|
1507
|
-
"--json",
|
|
1508
|
-
"--output",
|
|
1509
|
-
"--timeout"
|
|
1510
|
-
]);
|
|
1511
|
-
function callSyntaxError(args) {
|
|
1512
|
-
for (let index = 0; index < args.length; index += 1) {
|
|
1513
|
-
const arg = args[index];
|
|
1514
|
-
if (arg === "--") {
|
|
1515
|
-
return "mcp call positional arguments are unavailable; use key=value or --json instead.";
|
|
1516
|
-
}
|
|
1517
|
-
if (arg.startsWith("--")) {
|
|
1518
|
-
const flag = flagName(arg);
|
|
1519
|
-
if (!CALL_FLAGS_WITH_VALUE.has(flag)) {
|
|
1520
|
-
return `mcp call option '${flag}' is unavailable; use key=value or --json for tool arguments.`;
|
|
1521
|
-
}
|
|
1522
|
-
if (!arg.includes("=")) index += 1;
|
|
1523
|
-
continue;
|
|
1524
|
-
}
|
|
1525
|
-
if (/^[A-Za-z_][A-Za-z0-9_.-]*=/.test(arg)) continue;
|
|
1526
|
-
return `mcp call argument '${arg}' must use key=value syntax or be supplied through --json.`;
|
|
1527
|
-
}
|
|
1528
|
-
return void 0;
|
|
1529
|
-
}
|
|
1530
|
-
function validateCall(args, policy) {
|
|
1531
|
-
const rawSelector = args[1];
|
|
1532
|
-
const selector = rawSelector ? toolSelector2(rawSelector) : null;
|
|
1533
|
-
if (!selector) {
|
|
1534
|
-
const splitTool = rawSelector ? args[2] : void 0;
|
|
1535
|
-
if (rawSelector && splitTool && policy.servers.has(rawSelector) && mcpSessionAllowsTool(policy.servers.get(rawSelector), splitTool)) {
|
|
1536
|
-
return {
|
|
1537
|
-
error: `mcp call requires a dotted tool selector. Use mcp call ${rawSelector}.${splitTool} key=value or --json for structured arguments.`
|
|
1538
|
-
};
|
|
1539
|
-
}
|
|
1540
|
-
return {
|
|
1541
|
-
error: "mcp call requires an exact session tool selector: mcp call <server>.<tool> key=value ..."
|
|
1542
|
-
};
|
|
1543
|
-
}
|
|
1544
|
-
if (/^(?:https?:\/\/|[^/]+\/)/i.test(selector.server)) {
|
|
1545
|
-
return { error: "mcp call accepts only tools materialized for this recipe session; URLs and ad-hoc servers are unavailable." };
|
|
1546
|
-
}
|
|
1547
|
-
const targetError = validateExactTarget(policy, selector.server, selector.tool);
|
|
1548
|
-
if (targetError) return { error: targetError };
|
|
1549
|
-
const blocked = forbiddenFlag(args.slice(2));
|
|
1550
|
-
if (blocked === "--args") {
|
|
1551
|
-
return {
|
|
1552
|
-
error: "mcp call option '--args' was removed; use --json <object|-> for structured tool arguments."
|
|
1553
|
-
};
|
|
1554
|
-
}
|
|
1555
|
-
if (blocked) return { error: `mcp call option '${blocked}' is unavailable in recipe sessions.` };
|
|
1556
|
-
const syntaxError = callSyntaxError(args.slice(2));
|
|
1557
|
-
if (syntaxError) return { error: syntaxError };
|
|
1558
|
-
return {
|
|
1559
|
-
command: {
|
|
1560
|
-
args: withNoOAuth(args)
|
|
1561
|
-
}
|
|
1562
|
-
};
|
|
1563
|
-
}
|
|
1564
|
-
function createMcpCliSessionPolicy(session) {
|
|
1565
|
-
return {
|
|
1566
|
-
servers: new Map(
|
|
1567
|
-
session.servers.map((server) => [server.id, server])
|
|
1568
|
-
)
|
|
1569
|
-
};
|
|
1570
|
-
}
|
|
1571
|
-
function validateDelegatedMcpCommand(args, policy) {
|
|
1572
|
-
if (args[0] === "list") return validateList(args, policy);
|
|
1573
|
-
if (args[0] === "call") return validateCall(args, policy);
|
|
1574
|
-
return {
|
|
1575
|
-
error: args[0] === "auth" ? "Interactive authentication is unavailable in the agent MCP CLI. Ask the user to authenticate this MCP connection outside the agent session, then retry." : `mcp command '${args[0] ?? ""}' is unavailable in recipe sessions. Use mcp search, list, call, or run.`
|
|
1576
|
-
};
|
|
1577
|
-
}
|
|
1578
|
-
|
|
1579
|
-
// src/mcp/cli/core.ts
|
|
1580
|
-
var DEFAULT_RUN_TIMEOUT_MS = 12e4;
|
|
1581
|
-
var DEFAULT_TOOL_CALL_TIMEOUT_MS = 6e4;
|
|
1582
|
-
var DEFAULT_LIST_TIMEOUT_MS = 3e4;
|
|
1583
|
-
var DEFAULT_MAX_RUN_TOOL_CALLS = 100;
|
|
1584
|
-
var DEFAULT_MAX_CONCURRENT_TOOL_CALLS = 16;
|
|
1585
|
-
var MAX_SEARCH_DESCRIPTION_CHARS = 600;
|
|
1586
|
-
var MAX_SEARCH_CONTRACT_CHARS = 4e3;
|
|
1587
|
-
var CATALOG_LOCK_POLL_MS = 50;
|
|
1588
|
-
var CATALOG_LOCK_INCOMPLETE_GRACE_MS = 1e3;
|
|
1589
|
-
var MCP_SESSION_ENV2 = "PI_RECIPES_MCP_SESSION";
|
|
1590
|
-
var mcporterCliPromise;
|
|
1591
|
-
var callCatalogCache = /* @__PURE__ */ new WeakMap();
|
|
1592
|
-
function loadMcporterCli() {
|
|
1593
|
-
if (mcporterCliPromise) return mcporterCliPromise;
|
|
1594
|
-
const previousDisableAutorun = process.env.MCPORTER_DISABLE_AUTORUN;
|
|
1595
|
-
process.env.MCPORTER_DISABLE_AUTORUN = "1";
|
|
1596
|
-
mcporterCliPromise = import("./cli-4OQD3H4N.js").finally(() => {
|
|
1597
|
-
if (previousDisableAutorun === void 0) {
|
|
1598
|
-
delete process.env.MCPORTER_DISABLE_AUTORUN;
|
|
1599
|
-
} else {
|
|
1600
|
-
process.env.MCPORTER_DISABLE_AUTORUN = previousDisableAutorun;
|
|
1601
|
-
}
|
|
1602
|
-
});
|
|
1603
|
-
return mcporterCliPromise;
|
|
1604
|
-
}
|
|
1605
|
-
async function acquireRuntime() {
|
|
1606
|
-
const shared = currentMcpCommandContext()?.runtime;
|
|
1607
|
-
return shared ? { runtime: shared, owned: false } : { runtime: await createRuntime(), owned: true };
|
|
1608
|
-
}
|
|
1609
|
-
async function closeOwnedRuntime(runtime, owned) {
|
|
1610
|
-
if (owned) await runtime.close();
|
|
1611
|
-
}
|
|
1612
|
-
var McpRunUsageError = class extends Error {
|
|
1613
|
-
};
|
|
1614
|
-
var McpRunTimeoutError = class extends Error {
|
|
1615
|
-
outcome = "unknown";
|
|
1616
|
-
constructor(message) {
|
|
1617
|
-
super(message);
|
|
1618
|
-
this.name = "McpRunTimeoutError";
|
|
1619
|
-
}
|
|
1620
|
-
};
|
|
1621
|
-
var McpRemoteToolResultError = class extends Error {
|
|
1622
|
-
constructor(details) {
|
|
1623
|
-
super(details.message);
|
|
1624
|
-
this.details = details;
|
|
1625
|
-
this.name = "McpRemoteToolResultError";
|
|
1626
|
-
}
|
|
1627
|
-
details;
|
|
1628
|
-
};
|
|
1629
|
-
var McpRunToolError = class extends Error {
|
|
1630
|
-
constructor(server, tool, message, options) {
|
|
1631
|
-
super(message, options);
|
|
1632
|
-
this.server = server;
|
|
1633
|
-
this.tool = tool;
|
|
1634
|
-
this.name = "McpRunToolError";
|
|
1635
|
-
this.details = options?.details;
|
|
1636
|
-
this.code = options?.details?.code;
|
|
1637
|
-
this.retryable = options?.details?.retryable;
|
|
1638
|
-
this.action = options?.details?.action;
|
|
1639
|
-
this.outcome = options?.details?.outcome;
|
|
1640
|
-
}
|
|
1641
|
-
server;
|
|
1642
|
-
tool;
|
|
1643
|
-
kind = "tool_execution";
|
|
1644
|
-
details;
|
|
1645
|
-
code;
|
|
1646
|
-
retryable;
|
|
1647
|
-
action;
|
|
1648
|
-
outcome;
|
|
1649
|
-
};
|
|
1650
|
-
function isHelpArg(value) {
|
|
1651
|
-
return value === "--help" || value === "-h" || value === "help";
|
|
1652
|
-
}
|
|
1653
|
-
function readStdin() {
|
|
1654
|
-
const source = currentMcpCommandContext()?.stdin ?? input;
|
|
1655
|
-
source.setEncoding("utf8");
|
|
1656
|
-
return new Promise((resolve2, reject) => {
|
|
1657
|
-
let data = "";
|
|
1658
|
-
source.on("data", (chunk) => {
|
|
1659
|
-
data += chunk;
|
|
1660
|
-
});
|
|
1661
|
-
source.on("error", reject);
|
|
1662
|
-
source.on("end", () => resolve2(data));
|
|
1663
|
-
});
|
|
1664
|
-
}
|
|
1665
|
-
function checkedCallResult(callResult) {
|
|
1666
|
-
if (asRecord(callResult.raw).isError === true) {
|
|
1667
|
-
const parsed = callResult.json();
|
|
1668
|
-
const parsedRecord = asRecord(parsed);
|
|
1669
|
-
const parsedError = Object.prototype.hasOwnProperty.call(parsedRecord, "error") ? parsedRecord.error : parsedRecord;
|
|
1670
|
-
const errorObject = asRecord(parsedError);
|
|
1671
|
-
const message = typeof parsedError === "string" ? parsedError : typeof errorObject.message === "string" ? errorObject.message : callResult.text() ?? "MCP tool call failed.";
|
|
1672
|
-
throw new McpRemoteToolResultError({ ...errorObject, message });
|
|
1673
|
-
}
|
|
1674
|
-
return callResult;
|
|
1675
|
-
}
|
|
1676
|
-
function decodeCallResult(callResult, format, ref) {
|
|
1677
|
-
switch (format) {
|
|
1678
|
-
case "json": {
|
|
1679
|
-
const decoded = callResult.json();
|
|
1680
|
-
if (decoded === null && callResult.structuredContent() == null && callResult.text() != null) {
|
|
1681
|
-
const text = callResult.text().trim();
|
|
1682
|
-
const shown = text.length > 500 ? `${text.slice(0, 500)}\u2026` : text;
|
|
1683
|
-
throw new McpRunUsageError(
|
|
1684
|
-
`${ref} returned text, not JSON: ${shown} If plain text is this tool's documented response, call tools[${JSON.stringify(ref.split(".")[0])}][${JSON.stringify(ref.slice(ref.indexOf(".") + 1))}].text(args).`
|
|
1685
|
-
);
|
|
1686
|
-
}
|
|
1687
|
-
return decoded;
|
|
1688
|
-
}
|
|
1689
|
-
case "text":
|
|
1690
|
-
return callResult.text();
|
|
1691
|
-
case "markdown":
|
|
1692
|
-
return callResult.markdown();
|
|
1693
|
-
case "images":
|
|
1694
|
-
return callResult.images();
|
|
1695
|
-
case "content":
|
|
1696
|
-
return callResult.content();
|
|
1697
|
-
case "structuredContent":
|
|
1698
|
-
return callResult.structuredContent();
|
|
1699
|
-
case "raw":
|
|
1700
|
-
return callResult.raw;
|
|
1701
|
-
}
|
|
1702
|
-
}
|
|
1703
|
-
function validateRunToolArgs(server, tool, args) {
|
|
1704
|
-
const cliStyleKey = Object.keys(args).find((key) => key.includes(":=") || key.includes("="));
|
|
1705
|
-
if (!cliStyleKey) return;
|
|
1706
|
-
const suggestedKey = cliStyleKey.split(/:=|=/, 1)[0];
|
|
1707
|
-
throw new McpRunUsageError(
|
|
1708
|
-
`Invalid JavaScript argument key '${cliStyleKey}' for ${server}.${tool}. mcp run uses normal JavaScript objects: write { ${suggestedKey}: value }, not mcporter CLI key=value or key:=value syntax.`
|
|
1709
|
-
);
|
|
1710
|
-
}
|
|
1711
|
-
var ToolCallQueue = class {
|
|
1712
|
-
constructor(limit) {
|
|
1713
|
-
this.limit = limit;
|
|
1714
|
-
}
|
|
1715
|
-
limit;
|
|
1716
|
-
active = 0;
|
|
1717
|
-
waiting = [];
|
|
1718
|
-
cancelled;
|
|
1719
|
-
acquire() {
|
|
1720
|
-
if (this.cancelled !== void 0) return Promise.reject(this.cancelled);
|
|
1721
|
-
if (this.active < this.limit) {
|
|
1722
|
-
this.active += 1;
|
|
1723
|
-
return Promise.resolve(this.releaseHandle());
|
|
1724
|
-
}
|
|
1725
|
-
return new Promise((resolve2, reject) => this.waiting.push({ resolve: resolve2, reject }));
|
|
1726
|
-
}
|
|
1727
|
-
cancel(error) {
|
|
1728
|
-
if (this.cancelled !== void 0) return;
|
|
1729
|
-
this.cancelled = error;
|
|
1730
|
-
for (const waiter of this.waiting.splice(0)) waiter.reject(error);
|
|
1731
|
-
}
|
|
1732
|
-
releaseHandle() {
|
|
1733
|
-
let released = false;
|
|
1734
|
-
return () => {
|
|
1735
|
-
if (released) return;
|
|
1736
|
-
released = true;
|
|
1737
|
-
const next = this.waiting.shift();
|
|
1738
|
-
if (next && this.cancelled === void 0) {
|
|
1739
|
-
next.resolve(this.releaseHandle());
|
|
1740
|
-
return;
|
|
1741
|
-
}
|
|
1742
|
-
this.active -= 1;
|
|
1743
|
-
};
|
|
1744
|
-
}
|
|
1745
|
-
};
|
|
1746
|
-
function asRecord(value) {
|
|
1747
|
-
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1748
|
-
}
|
|
1749
|
-
function words(value) {
|
|
1750
|
-
return value.toLowerCase().split(/[^a-z0-9_/-]+/g).map((token) => token.trim()).filter(Boolean);
|
|
1751
|
-
}
|
|
1752
|
-
function toolProperties(tool) {
|
|
1753
|
-
const schema = asRecord(tool.input_schema);
|
|
1754
|
-
const properties = asRecord(schema.properties);
|
|
1755
|
-
return Object.entries(properties).map(([name, value]) => {
|
|
1756
|
-
const property = asRecord(value);
|
|
1757
|
-
const description = typeof property.description === "string" ? property.description : typeof property.title === "string" ? property.title : "";
|
|
1758
|
-
return { name, description };
|
|
1759
|
-
});
|
|
1760
|
-
}
|
|
1761
|
-
function toolRequired(tool) {
|
|
1762
|
-
const schema = asRecord(tool.input_schema);
|
|
1763
|
-
return Array.isArray(schema.required) ? schema.required.filter((item) => typeof item === "string") : [];
|
|
1764
|
-
}
|
|
1765
|
-
function includesTerm(value, term) {
|
|
1766
|
-
return value.toLowerCase().includes(term.toLowerCase());
|
|
1767
|
-
}
|
|
1768
|
-
function scoreTool(opts) {
|
|
1769
|
-
const ref = `${opts.serverId}.${opts.tool.name}`;
|
|
1770
|
-
const description = opts.tool.description ?? "";
|
|
1771
|
-
const properties = toolProperties(opts.tool);
|
|
1772
|
-
const propertyNames = properties.map((property) => property.name).join(" ");
|
|
1773
|
-
const propertyDescriptions = properties.map((property) => property.description).join(" ");
|
|
1774
|
-
const searchable = [
|
|
1775
|
-
ref,
|
|
1776
|
-
opts.serverId,
|
|
1777
|
-
opts.serverName,
|
|
1778
|
-
opts.tool.name,
|
|
1779
|
-
description,
|
|
1780
|
-
propertyNames,
|
|
1781
|
-
propertyDescriptions
|
|
1782
|
-
].join("\n");
|
|
1783
|
-
if (opts.regex) return opts.regex.test(searchable) ? 100 : 0;
|
|
1784
|
-
const query = opts.query.toLowerCase();
|
|
1785
|
-
const toolName = opts.tool.name.toLowerCase();
|
|
1786
|
-
const refName = ref.toLowerCase();
|
|
1787
|
-
let score = 0;
|
|
1788
|
-
if (refName === query) score += 500;
|
|
1789
|
-
if (toolName === query) score += 300;
|
|
1790
|
-
if (refName.includes(query)) score += 120;
|
|
1791
|
-
if (toolName.includes(query)) score += 100;
|
|
1792
|
-
if (description.toLowerCase().includes(query)) score += 60;
|
|
1793
|
-
const toolNameTokens = new Set(words(opts.tool.name));
|
|
1794
|
-
const serverTokens = new Set(words(`${opts.serverId} ${opts.serverName}`));
|
|
1795
|
-
const descriptionText2 = description.toLowerCase();
|
|
1796
|
-
const propertyNameTokens = new Set(words(propertyNames));
|
|
1797
|
-
const propertyDescriptionText = propertyDescriptions.toLowerCase();
|
|
1798
|
-
for (const term of opts.queryTerms) {
|
|
1799
|
-
if (toolNameTokens.has(term)) score += 40;
|
|
1800
|
-
else if (includesTerm(opts.tool.name, term)) score += 20;
|
|
1801
|
-
if (descriptionText2.includes(term)) score += 16;
|
|
1802
|
-
if (propertyNameTokens.has(term)) score += 12;
|
|
1803
|
-
else if (includesTerm(propertyNames, term)) score += 6;
|
|
1804
|
-
if (propertyDescriptionText.includes(term)) score += 6;
|
|
1805
|
-
if (serverTokens.has(term)) score += 4;
|
|
1806
|
-
}
|
|
1807
|
-
return score;
|
|
1808
|
-
}
|
|
1809
|
-
function exampleValue2(name) {
|
|
1810
|
-
if (/^(q|query|search)$/i.test(name)) return `="example query"`;
|
|
1811
|
-
if (/limit|count|max/i.test(name)) return "=10";
|
|
1812
|
-
if (/^(id|.*Id)$/i.test(name)) return '="<id>"';
|
|
1813
|
-
return '="<value>"';
|
|
1814
|
-
}
|
|
1815
|
-
function callExample2(serverId, tool) {
|
|
1816
|
-
const required = toolRequired(tool);
|
|
1817
|
-
const args = required.slice(0, 4).map((name) => `${name}${exampleValue2(name)}`);
|
|
1818
|
-
return ["mcp call", `${serverId}.${tool.name}`, ...args].join(" ");
|
|
1819
|
-
}
|
|
1820
|
-
function searchMcpTools(session, query, opts = {}) {
|
|
1821
|
-
const trimmed = query.trim();
|
|
1822
|
-
if (!trimmed) return [];
|
|
1823
|
-
const regex = opts.regex ? new RegExp(trimmed, "i") : void 0;
|
|
1824
|
-
const queryTerms = words(trimmed);
|
|
1825
|
-
const matches = [];
|
|
1826
|
-
for (const server of session.servers) {
|
|
1827
|
-
for (const tool of server.catalog ?? []) {
|
|
1828
|
-
const score = scoreTool({
|
|
1829
|
-
query: trimmed,
|
|
1830
|
-
queryTerms,
|
|
1831
|
-
regex,
|
|
1832
|
-
serverId: server.id,
|
|
1833
|
-
serverName: server.name ?? "",
|
|
1834
|
-
tool
|
|
1835
|
-
});
|
|
1836
|
-
if (score <= 0) continue;
|
|
1837
|
-
const ref = `${server.id}.${tool.name}`;
|
|
1838
|
-
matches.push({
|
|
1839
|
-
ref,
|
|
1840
|
-
server: server.id,
|
|
1841
|
-
tool: tool.name,
|
|
1842
|
-
description: (tool.description ?? "").length > MAX_SEARCH_DESCRIPTION_CHARS ? `${(tool.description ?? "").slice(0, MAX_SEARCH_DESCRIPTION_CHARS - 14).trimEnd()}\u2026 [truncated]` : tool.description ?? "",
|
|
1843
|
-
required: toolRequired(tool),
|
|
1844
|
-
score,
|
|
1845
|
-
inspect: `mcp list ${ref} --schema`,
|
|
1846
|
-
call: callExample2(server.id, tool),
|
|
1847
|
-
...tool.annotations ? { annotations: tool.annotations } : {}
|
|
1848
|
-
});
|
|
1849
|
-
}
|
|
1850
|
-
}
|
|
1851
|
-
return matches.sort((a, b) => b.score - a.score || a.ref.localeCompare(b.ref)).slice(0, opts.limit ?? 5);
|
|
1852
|
-
}
|
|
1853
|
-
async function readSession() {
|
|
1854
|
-
const path = sessionPolicyPath();
|
|
1855
|
-
const data = await readFile(path, "utf8");
|
|
1856
|
-
const parsed = JSON.parse(data);
|
|
1857
|
-
if (parsed.version !== 1 || !Array.isArray(parsed.servers)) {
|
|
1858
|
-
throw new Error(`Invalid MCP session policy at ${path}`);
|
|
1859
|
-
}
|
|
1860
|
-
return parsed;
|
|
1861
|
-
}
|
|
1862
|
-
function sessionPolicyPath() {
|
|
1863
|
-
const workspacePath = defaultMcpSessionPath(sessionRoot());
|
|
1864
|
-
return existsSync(workspacePath) ? workspacePath : process.env[MCP_SESSION_ENV2] || workspacePath;
|
|
1865
|
-
}
|
|
1866
|
-
function sessionMcporterConfigPath() {
|
|
1867
|
-
const workspacePath = defaultMcporterConfigPath(sessionRoot());
|
|
1868
|
-
return existsSync(workspacePath) ? workspacePath : process.env.MCPORTER_CONFIG || workspacePath;
|
|
1869
|
-
}
|
|
1870
|
-
function sessionRoot() {
|
|
1871
|
-
return process.env.PI_RECIPES_MCP_SESSION_ROOT || process.cwd();
|
|
1872
|
-
}
|
|
1873
|
-
function pinSessionMcporterConfig() {
|
|
1874
|
-
process.env.MCPORTER_CONFIG = sessionMcporterConfigPath();
|
|
1875
|
-
}
|
|
1876
|
-
async function sessionCliPolicy() {
|
|
1877
|
-
return createMcpCliSessionPolicy(await readSession());
|
|
1878
|
-
}
|
|
1879
|
-
function catalogFingerprint(server) {
|
|
1880
|
-
return createHash("sha256").update(
|
|
1881
|
-
JSON.stringify({
|
|
1882
|
-
id: server.id,
|
|
1883
|
-
baseUrl: server.base_url,
|
|
1884
|
-
packageTools: server.package_tools,
|
|
1885
|
-
agentTools: server.agent_tools
|
|
1886
|
-
})
|
|
1887
|
-
).digest("hex").slice(0, 20);
|
|
1888
|
-
}
|
|
1889
|
-
function catalogCachePath(server) {
|
|
1890
|
-
return join2(
|
|
1891
|
-
sessionRoot(),
|
|
1892
|
-
".pi",
|
|
1893
|
-
"mcp-catalogs",
|
|
1894
|
-
`${server.id}-${catalogFingerprint(server)}.json`
|
|
1895
|
-
);
|
|
1896
|
-
}
|
|
1897
|
-
async function readCachedCatalog(server) {
|
|
1898
|
-
if (server.catalog) return server.catalog;
|
|
1899
|
-
try {
|
|
1900
|
-
const parsed = JSON.parse(
|
|
1901
|
-
await readFile(catalogCachePath(server), "utf8")
|
|
1902
|
-
);
|
|
1903
|
-
return Array.isArray(parsed.tools) ? parsed.tools : null;
|
|
1904
|
-
} catch {
|
|
1905
|
-
return null;
|
|
1906
|
-
}
|
|
1907
|
-
}
|
|
1908
|
-
async function writeCachedCatalog(server, tools) {
|
|
1909
|
-
const directory = join2(sessionRoot(), ".pi", "mcp-catalogs");
|
|
1910
|
-
await mkdir(directory, { recursive: true });
|
|
1911
|
-
const path = catalogCachePath(server);
|
|
1912
|
-
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
1913
|
-
await writeFile(temporary, `${JSON.stringify({ tools })}
|
|
1914
|
-
`, { mode: 384 });
|
|
1915
|
-
await rename(temporary, path);
|
|
1916
|
-
}
|
|
1917
|
-
function processExists(pid) {
|
|
1918
|
-
try {
|
|
1919
|
-
process.kill(pid, 0);
|
|
1920
|
-
return true;
|
|
1921
|
-
} catch (error) {
|
|
1922
|
-
return error.code === "EPERM";
|
|
1923
|
-
}
|
|
1924
|
-
}
|
|
1925
|
-
async function catalogLockIsStale(path, timeoutMs) {
|
|
1926
|
-
try {
|
|
1927
|
-
const owner = JSON.parse(await readFile(path, "utf8"));
|
|
1928
|
-
if (typeof owner.pid === "number" && Number.isInteger(owner.pid) && owner.pid > 0 && typeof owner.createdAt === "number" && Number.isFinite(owner.createdAt)) {
|
|
1929
|
-
return !processExists(owner.pid) || Date.now() - owner.createdAt > timeoutMs + CATALOG_LOCK_INCOMPLETE_GRACE_MS;
|
|
1930
|
-
}
|
|
1931
|
-
} catch (error) {
|
|
1932
|
-
if (error.code === "ENOENT") return false;
|
|
1933
|
-
}
|
|
1934
|
-
try {
|
|
1935
|
-
const metadata = await stat(path);
|
|
1936
|
-
return Date.now() - metadata.mtimeMs > CATALOG_LOCK_INCOMPLETE_GRACE_MS;
|
|
1937
|
-
} catch {
|
|
1938
|
-
return false;
|
|
1939
|
-
}
|
|
1940
|
-
}
|
|
1941
|
-
async function acquireCatalogLock(path) {
|
|
1942
|
-
let handle;
|
|
1943
|
-
try {
|
|
1944
|
-
handle = await open(path, "wx", 384);
|
|
1945
|
-
} catch (error) {
|
|
1946
|
-
if (error.code === "EEXIST") return false;
|
|
1947
|
-
throw error;
|
|
1948
|
-
}
|
|
1949
|
-
try {
|
|
1950
|
-
await handle.writeFile(
|
|
1951
|
-
`${JSON.stringify({ pid: process.pid, createdAt: Date.now() })}
|
|
1952
|
-
`
|
|
1953
|
-
);
|
|
1954
|
-
} catch (error) {
|
|
1955
|
-
await handle.close();
|
|
1956
|
-
await rm(path, { force: true });
|
|
1957
|
-
throw error;
|
|
1958
|
-
}
|
|
1959
|
-
await handle.close();
|
|
1960
|
-
return true;
|
|
1961
|
-
}
|
|
1962
|
-
function catalogEntry(tool) {
|
|
1963
|
-
const annotations = asRecord(tool).annotations;
|
|
1964
|
-
return {
|
|
1965
|
-
name: tool.name,
|
|
1966
|
-
...tool.description ? { description: tool.description } : {},
|
|
1967
|
-
...tool.inputSchema && typeof tool.inputSchema === "object" ? { input_schema: tool.inputSchema } : {},
|
|
1968
|
-
...tool.outputSchema && typeof tool.outputSchema === "object" ? { output_schema: tool.outputSchema } : {},
|
|
1969
|
-
...annotations && typeof annotations === "object" ? { annotations } : {}
|
|
1970
|
-
};
|
|
1971
|
-
}
|
|
1972
|
-
async function discoverServerCatalog(runtime, server, timeoutMs) {
|
|
1973
|
-
const cached = await readCachedCatalog(server);
|
|
1974
|
-
if (cached) return cached;
|
|
1975
|
-
const lock = `${catalogCachePath(server)}.lock`;
|
|
1976
|
-
await mkdir(dirname2(lock), { recursive: true });
|
|
1977
|
-
let ownsLock = false;
|
|
1978
|
-
const deadline = Date.now() + timeoutMs;
|
|
1979
|
-
while (!ownsLock && Date.now() < deadline) {
|
|
1980
|
-
ownsLock = await acquireCatalogLock(lock);
|
|
1981
|
-
if (ownsLock) break;
|
|
1982
|
-
const populated = await readCachedCatalog(server);
|
|
1983
|
-
if (populated) return populated;
|
|
1984
|
-
if (await catalogLockIsStale(lock, timeoutMs)) {
|
|
1985
|
-
await rm(lock, { force: true });
|
|
1986
|
-
continue;
|
|
1987
|
-
}
|
|
1988
|
-
const remainingMs = deadline - Date.now();
|
|
1989
|
-
if (remainingMs > 0) {
|
|
1990
|
-
await delay(Math.min(CATALOG_LOCK_POLL_MS, remainingMs));
|
|
1991
|
-
}
|
|
1992
|
-
}
|
|
1993
|
-
if (!ownsLock) {
|
|
1994
|
-
const populated = await readCachedCatalog(server);
|
|
1995
|
-
if (populated) return populated;
|
|
1996
|
-
throw new Error(
|
|
1997
|
-
`timed out after ${timeoutMs}ms waiting for MCP catalog discovery for '${server.id}'`
|
|
1998
|
-
);
|
|
1999
|
-
}
|
|
2000
|
-
try {
|
|
2001
|
-
const populated = await readCachedCatalog(server);
|
|
2002
|
-
if (populated) return populated;
|
|
2003
|
-
const remainingMs = deadline - Date.now();
|
|
2004
|
-
if (remainingMs <= 0) {
|
|
2005
|
-
throw new Error(
|
|
2006
|
-
`timed out after ${timeoutMs}ms before MCP catalog discovery for '${server.id}' started`
|
|
2007
|
-
);
|
|
2008
|
-
}
|
|
2009
|
-
const discovered = await withListTimeout(
|
|
2010
|
-
runtime.listTools(server.id, {
|
|
2011
|
-
includeSchema: true,
|
|
2012
|
-
autoAuthorize: false,
|
|
2013
|
-
allowCachedAuth: true,
|
|
2014
|
-
disableOAuth: true
|
|
2015
|
-
}),
|
|
2016
|
-
remainingMs
|
|
2017
|
-
);
|
|
2018
|
-
const tools = filterMcpCatalog(server, discovered.map(catalogEntry));
|
|
2019
|
-
await writeCachedCatalog(server, tools);
|
|
2020
|
-
return tools;
|
|
2021
|
-
} finally {
|
|
2022
|
-
if (ownsLock) await rm(lock, { recursive: true, force: true });
|
|
2023
|
-
}
|
|
2024
|
-
}
|
|
2025
|
-
async function discoverMcpCatalogs(runtime, timeoutMs) {
|
|
2026
|
-
const session = await readSession();
|
|
2027
|
-
return await Promise.all(
|
|
2028
|
-
session.servers.map(async (server) => {
|
|
2029
|
-
try {
|
|
2030
|
-
return {
|
|
2031
|
-
id: server.id,
|
|
2032
|
-
name: server.name,
|
|
2033
|
-
tools: await discoverServerCatalog(runtime, server, timeoutMs)
|
|
2034
|
-
};
|
|
2035
|
-
} catch (error) {
|
|
2036
|
-
return {
|
|
2037
|
-
id: server.id,
|
|
2038
|
-
name: server.name,
|
|
2039
|
-
tools: [],
|
|
2040
|
-
error: error instanceof Error ? error.message : String(error)
|
|
2041
|
-
};
|
|
2042
|
-
}
|
|
2043
|
-
})
|
|
2044
|
-
);
|
|
2045
|
-
}
|
|
2046
|
-
var SEARCH_OPTIONS = {
|
|
2047
|
-
limit: { type: "string" },
|
|
2048
|
-
regex: { type: "boolean" }
|
|
2049
|
-
};
|
|
2050
|
-
function optionName(value) {
|
|
2051
|
-
const equals = value.indexOf("=");
|
|
2052
|
-
return equals === -1 ? value : value.slice(0, equals);
|
|
2053
|
-
}
|
|
2054
|
-
function parseSearchArgs(args) {
|
|
2055
|
-
if (args.some((arg) => optionName(arg) === "--json")) {
|
|
2056
|
-
return { error: "mcp search metadata is compact text; JSON is reserved for tool results." };
|
|
2057
|
-
}
|
|
2058
|
-
let parsed;
|
|
2059
|
-
try {
|
|
2060
|
-
parsed = parseArgs({ args, options: SEARCH_OPTIONS, allowPositionals: true });
|
|
2061
|
-
} catch (error) {
|
|
2062
|
-
if (error.code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE") {
|
|
2063
|
-
const index = args.findIndex((arg) => optionName(arg) === "--limit");
|
|
2064
|
-
const flag = args[index] ?? "";
|
|
2065
|
-
const raw = flag.includes("=") ? flag.slice(flag.indexOf("=") + 1) : args[index + 1] ?? "";
|
|
2066
|
-
return { error: `--limit expects a positive integer, got '${raw}'.` };
|
|
2067
|
-
}
|
|
2068
|
-
const unknown = args.find(
|
|
2069
|
-
(arg) => arg.startsWith("-") && !(optionName(arg).slice(2) in SEARCH_OPTIONS)
|
|
2070
|
-
);
|
|
2071
|
-
return { error: `Unknown mcp search option '${unknown}'.` };
|
|
2072
|
-
}
|
|
2073
|
-
const { values, positionals } = parsed;
|
|
2074
|
-
let limit = 5;
|
|
2075
|
-
if (values.limit !== void 0) {
|
|
2076
|
-
const value = Number(values.limit);
|
|
2077
|
-
if (!Number.isInteger(value) || value <= 0) {
|
|
2078
|
-
return { error: `--limit expects a positive integer, got '${values.limit}'.` };
|
|
2079
|
-
}
|
|
2080
|
-
limit = value;
|
|
2081
|
-
}
|
|
2082
|
-
return { query: positionals.join(" "), limit, regex: values.regex === true };
|
|
2083
|
-
}
|
|
2084
|
-
function renderSearchResults(matches, catalogs) {
|
|
2085
|
-
let budget = MAX_SEARCH_CONTRACT_CHARS;
|
|
2086
|
-
let shortened = false;
|
|
2087
|
-
const blocks = matches.map((match, index) => {
|
|
2088
|
-
const entry = catalogs.get(match.server)?.find((tool2) => tool2.name === match.tool);
|
|
2089
|
-
if (!entry) return `${match.ref}${match.description ? ` \u2014 ${match.description}` : ""}
|
|
2090
|
-
`;
|
|
2091
|
-
const tool = {
|
|
2092
|
-
name: entry.name,
|
|
2093
|
-
description: entry.description,
|
|
2094
|
-
inputSchema: entry.input_schema,
|
|
2095
|
-
outputSchema: entry.output_schema,
|
|
2096
|
-
annotations: entry.annotations
|
|
2097
|
-
};
|
|
2098
|
-
const contract = renderToolContract(match.server, tool);
|
|
2099
|
-
if (!shortened && (index === 0 || contract.length <= budget)) {
|
|
2100
|
-
budget -= contract.length;
|
|
2101
|
-
return contract;
|
|
2102
|
-
}
|
|
2103
|
-
shortened = true;
|
|
2104
|
-
return `${renderToolSignature(match.server, tool)}
|
|
2105
|
-
`;
|
|
2106
|
-
});
|
|
2107
|
-
return blocks.join("\n") + (shortened ? "\nThe rest are signatures: `mcp list <server.tool> --schema` shows one in full.\n" : "");
|
|
2108
|
-
}
|
|
2109
|
-
async function searchCatalog(args) {
|
|
2110
|
-
const parsed = parseSearchArgs(args);
|
|
2111
|
-
if (parsed.error !== void 0) {
|
|
2112
|
-
stderr.write(`${parsed.error}
|
|
2113
|
-
`);
|
|
2114
|
-
return 2;
|
|
2115
|
-
}
|
|
2116
|
-
const { query, limit, regex } = parsed;
|
|
2117
|
-
if (!query.trim()) {
|
|
2118
|
-
stderr.write('Usage: mcp search "what you need" [--limit N] [--regex]\n');
|
|
2119
|
-
return 2;
|
|
2120
|
-
}
|
|
2121
|
-
let matches;
|
|
2122
|
-
const catalogs = /* @__PURE__ */ new Map();
|
|
2123
|
-
const { runtime, owned } = await acquireRuntime();
|
|
2124
|
-
try {
|
|
2125
|
-
const session = await readSession();
|
|
2126
|
-
const results = await Promise.all(
|
|
2127
|
-
session.servers.map(async (server) => {
|
|
2128
|
-
try {
|
|
2129
|
-
return {
|
|
2130
|
-
catalog: await discoverServerCatalog(
|
|
2131
|
-
runtime,
|
|
2132
|
-
server,
|
|
2133
|
-
DEFAULT_LIST_TIMEOUT_MS
|
|
2134
|
-
)
|
|
2135
|
-
};
|
|
2136
|
-
} catch (error) {
|
|
2137
|
-
return { error };
|
|
2138
|
-
}
|
|
2139
|
-
})
|
|
2140
|
-
);
|
|
2141
|
-
const failed = results.filter((result) => "error" in result).length;
|
|
2142
|
-
if (failed > 0) {
|
|
2143
|
-
stderr.write(
|
|
2144
|
-
`mcp search: ${failed} of ${results.length} server(s) unavailable; searched the remaining catalogs.
|
|
2145
|
-
`
|
|
2146
|
-
);
|
|
2147
|
-
}
|
|
2148
|
-
session.servers.forEach((server, index) => {
|
|
2149
|
-
const result = results[index];
|
|
2150
|
-
if ("catalog" in result && result.catalog) catalogs.set(server.id, result.catalog);
|
|
2151
|
-
});
|
|
2152
|
-
matches = searchMcpTools(
|
|
2153
|
-
{
|
|
2154
|
-
...session,
|
|
2155
|
-
servers: session.servers.map((server, index) => ({
|
|
2156
|
-
...server,
|
|
2157
|
-
catalog: "catalog" in results[index] ? results[index].catalog : []
|
|
2158
|
-
}))
|
|
2159
|
-
},
|
|
2160
|
-
query,
|
|
2161
|
-
{ limit, regex }
|
|
2162
|
-
);
|
|
2163
|
-
} catch (err) {
|
|
2164
|
-
if (regex && err instanceof SyntaxError) {
|
|
2165
|
-
stderr.write(`Invalid --regex pattern: ${query}
|
|
2166
|
-
`);
|
|
2167
|
-
return 2;
|
|
2168
|
-
}
|
|
2169
|
-
throw err;
|
|
2170
|
-
} finally {
|
|
2171
|
-
await closeOwnedRuntime(runtime, owned);
|
|
2172
|
-
}
|
|
2173
|
-
if (matches.length === 0) {
|
|
2174
|
-
stdout.write(`No matching tools found for "${query}".
|
|
2175
|
-
`);
|
|
2176
|
-
stdout.write("Try broader or alternate terms.\n");
|
|
2177
|
-
stdout.write(
|
|
2178
|
-
"`mcp list <server> --schema` shows every tool on one server.\n"
|
|
2179
|
-
);
|
|
2180
|
-
return 0;
|
|
2181
|
-
}
|
|
2182
|
-
stdout.write(renderSearchResults(matches, catalogs));
|
|
2183
|
-
return 0;
|
|
2184
|
-
}
|
|
2185
|
-
function exactToolTarget(value) {
|
|
2186
|
-
if (!value) return null;
|
|
2187
|
-
const dot = value.indexOf(".");
|
|
2188
|
-
if (dot < 1 || dot === value.length - 1) return null;
|
|
2189
|
-
return { server: value.slice(0, dot), tool: value.slice(dot + 1) };
|
|
2190
|
-
}
|
|
2191
|
-
function catalogTool(session, server, tool) {
|
|
2192
|
-
return session.servers?.find((entry) => entry.id === server)?.catalog?.find((entry) => entry.name === tool);
|
|
2193
|
-
}
|
|
2194
|
-
function toolCount(count) {
|
|
2195
|
-
return `${count} tool${count === 1 ? "" : "s"}`;
|
|
2196
|
-
}
|
|
2197
|
-
function parseListTimeoutMs(args) {
|
|
2198
|
-
const configured = process.env.MCPORTER_LIST_TIMEOUT;
|
|
2199
|
-
let raw = configured && /^[1-9]\d*$/.test(configured) ? configured : String(DEFAULT_LIST_TIMEOUT_MS);
|
|
2200
|
-
const { values } = parseArgs({
|
|
2201
|
-
args: [...args.slice(1)],
|
|
2202
|
-
options: { timeout: { type: "string" } },
|
|
2203
|
-
strict: false,
|
|
2204
|
-
allowPositionals: true
|
|
2205
|
-
});
|
|
2206
|
-
if (values.timeout !== void 0) {
|
|
2207
|
-
if (typeof values.timeout !== "string" || values.timeout === "") {
|
|
2208
|
-
return "mcp list: --timeout requires a value.";
|
|
2209
|
-
}
|
|
2210
|
-
raw = values.timeout;
|
|
2211
|
-
}
|
|
2212
|
-
if (!/^[1-9]\d*$/.test(raw)) {
|
|
2213
|
-
return "mcp list: --timeout must be a positive integer (milliseconds).";
|
|
2214
|
-
}
|
|
2215
|
-
const timeout = Number(raw);
|
|
2216
|
-
return Number.isSafeInteger(timeout) ? timeout : "mcp list: --timeout must be a positive integer (milliseconds).";
|
|
2217
|
-
}
|
|
2218
|
-
function withListTimeout(promise, timeoutMs) {
|
|
2219
|
-
return new Promise((resolve2, reject) => {
|
|
2220
|
-
const timer = setTimeout(
|
|
2221
|
-
() => reject(new Error(`timed out after ${timeoutMs}ms`)),
|
|
2222
|
-
timeoutMs
|
|
2223
|
-
);
|
|
2224
|
-
promise.then(
|
|
2225
|
-
(value) => {
|
|
2226
|
-
clearTimeout(timer);
|
|
2227
|
-
resolve2(value);
|
|
2228
|
-
},
|
|
2229
|
-
(error) => {
|
|
2230
|
-
clearTimeout(timer);
|
|
2231
|
-
reject(error);
|
|
2232
|
-
}
|
|
2233
|
-
);
|
|
2234
|
-
});
|
|
2235
|
-
}
|
|
2236
|
-
function aggregateListExitCode(hadFailure, args) {
|
|
2237
|
-
return hadFailure && (args.includes("--quiet") || args.includes("--exit-code")) ? 1 : 0;
|
|
2238
|
-
}
|
|
2239
|
-
function writeCompactListError(error) {
|
|
2240
|
-
const filter = createDelegatedErrorFilter((text) => stderr.write(text));
|
|
2241
|
-
const message = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
2242
|
-
filter.push(`mcp list: ${message.endsWith("\n") ? message : `${message}
|
|
2243
|
-
`}`);
|
|
2244
|
-
filter.flush();
|
|
2245
|
-
}
|
|
2246
|
-
var LIST_OPTIONS = {
|
|
2247
|
-
"all-parameters": { type: "boolean" },
|
|
2248
|
-
"exit-code": { type: "boolean" },
|
|
2249
|
-
"no-oauth": { type: "boolean" },
|
|
2250
|
-
quiet: { type: "boolean" },
|
|
2251
|
-
schema: { type: "boolean" },
|
|
2252
|
-
status: { type: "boolean" },
|
|
2253
|
-
timeout: { type: "string" },
|
|
2254
|
-
verbose: { type: "boolean" }
|
|
2255
|
-
};
|
|
2256
|
-
var LIST_BOOLEAN_FLAGS = new Set(
|
|
2257
|
-
Object.entries(LIST_OPTIONS).filter(([, spec]) => spec.type === "boolean").map(([name]) => name)
|
|
2258
|
-
);
|
|
2259
|
-
function isValidListOption(arg) {
|
|
2260
|
-
const name = optionName(arg).slice(2);
|
|
2261
|
-
if (!(name in LIST_OPTIONS)) return false;
|
|
2262
|
-
return !(arg.includes("=") && LIST_BOOLEAN_FLAGS.has(name));
|
|
2263
|
-
}
|
|
2264
|
-
function compactListArgumentError(args) {
|
|
2265
|
-
const rest = args.slice(1);
|
|
2266
|
-
const target = rest[0] !== void 0 && !rest[0].startsWith("-");
|
|
2267
|
-
const options = target ? rest.slice(1) : rest;
|
|
2268
|
-
try {
|
|
2269
|
-
const { positionals } = parseArgs({
|
|
2270
|
-
args: [...options],
|
|
2271
|
-
options: LIST_OPTIONS,
|
|
2272
|
-
allowPositionals: true
|
|
2273
|
-
});
|
|
2274
|
-
if (positionals.length > 0) {
|
|
2275
|
-
return `Unexpected mcp list argument '${positionals[0]}'.`;
|
|
2276
|
-
}
|
|
2277
|
-
return void 0;
|
|
2278
|
-
} catch {
|
|
2279
|
-
const offending = options.find(
|
|
2280
|
-
(arg) => arg.startsWith("-") && !isValidListOption(arg)
|
|
2281
|
-
);
|
|
2282
|
-
return offending ? `Unknown mcp list option '${offending}'.` : void 0;
|
|
2283
|
-
}
|
|
2284
|
-
}
|
|
2285
|
-
async function compactList(args) {
|
|
2286
|
-
if (args.includes("--json")) {
|
|
2287
|
-
stderr.write("mcp list metadata is compact text; JSON is reserved for tool results.\n");
|
|
2288
|
-
return 2;
|
|
2289
|
-
}
|
|
2290
|
-
const argumentError = compactListArgumentError(args);
|
|
2291
|
-
if (argumentError) {
|
|
2292
|
-
stderr.write(`${argumentError}
|
|
2293
|
-
`);
|
|
2294
|
-
return 2;
|
|
2295
|
-
}
|
|
2296
|
-
const target = args[1] && !args[1].startsWith("-") ? args[1] : void 0;
|
|
2297
|
-
const schema = args.includes("--schema");
|
|
2298
|
-
const status = args.includes("--status");
|
|
2299
|
-
const verbose = args.includes("--verbose");
|
|
2300
|
-
const allParameters = args.includes("--all-parameters");
|
|
2301
|
-
const quiet = args.includes("--quiet");
|
|
2302
|
-
const timeout = parseListTimeoutMs(args);
|
|
2303
|
-
if (typeof timeout === "string") {
|
|
2304
|
-
stderr.write(`${timeout}
|
|
2305
|
-
`);
|
|
2306
|
-
return 2;
|
|
2307
|
-
}
|
|
2308
|
-
if (schema && !target) {
|
|
2309
|
-
stderr.write("mcp list --schema requires a server or one exact tool: mcp list <server>[.<tool>] --schema\n");
|
|
2310
|
-
return 2;
|
|
2311
|
-
}
|
|
2312
|
-
const session = await readSession();
|
|
2313
|
-
if (!target) {
|
|
2314
|
-
const { runtime: runtime2, owned: owned2 } = await acquireRuntime();
|
|
2315
|
-
try {
|
|
2316
|
-
const results = await Promise.all(
|
|
2317
|
-
session.servers.map(async (server2) => {
|
|
2318
|
-
try {
|
|
2319
|
-
const tools = await discoverServerCatalog(runtime2, server2, timeout);
|
|
2320
|
-
return { server: server2, tools };
|
|
2321
|
-
} catch (error) {
|
|
2322
|
-
return { server: server2, error };
|
|
2323
|
-
}
|
|
2324
|
-
})
|
|
2325
|
-
);
|
|
2326
|
-
let hadFailure = false;
|
|
2327
|
-
for (const result of results) {
|
|
2328
|
-
if ("error" in result) {
|
|
2329
|
-
hadFailure = true;
|
|
2330
|
-
if (!quiet) stdout.write(`${result.server.id} \u2014 unavailable
|
|
2331
|
-
`);
|
|
2332
|
-
} else if (!quiet) {
|
|
2333
|
-
stdout.write(
|
|
2334
|
-
`${result.server.id} \u2014 ${toolCount(result.tools.length)}
|
|
2335
|
-
`
|
|
2336
|
-
);
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
2339
|
-
return aggregateListExitCode(hadFailure, args);
|
|
2340
|
-
} finally {
|
|
2341
|
-
await closeOwnedRuntime(runtime2, owned2);
|
|
2342
|
-
}
|
|
2343
|
-
}
|
|
2344
|
-
const exact = exactToolTarget(target);
|
|
2345
|
-
const server = exact?.server ?? target;
|
|
2346
|
-
const { runtime, owned } = await acquireRuntime();
|
|
2347
|
-
try {
|
|
2348
|
-
const sessionServer = session.servers.find((entry) => entry.id === server);
|
|
2349
|
-
if (!sessionServer) {
|
|
2350
|
-
stderr.write(`MCP server '${server}' is not available in this session.
|
|
2351
|
-
`);
|
|
2352
|
-
return 1;
|
|
2353
|
-
}
|
|
2354
|
-
const catalog = await discoverServerCatalog(runtime, sessionServer, timeout);
|
|
2355
|
-
const tools = catalog.map((tool) => ({
|
|
2356
|
-
name: tool.name,
|
|
2357
|
-
description: tool.description,
|
|
2358
|
-
inputSchema: tool.input_schema,
|
|
2359
|
-
outputSchema: tool.output_schema,
|
|
2360
|
-
annotations: tool.annotations
|
|
2361
|
-
}));
|
|
2362
|
-
if (quiet) return 0;
|
|
2363
|
-
if (status) {
|
|
2364
|
-
stdout.write(`${server} ok \u2014 ${toolCount(tools.length)}
|
|
2365
|
-
`);
|
|
2366
|
-
return 0;
|
|
2367
|
-
}
|
|
2368
|
-
const selected = exact ? tools.filter((tool) => tool.name === exact.tool) : tools;
|
|
2369
|
-
if (exact && selected.length === 0) {
|
|
2370
|
-
stderr.write(`Tool '${exact.tool}' is not available on server '${server}'.
|
|
2371
|
-
`);
|
|
2372
|
-
return 1;
|
|
2373
|
-
}
|
|
2374
|
-
if (schema) {
|
|
2375
|
-
const withCatalog = {
|
|
2376
|
-
...session,
|
|
2377
|
-
servers: session.servers.map(
|
|
2378
|
-
(entry) => entry.id === server ? { ...entry, catalog } : entry
|
|
2379
|
-
)
|
|
2380
|
-
};
|
|
2381
|
-
stdout.write(
|
|
2382
|
-
selected.map(
|
|
2383
|
-
(tool) => renderToolContract(
|
|
2384
|
-
server,
|
|
2385
|
-
{
|
|
2386
|
-
...tool,
|
|
2387
|
-
outputSchema: tool.outputSchema ?? catalogOutputSchema(catalogTool(withCatalog, server, tool.name))
|
|
2388
|
-
},
|
|
2389
|
-
{ verboseDescriptions: verbose }
|
|
2390
|
-
)
|
|
2391
|
-
).join("\n")
|
|
2392
|
-
);
|
|
2393
|
-
return 0;
|
|
2394
|
-
}
|
|
2395
|
-
for (const tool of selected) {
|
|
2396
|
-
stdout.write(`${renderToolSignature(server, tool, { allParameters })}
|
|
2397
|
-
`);
|
|
2398
|
-
if (verbose && tool.description?.trim()) {
|
|
2399
|
-
stdout.write(` ${tool.description.trim().replace(/\s+/g, " ")}
|
|
2400
|
-
`);
|
|
2401
|
-
}
|
|
2402
|
-
}
|
|
2403
|
-
return 0;
|
|
2404
|
-
} catch (error) {
|
|
2405
|
-
if (!quiet) writeCompactListError(error);
|
|
2406
|
-
return 1;
|
|
2407
|
-
} finally {
|
|
2408
|
-
await closeOwnedRuntime(runtime, owned);
|
|
2409
|
-
}
|
|
2410
|
-
}
|
|
2411
|
-
var PROXY_PROBE_PROPS = /* @__PURE__ */ new Set(["then", "toJSON", "constructor", "inspect"]);
|
|
2412
|
-
function normalizeName(value) {
|
|
2413
|
-
return value.replace(/[^a-z0-9]/gi, "").toLowerCase();
|
|
2414
|
-
}
|
|
2415
|
-
function levenshtein(a, b) {
|
|
2416
|
-
if (a === b) return 0;
|
|
2417
|
-
if (a.length === 0) return b.length;
|
|
2418
|
-
if (b.length === 0) return a.length;
|
|
2419
|
-
let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
2420
|
-
for (let i = 1; i <= a.length; i += 1) {
|
|
2421
|
-
const current = [i];
|
|
2422
|
-
for (let j = 1; j <= b.length; j += 1) {
|
|
2423
|
-
current[j] = Math.min(
|
|
2424
|
-
current[j - 1] + 1,
|
|
2425
|
-
previous[j] + 1,
|
|
2426
|
-
previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
|
|
2427
|
-
);
|
|
2428
|
-
}
|
|
2429
|
-
previous = current;
|
|
2430
|
-
}
|
|
2431
|
-
return previous[b.length];
|
|
2432
|
-
}
|
|
2433
|
-
function closestName2(input2, candidates) {
|
|
2434
|
-
const normalizedInput = normalizeName(input2);
|
|
2435
|
-
let best;
|
|
2436
|
-
let bestScore = Number.POSITIVE_INFINITY;
|
|
2437
|
-
for (const candidate of candidates) {
|
|
2438
|
-
const score = levenshtein(normalizedInput, normalizeName(candidate));
|
|
2439
|
-
if (score < bestScore) {
|
|
2440
|
-
bestScore = score;
|
|
2441
|
-
best = candidate;
|
|
2442
|
-
}
|
|
2443
|
-
}
|
|
2444
|
-
if (best === void 0) return void 0;
|
|
2445
|
-
const baseline = Math.max(normalizedInput.length, normalizeName(best).length, 1);
|
|
2446
|
-
return bestScore <= Math.max(2, Math.floor(baseline / 3)) ? best : void 0;
|
|
2447
|
-
}
|
|
2448
|
-
function describeUnknownRunServer(server, servers) {
|
|
2449
|
-
const suggestion = closestName2(server, servers);
|
|
2450
|
-
const parts = [`Unknown MCP server '${server}'.`];
|
|
2451
|
-
if (suggestion) parts.push(`Did you mean 'tools.${suggestion}'?`);
|
|
2452
|
-
parts.push(
|
|
2453
|
-
servers.length > 0 ? `Available servers: ${servers.join(", ")}.` : "No MCP servers are configured."
|
|
2454
|
-
);
|
|
2455
|
-
return parts.join(" ");
|
|
2456
|
-
}
|
|
2457
|
-
var RUN_TOOL_REJECTED_PATTERNS = [
|
|
2458
|
-
/\btool\s+[\w.-]+\s+not found\b/i,
|
|
2459
|
-
/\bunknown tool\b/i
|
|
2460
|
-
];
|
|
2461
|
-
var RUN_TOOL_BLOCKED_PATTERN = /is not accessible on server '[^']+' \(blocked by configuration\)/;
|
|
2462
|
-
var RUN_AUTH_REQUIRED_PATTERN = /\b(?:authentication required|unauthenticated|HTTP 401|missing (?:access )?token|invalid (?:access )?token|failed to resolve header ['"]Authorization)/i;
|
|
2463
|
-
function describeUnavailableRunTool(server, tool, knownTools) {
|
|
2464
|
-
const suggestion = closestName2(tool, knownTools);
|
|
2465
|
-
const parts = [`Tool '${tool}' is not available on server '${server}'.`];
|
|
2466
|
-
if (suggestion) parts.push(`Did you mean '${suggestion}'?`);
|
|
2467
|
-
parts.push(`Run \`mcp list ${server}\` to see available tools.`);
|
|
2468
|
-
return parts.join(" ");
|
|
2469
|
-
}
|
|
2470
|
-
function improveRunToolError(error, server, tool, knownTools) {
|
|
2471
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
2472
|
-
if (RUN_AUTH_REQUIRED_PATTERN.test(message)) {
|
|
2473
|
-
return new McpRemoteToolResultError({
|
|
2474
|
-
code: "authentication_required",
|
|
2475
|
-
message: `Authentication is required for MCP server '${server}'. Ask the user to authenticate this MCP connection outside the agent session, then retry.`,
|
|
2476
|
-
retryable: false,
|
|
2477
|
-
action: "ask_user_to_authenticate"
|
|
2478
|
-
});
|
|
2479
|
-
}
|
|
2480
|
-
if (RUN_TOOL_BLOCKED_PATTERN.test(message)) {
|
|
2481
|
-
return new Error(
|
|
2482
|
-
`Tool '${tool}' is not enabled for server '${server}' in this session. Run \`mcp list ${server}\` to inspect the allowlist; if absent, the recipe configuration must grant it.`,
|
|
2483
|
-
{ cause: error }
|
|
2484
|
-
);
|
|
2485
|
-
}
|
|
2486
|
-
if (!RUN_TOOL_REJECTED_PATTERNS.some((pattern) => pattern.test(message))) return error;
|
|
2487
|
-
return new Error(describeUnavailableRunTool(server, tool, knownTools), { cause: error });
|
|
2488
|
-
}
|
|
2489
|
-
var HANDSHAKE_RETRY_DELAYS_MS = [500, 1500];
|
|
2490
|
-
function refusedHandshake(error) {
|
|
2491
|
-
let current = error;
|
|
2492
|
-
for (let depth = 0; current instanceof Error && depth < 5; depth += 1) {
|
|
2493
|
-
if (/Version negotiation failed: the server answered the probe with HTTP 5\d\d/.test(current.message)) {
|
|
2494
|
-
return true;
|
|
2495
|
-
}
|
|
2496
|
-
current = current.cause;
|
|
2497
|
-
}
|
|
2498
|
-
return false;
|
|
2499
|
-
}
|
|
2500
|
-
async function callToolWithHandshakeRetry(runtime, server, tool, options, deadlineMs = Number.POSITIVE_INFINITY) {
|
|
2501
|
-
for (let attempt = 0; ; attempt += 1) {
|
|
2502
|
-
try {
|
|
2503
|
-
return await runtime.callTool(server, tool, options());
|
|
2504
|
-
} catch (error) {
|
|
2505
|
-
const wait = HANDSHAKE_RETRY_DELAYS_MS[attempt];
|
|
2506
|
-
if (wait === void 0 || !refusedHandshake(error) || Date.now() + wait >= deadlineMs) {
|
|
2507
|
-
throw error;
|
|
2508
|
-
}
|
|
2509
|
-
await delay(wait);
|
|
2510
|
-
}
|
|
2511
|
-
}
|
|
2512
|
-
}
|
|
2513
|
-
async function createTools(opts) {
|
|
2514
|
-
const { runtime, owned } = await acquireRuntime();
|
|
2515
|
-
const session = await readSession();
|
|
2516
|
-
const knownTools = /* @__PURE__ */ new Map();
|
|
2517
|
-
await Promise.all(
|
|
2518
|
-
session.servers.map(async (server) => {
|
|
2519
|
-
knownTools.set(
|
|
2520
|
-
server.id,
|
|
2521
|
-
(await readCachedCatalog(server))?.map((tool) => tool.name) ?? []
|
|
2522
|
-
);
|
|
2523
|
-
})
|
|
2524
|
-
);
|
|
2525
|
-
const configuredServers = new Set(runtime.listServers());
|
|
2526
|
-
const servers = session.servers.filter(
|
|
2527
|
-
(server) => configuredServers.has(server.id)
|
|
2528
|
-
);
|
|
2529
|
-
const calls = [];
|
|
2530
|
-
let callCount = 0;
|
|
2531
|
-
const queue = new ToolCallQueue(opts.maxConcurrentCalls);
|
|
2532
|
-
const toolsByServer = /* @__PURE__ */ Object.create(null);
|
|
2533
|
-
for (const serverPolicy of servers) {
|
|
2534
|
-
const server = serverPolicy.id;
|
|
2535
|
-
toolsByServer[server] = new Proxy(/* @__PURE__ */ Object.create(null), {
|
|
2536
|
-
get(_target, property) {
|
|
2537
|
-
if (typeof property !== "string" || PROXY_PROBE_PROPS.has(property)) return void 0;
|
|
2538
|
-
const startCall = (args, format) => {
|
|
2539
|
-
validateRunToolArgs(server, property, args);
|
|
2540
|
-
const allowedToolNames = knownTools.get(server) ?? [];
|
|
2541
|
-
if (!mcpSessionAllowsTool(serverPolicy, property)) {
|
|
2542
|
-
throw new McpRunToolError(
|
|
2543
|
-
server,
|
|
2544
|
-
property,
|
|
2545
|
-
describeUnavailableRunTool(server, property, allowedToolNames)
|
|
2546
|
-
);
|
|
2547
|
-
}
|
|
2548
|
-
if (callCount >= opts.maxCalls) {
|
|
2549
|
-
throw new McpRunUsageError(
|
|
2550
|
-
`mcp run tool-call limit exceeded (${opts.maxCalls}). Split the workflow or raise PI_RECIPES_MCP_RUN_MAX_CALLS.`
|
|
2551
|
-
);
|
|
2552
|
-
}
|
|
2553
|
-
callCount += 1;
|
|
2554
|
-
const rawCall = (async () => {
|
|
2555
|
-
let release;
|
|
2556
|
-
try {
|
|
2557
|
-
release = await queue.acquire();
|
|
2558
|
-
const remainingMs = opts.deadlineMs - Date.now();
|
|
2559
|
-
if (remainingMs <= 0) {
|
|
2560
|
-
throw new McpRunTimeoutError(
|
|
2561
|
-
`mcp run deadline reached before ${server}.${property} started.`
|
|
2562
|
-
);
|
|
2563
|
-
}
|
|
2564
|
-
const result = checkedCallResult(
|
|
2565
|
-
createCallResult(
|
|
2566
|
-
await callToolWithHandshakeRetry(
|
|
2567
|
-
runtime,
|
|
2568
|
-
server,
|
|
2569
|
-
property,
|
|
2570
|
-
() => ({
|
|
2571
|
-
args,
|
|
2572
|
-
// A queued call must never outlive the workflow that owns
|
|
2573
|
-
// it. mcporter forwards this timeout to the MCP SDK and
|
|
2574
|
-
// resets the transport when it fires.
|
|
2575
|
-
timeoutMs: Math.min(opts.callTimeoutMs, opts.deadlineMs - Date.now()),
|
|
2576
|
-
disableOAuth: true
|
|
2577
|
-
}),
|
|
2578
|
-
opts.deadlineMs
|
|
2579
|
-
)
|
|
2580
|
-
)
|
|
2581
|
-
);
|
|
2582
|
-
return decodeCallResult(result, format, `${server}.${property}`);
|
|
2583
|
-
} catch (error) {
|
|
2584
|
-
const improved = improveRunToolError(
|
|
2585
|
-
error,
|
|
2586
|
-
server,
|
|
2587
|
-
property,
|
|
2588
|
-
allowedToolNames ?? []
|
|
2589
|
-
);
|
|
2590
|
-
if (improved instanceof McpRunUsageError) throw improved;
|
|
2591
|
-
const message = improved instanceof Error ? improved.message : String(improved);
|
|
2592
|
-
const remoteDetails = improved instanceof McpRemoteToolResultError ? improved.details : error instanceof McpRemoteToolResultError ? error.details : void 0;
|
|
2593
|
-
const timeoutDetails = !remoteDetails && (improved instanceof McpRunTimeoutError || /\b(?:timed?\s*out|timeout)\b/i.test(message)) ? {
|
|
2594
|
-
code: "timeout",
|
|
2595
|
-
message: improved instanceof McpRunTimeoutError ? message : `MCP tool call ${server}.${property} timed out.`,
|
|
2596
|
-
retryable: true,
|
|
2597
|
-
action: "inspect_state",
|
|
2598
|
-
outcome: improved instanceof McpRunTimeoutError ? "not_started" : "unknown"
|
|
2599
|
-
} : void 0;
|
|
2600
|
-
throw new McpRunToolError(
|
|
2601
|
-
server,
|
|
2602
|
-
property,
|
|
2603
|
-
remoteDetails?.message ?? timeoutDetails?.message ?? message,
|
|
2604
|
-
{ cause: improved, details: remoteDetails ?? timeoutDetails }
|
|
2605
|
-
);
|
|
2606
|
-
} finally {
|
|
2607
|
-
release?.();
|
|
2608
|
-
}
|
|
2609
|
-
})();
|
|
2610
|
-
const record2 = {
|
|
2611
|
-
ref: `${server}.${property}`,
|
|
2612
|
-
observed: false,
|
|
2613
|
-
outcome: "pending",
|
|
2614
|
-
promise: rawCall
|
|
2615
|
-
};
|
|
2616
|
-
calls.push(record2);
|
|
2617
|
-
rawCall.then(
|
|
2618
|
-
() => {
|
|
2619
|
-
record2.outcome = "succeeded";
|
|
2620
|
-
},
|
|
2621
|
-
(error) => {
|
|
2622
|
-
record2.outcome = "failed";
|
|
2623
|
-
record2.error = error instanceof Error ? error.message : String(error);
|
|
2624
|
-
}
|
|
2625
|
-
);
|
|
2626
|
-
return new Proxy(rawCall, {
|
|
2627
|
-
get(target, key) {
|
|
2628
|
-
if (key === "toJSON") {
|
|
2629
|
-
return () => `[pending tool call ${server}.${property} \u2014 did you forget await?]`;
|
|
2630
|
-
}
|
|
2631
|
-
if (key === "then" || key === "catch" || key === "finally") {
|
|
2632
|
-
record2.observed = true;
|
|
2633
|
-
}
|
|
2634
|
-
const value = Reflect.get(target, key, target);
|
|
2635
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
2636
|
-
}
|
|
2637
|
-
});
|
|
2638
|
-
};
|
|
2639
|
-
const tool = ((args = {}) => startCall(args, "json"));
|
|
2640
|
-
tool.text = (args = {}) => startCall(args, "text");
|
|
2641
|
-
tool.markdown = (args = {}) => startCall(args, "markdown");
|
|
2642
|
-
tool.images = (args = {}) => startCall(args, "images");
|
|
2643
|
-
tool.content = (args = {}) => startCall(args, "content");
|
|
2644
|
-
tool.structuredContent = (args = {}) => startCall(args, "structuredContent");
|
|
2645
|
-
tool.raw = (args = {}) => startCall(args, "raw");
|
|
2646
|
-
return tool;
|
|
2647
|
-
}
|
|
2648
|
-
});
|
|
2649
|
-
}
|
|
2650
|
-
const tools = new Proxy(toolsByServer, {
|
|
2651
|
-
get(target, property) {
|
|
2652
|
-
if (typeof property !== "string" || PROXY_PROBE_PROPS.has(property)) return void 0;
|
|
2653
|
-
if (property in target) return target[property];
|
|
2654
|
-
throw new Error(
|
|
2655
|
-
describeUnknownRunServer(
|
|
2656
|
-
property,
|
|
2657
|
-
servers.map((server) => server.id)
|
|
2658
|
-
)
|
|
2659
|
-
);
|
|
2660
|
-
}
|
|
2661
|
-
});
|
|
2662
|
-
return {
|
|
2663
|
-
runtime,
|
|
2664
|
-
owned,
|
|
2665
|
-
tools,
|
|
2666
|
-
calls,
|
|
2667
|
-
cancelQueued: (error) => queue.cancel(error)
|
|
2668
|
-
};
|
|
2669
|
-
}
|
|
2670
|
-
function createVars(vars) {
|
|
2671
|
-
return new Proxy({ ...vars }, {
|
|
2672
|
-
get(target, property) {
|
|
2673
|
-
if (typeof property !== "string" || PROXY_PROBE_PROPS.has(property)) return void 0;
|
|
2674
|
-
if (property in target) return target[property];
|
|
2675
|
-
const defined = Object.keys(target);
|
|
2676
|
-
throw new Error(
|
|
2677
|
-
`vars.${property} is not defined. Pass it with --var ${property}=value` + (defined.length > 0 ? ` (defined vars: ${defined.join(", ")}).` : " (no vars were passed).") + ` Use \`"${property}" in vars\` to test for optional vars.`
|
|
2678
|
-
);
|
|
2679
|
-
}
|
|
2680
|
-
});
|
|
2681
|
-
}
|
|
2682
|
-
function createRunProcess() {
|
|
2683
|
-
return new Proxy(globalThis.process, {
|
|
2684
|
-
get(target, property) {
|
|
2685
|
-
if (property === "argv") {
|
|
2686
|
-
throw new McpRunUsageError(
|
|
2687
|
-
"process.argv is unavailable in mcp run. Pass dynamic values with --var KEY=value and read them as vars.KEY."
|
|
2688
|
-
);
|
|
2689
|
-
}
|
|
2690
|
-
const value = Reflect.get(target, property, target);
|
|
2691
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
2692
|
-
}
|
|
2693
|
-
});
|
|
2694
|
-
}
|
|
2695
|
-
function concurrentOutcomeError(error, calls) {
|
|
2696
|
-
if (calls.length < 2) return error;
|
|
2697
|
-
const outcomes = calls.map((call) => ({
|
|
2698
|
-
ref: call.ref,
|
|
2699
|
-
outcome: call.outcome,
|
|
2700
|
-
...call.error ? { error: call.error } : {}
|
|
2701
|
-
}));
|
|
2702
|
-
const summary = outcomes.map((call) => `${call.ref}=${call.outcome}`).join(", ");
|
|
2703
|
-
const message = `${error.message} Workflow call outcomes: ${summary}. Inspect state before retrying side-effecting calls.`;
|
|
2704
|
-
return new McpRunToolError(error.server, error.tool, message, {
|
|
2705
|
-
cause: error,
|
|
2706
|
-
details: { ...error.details, message, calls: outcomes }
|
|
2707
|
-
});
|
|
2708
|
-
}
|
|
2709
|
-
function positiveInteger(value, label, fallback) {
|
|
2710
|
-
const parsed = value === void 0 ? fallback : Number(value);
|
|
2711
|
-
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
2712
|
-
throw new McpRunUsageError(`${label} expects a positive integer, got '${value ?? ""}'.`);
|
|
2713
|
-
}
|
|
2714
|
-
return parsed;
|
|
2715
|
-
}
|
|
2716
|
-
async function runMcpJavaScript(code, opts = {}) {
|
|
2717
|
-
const timeoutMs = positiveInteger(
|
|
2718
|
-
opts.timeoutMs ?? process.env.PI_RECIPES_MCP_RUN_TIMEOUT_MS,
|
|
2719
|
-
"PI_RECIPES_MCP_RUN_TIMEOUT_MS",
|
|
2720
|
-
DEFAULT_RUN_TIMEOUT_MS
|
|
2721
|
-
);
|
|
2722
|
-
const callTimeoutMs = positiveInteger(
|
|
2723
|
-
opts.callTimeoutMs ?? process.env.PI_RECIPES_MCP_RUN_CALL_TIMEOUT_MS,
|
|
2724
|
-
"PI_RECIPES_MCP_RUN_CALL_TIMEOUT_MS",
|
|
2725
|
-
Math.min(DEFAULT_TOOL_CALL_TIMEOUT_MS, timeoutMs)
|
|
2726
|
-
);
|
|
2727
|
-
const maxCalls = positiveInteger(
|
|
2728
|
-
opts.maxCalls ?? process.env.PI_RECIPES_MCP_RUN_MAX_CALLS,
|
|
2729
|
-
"PI_RECIPES_MCP_RUN_MAX_CALLS",
|
|
2730
|
-
DEFAULT_MAX_RUN_TOOL_CALLS
|
|
2731
|
-
);
|
|
2732
|
-
const maxConcurrentCalls = positiveInteger(
|
|
2733
|
-
opts.maxConcurrentCalls ?? process.env.PI_RECIPES_MCP_RUN_MAX_CONCURRENCY,
|
|
2734
|
-
"PI_RECIPES_MCP_RUN_MAX_CONCURRENCY",
|
|
2735
|
-
DEFAULT_MAX_CONCURRENT_TOOL_CALLS
|
|
2736
|
-
);
|
|
2737
|
-
const deadlineMs = Date.now() + timeoutMs;
|
|
2738
|
-
const { runtime, owned, tools, calls, cancelQueued } = await createTools({
|
|
2739
|
-
callTimeoutMs,
|
|
2740
|
-
maxCalls,
|
|
2741
|
-
maxConcurrentCalls,
|
|
2742
|
-
deadlineMs
|
|
2743
|
-
});
|
|
2744
|
-
const AsyncFunction = Object.getPrototypeOf(async function() {
|
|
2745
|
-
}).constructor;
|
|
2746
|
-
const run = new AsyncFunction("tools", "vars", "process", code);
|
|
2747
|
-
let timeout;
|
|
2748
|
-
let primaryError;
|
|
2749
|
-
try {
|
|
2750
|
-
let scriptError;
|
|
2751
|
-
try {
|
|
2752
|
-
await Promise.race([
|
|
2753
|
-
run(tools, createVars(opts.vars ?? {}), createRunProcess()),
|
|
2754
|
-
new Promise((_resolve, reject) => {
|
|
2755
|
-
timeout = setTimeout(() => {
|
|
2756
|
-
reject(
|
|
2757
|
-
new McpRunTimeoutError(
|
|
2758
|
-
`mcp run timed out after ${timeoutMs}ms. Remote side effects may already have occurred; inspect state before retrying.`
|
|
2759
|
-
)
|
|
2760
|
-
);
|
|
2761
|
-
}, timeoutMs);
|
|
2762
|
-
})
|
|
2763
|
-
]);
|
|
2764
|
-
} catch (error) {
|
|
2765
|
-
scriptError = error;
|
|
2766
|
-
}
|
|
2767
|
-
if (scriptError instanceof McpRunTimeoutError) {
|
|
2768
|
-
cancelQueued(scriptError);
|
|
2769
|
-
for (const call of calls) {
|
|
2770
|
-
if (call.outcome === "pending") call.outcome = "outcome_unknown";
|
|
2771
|
-
}
|
|
2772
|
-
throw scriptError;
|
|
2773
|
-
}
|
|
2774
|
-
const unsafeAtExit = calls.filter(
|
|
2775
|
-
(call) => !call.observed || call.outcome === "pending"
|
|
2776
|
-
);
|
|
2777
|
-
if (unsafeAtExit.length > 0) {
|
|
2778
|
-
const remainingSettleMs = Math.max(0, Math.min(15e3, deadlineMs - Date.now()));
|
|
2779
|
-
if (remainingSettleMs > 0) {
|
|
2780
|
-
let settleTimer;
|
|
2781
|
-
try {
|
|
2782
|
-
await Promise.race([
|
|
2783
|
-
Promise.allSettled(unsafeAtExit.map((call) => call.promise)),
|
|
2784
|
-
new Promise((resolve2) => {
|
|
2785
|
-
settleTimer = setTimeout(resolve2, remainingSettleMs);
|
|
2786
|
-
})
|
|
2787
|
-
]);
|
|
2788
|
-
} finally {
|
|
2789
|
-
if (settleTimer) clearTimeout(settleTimer);
|
|
2790
|
-
}
|
|
2791
|
-
}
|
|
2792
|
-
for (const call of unsafeAtExit) {
|
|
2793
|
-
if (call.outcome === "pending") call.outcome = "outcome_unknown";
|
|
2794
|
-
}
|
|
2795
|
-
const remainingUnsafe = unsafeAtExit.filter(
|
|
2796
|
-
(call) => !call.observed || call.outcome === "outcome_unknown"
|
|
2797
|
-
);
|
|
2798
|
-
if (scriptError instanceof McpRunToolError && remainingUnsafe.length === 0) {
|
|
2799
|
-
throw concurrentOutcomeError(scriptError, calls);
|
|
2800
|
-
}
|
|
2801
|
-
const summary = unsafeAtExit.map(
|
|
2802
|
-
(call) => `${call.ref}=${call.outcome}` + (call.error ? ` (${call.error})` : "")
|
|
2803
|
-
).join(", ");
|
|
2804
|
-
throw new McpRunUsageError(
|
|
2805
|
-
`mcp run: ${unsafeAtExit.length} tool call(s) were not awaited: ${summary}. Await or return every tool-call chain before the script exits; attaching .then/.catch without awaiting the chain is not enough. Remote side effects may already have occurred.` + (scriptError ? ` The script also failed: ${scriptError instanceof Error ? scriptError.message : String(scriptError)}.` : "")
|
|
2806
|
-
);
|
|
2807
|
-
}
|
|
2808
|
-
if (scriptError) throw scriptError;
|
|
2809
|
-
} catch (error) {
|
|
2810
|
-
primaryError = error;
|
|
2811
|
-
throw error;
|
|
2812
|
-
} finally {
|
|
2813
|
-
if (timeout) clearTimeout(timeout);
|
|
2814
|
-
try {
|
|
2815
|
-
await closeOwnedRuntime(runtime, owned);
|
|
2816
|
-
} catch (closeError) {
|
|
2817
|
-
if (primaryError === void 0) throw closeError;
|
|
2818
|
-
}
|
|
2819
|
-
}
|
|
2820
|
-
}
|
|
2821
|
-
var RUN_WATCHDOG_GRACE_MS = 2e3;
|
|
2822
|
-
function startRunWatchdog(timeoutMs) {
|
|
2823
|
-
const worker = new Worker(
|
|
2824
|
-
`const { workerData } = require("node:worker_threads");
|
|
2825
|
-
const { writeSync } = require("node:fs");
|
|
2826
|
-
setTimeout(() => {
|
|
2827
|
-
writeSync(
|
|
2828
|
-
2,
|
|
2829
|
-
"mcp run: killed after " + workerData.limitMs + "ms. The script never yielded " +
|
|
2830
|
-
"(synchronous busy-loop?) or ignored the timeout. Use await inside loops and " +
|
|
2831
|
-
"set PI_RECIPES_MCP_RUN_TIMEOUT_MS to adjust the limit. Remote side effects " +
|
|
2832
|
-
"may already have occurred; inspect state before retrying.\\n"
|
|
2833
|
-
);
|
|
2834
|
-
process.kill(process.pid, "SIGKILL");
|
|
2835
|
-
}, workerData.limitMs);`,
|
|
2836
|
-
{ eval: true, workerData: { limitMs: timeoutMs + RUN_WATCHDOG_GRACE_MS } }
|
|
2837
|
-
);
|
|
2838
|
-
worker.unref();
|
|
2839
|
-
return () => void worker.terminate();
|
|
2840
|
-
}
|
|
2841
|
-
async function runCode(args) {
|
|
2842
|
-
const vars = {};
|
|
2843
|
-
const positional = [];
|
|
2844
|
-
let jsonErrors = false;
|
|
2845
|
-
for (let index = 0; index < args.length; index += 1) {
|
|
2846
|
-
const arg = args[index];
|
|
2847
|
-
if (arg === "--json-errors") {
|
|
2848
|
-
jsonErrors = true;
|
|
2849
|
-
continue;
|
|
2850
|
-
}
|
|
2851
|
-
const inline = arg.startsWith("--var=") ? arg.slice("--var=".length) : void 0;
|
|
2852
|
-
const value = inline ?? (arg === "--var" ? args[++index] : void 0);
|
|
2853
|
-
if (arg === "--var" || inline !== void 0) {
|
|
2854
|
-
const eq = value?.indexOf("=") ?? -1;
|
|
2855
|
-
if (value === void 0 || eq < 1) {
|
|
2856
|
-
stderr.write("--var expects KEY=value.\n");
|
|
2857
|
-
return 2;
|
|
2858
|
-
}
|
|
2859
|
-
vars[value.slice(0, eq)] = value.slice(eq + 1);
|
|
2860
|
-
continue;
|
|
2861
|
-
}
|
|
2862
|
-
positional.push(arg);
|
|
2863
|
-
}
|
|
2864
|
-
const file = positional[0];
|
|
2865
|
-
if (positional.length > 1) {
|
|
2866
|
-
stderr.write("mcp run accepts at most one file path.\n");
|
|
2867
|
-
return 2;
|
|
2868
|
-
}
|
|
2869
|
-
const code = file ? await readFile(file, "utf8") : await readStdin();
|
|
2870
|
-
if (!code.trim()) {
|
|
2871
|
-
stderr.write(
|
|
2872
|
-
"mcp run: empty script. Pass a file path or pipe JavaScript on stdin (see `mcp run --help`).\n"
|
|
2873
|
-
);
|
|
2874
|
-
return 2;
|
|
2875
|
-
}
|
|
2876
|
-
let timeoutMs;
|
|
2877
|
-
try {
|
|
2878
|
-
timeoutMs = positiveInteger(
|
|
2879
|
-
process.env.PI_RECIPES_MCP_RUN_TIMEOUT_MS,
|
|
2880
|
-
"PI_RECIPES_MCP_RUN_TIMEOUT_MS",
|
|
2881
|
-
DEFAULT_RUN_TIMEOUT_MS
|
|
2882
|
-
);
|
|
2883
|
-
} catch (error) {
|
|
2884
|
-
stderr.write(`${error instanceof Error ? error.message : String(error)}
|
|
2885
|
-
`);
|
|
2886
|
-
return 2;
|
|
2887
|
-
}
|
|
2888
|
-
const stopWatchdog = isMainThread ? startRunWatchdog(timeoutMs) : () => {
|
|
2889
|
-
};
|
|
2890
|
-
try {
|
|
2891
|
-
await runMcpJavaScript(code, { vars, timeoutMs });
|
|
2892
|
-
} catch (error) {
|
|
2893
|
-
const message = error instanceof Error ? error.name === "Error" ? error.message : `${error.name}: ${error.message}` : String(error);
|
|
2894
|
-
const prefixed = message.startsWith("mcp run") ? message : `mcp run: ${message}`;
|
|
2895
|
-
const code2 = error instanceof McpRunUsageError ? 2 : 1;
|
|
2896
|
-
if (jsonErrors) {
|
|
2897
|
-
const remoteDetails = error instanceof McpRunToolError ? error.details : void 0;
|
|
2898
|
-
stderr.write(
|
|
2899
|
-
`${JSON.stringify({
|
|
2900
|
-
error: {
|
|
2901
|
-
...remoteDetails,
|
|
2902
|
-
code: remoteDetails?.code ?? (error instanceof McpRunUsageError ? "invalid_usage" : error instanceof McpRunToolError ? "tool_execution" : error instanceof McpRunTimeoutError ? "timeout" : "script_failure"),
|
|
2903
|
-
message: remoteDetails?.message ?? prefixed,
|
|
2904
|
-
retryable: remoteDetails?.retryable ?? false,
|
|
2905
|
-
action: remoteDetails?.action ?? (error instanceof McpRunUsageError ? "correct_script" : error instanceof McpRunTimeoutError ? "inspect_state" : "inspect_error"),
|
|
2906
|
-
...error instanceof McpRunTimeoutError ? { outcome: error.outcome } : {},
|
|
2907
|
-
...error instanceof McpRunToolError ? { server: error.server, tool: error.tool } : {}
|
|
2908
|
-
}
|
|
2909
|
-
})}
|
|
2910
|
-
`
|
|
2911
|
-
);
|
|
2912
|
-
} else {
|
|
2913
|
-
stderr.write(`${prefixed}
|
|
2914
|
-
`);
|
|
2915
|
-
}
|
|
2916
|
-
return code2;
|
|
2917
|
-
} finally {
|
|
2918
|
-
stopWatchdog();
|
|
2919
|
-
}
|
|
2920
|
-
return 0;
|
|
2921
|
-
}
|
|
2922
|
-
function createDelegatedErrorFilter(write) {
|
|
2923
|
-
let buffer = "";
|
|
2924
|
-
let sawOAuthMetadataError = false;
|
|
2925
|
-
const emit = (line) => {
|
|
2926
|
-
if (/^\s+at\s\S/.test(line)) return;
|
|
2927
|
-
if (/trying to load OAuth metadata/.test(line)) sawOAuthMetadataError = true;
|
|
2928
|
-
const safe = line.replace(
|
|
2929
|
-
/Tool '([^']+)' is not accessible on server '([^']+)' \(blocked by configuration\)/g,
|
|
2930
|
-
"Tool '$1' is not enabled on server '$2' in this recipe session"
|
|
2931
|
-
).replace(
|
|
2932
|
-
/Failed to resolve header 'Authorization' for server '([^']+)': Environment variable\(s\) [A-Z0-9_, ]+ must be set for MCP header substitution\./g,
|
|
2933
|
-
"Authentication is required for MCP server '$1'. Ask the user to authenticate this MCP connection outside the agent session, then retry."
|
|
2934
|
-
).replace(
|
|
2935
|
-
/Next: run ['`]mcporter auth [^'`]+['`] to finish authentication\.?/gi,
|
|
2936
|
-
"Authentication is required. Ask the user to authenticate this MCP connection outside the agent session, then retry."
|
|
2937
|
-
);
|
|
2938
|
-
write(safe);
|
|
2939
|
-
};
|
|
2940
|
-
return {
|
|
2941
|
-
push(chunk) {
|
|
2942
|
-
buffer += chunk;
|
|
2943
|
-
let index = buffer.indexOf("\n");
|
|
2944
|
-
while (index !== -1) {
|
|
2945
|
-
emit(buffer.slice(0, index + 1));
|
|
2946
|
-
buffer = buffer.slice(index + 1);
|
|
2947
|
-
index = buffer.indexOf("\n");
|
|
2948
|
-
}
|
|
2949
|
-
},
|
|
2950
|
-
flush() {
|
|
2951
|
-
if (buffer) emit(buffer);
|
|
2952
|
-
buffer = "";
|
|
2953
|
-
if (sawOAuthMetadataError) {
|
|
2954
|
-
write(
|
|
2955
|
-
"Hint: this server is called with a configured bearer token; the token may be invalid or expired.\n"
|
|
2956
|
-
);
|
|
2957
|
-
sawOAuthMetadataError = false;
|
|
2958
|
-
}
|
|
2959
|
-
}
|
|
2960
|
-
};
|
|
2961
|
-
}
|
|
2962
|
-
function duplicateCallArgumentKeys(args) {
|
|
2963
|
-
const seen = /* @__PURE__ */ new Set();
|
|
2964
|
-
const duplicates = /* @__PURE__ */ new Set();
|
|
2965
|
-
for (const token of args.slice(1)) {
|
|
2966
|
-
const rawKey = token.match(/^([A-Za-z_][A-Za-z0-9_.-]*)=/)?.[1];
|
|
2967
|
-
if (!rawKey) continue;
|
|
2968
|
-
const key = rawKey.replace(
|
|
2969
|
-
/-([a-zA-Z0-9])/g,
|
|
2970
|
-
(_match, char) => char.toUpperCase()
|
|
2971
|
-
);
|
|
2972
|
-
if (seen.has(key)) duplicates.add(key);
|
|
2973
|
-
seen.add(key);
|
|
2974
|
-
}
|
|
2975
|
-
return [...duplicates];
|
|
2976
|
-
}
|
|
2977
|
-
function callJsonArgumentError(args) {
|
|
2978
|
-
for (let index = 1; index < args.length; index += 1) {
|
|
2979
|
-
const arg = args[index];
|
|
2980
|
-
if (arg === "--json") {
|
|
2981
|
-
const value = args[index + 1];
|
|
2982
|
-
if (value === void 0 || value.startsWith("--") && value !== "-") {
|
|
2983
|
-
return `mcp call: ${arg} expects a JSON object or - for stdin. Example: mcp call server.tool --json '{"tags":["a","b"]}'`;
|
|
2984
|
-
}
|
|
2985
|
-
index += 1;
|
|
2986
|
-
continue;
|
|
2987
|
-
}
|
|
2988
|
-
if (arg === "--json=") {
|
|
2989
|
-
return `mcp call: ${arg.slice(0, -1)} expects a JSON object or - for stdin.`;
|
|
2990
|
-
}
|
|
2991
|
-
}
|
|
2992
|
-
return null;
|
|
2993
|
-
}
|
|
2994
|
-
function malformedCallExpression(args) {
|
|
2995
|
-
const ref = args.find((arg) => !arg.startsWith("-"));
|
|
2996
|
-
if (!ref || !/[()]/.test(ref)) return null;
|
|
2997
|
-
return `mcp call: function-call expressions are unavailable. Use mcp call <server>.<tool> key=value or --json for structured arguments.`;
|
|
2998
|
-
}
|
|
2999
|
-
async function callWithMcporter(args) {
|
|
3000
|
-
const shared = currentMcpCommandContext()?.runtime;
|
|
3001
|
-
if (shared) return callWithSharedRuntime(shared, args);
|
|
3002
|
-
const previousDisableAutorun = process.env.MCPORTER_DISABLE_AUTORUN;
|
|
3003
|
-
const previousExitCode = process.exitCode;
|
|
3004
|
-
process.env.MCPORTER_DISABLE_AUTORUN = "1";
|
|
3005
|
-
process.exitCode = void 0;
|
|
3006
|
-
let runtime;
|
|
3007
|
-
let owned = false;
|
|
3008
|
-
try {
|
|
3009
|
-
({ runtime, owned } = await acquireRuntime());
|
|
3010
|
-
const { handleCall } = await loadMcporterCli();
|
|
3011
|
-
await handleCall(runtime, args);
|
|
3012
|
-
return process.exitCode ?? 0;
|
|
3013
|
-
} finally {
|
|
3014
|
-
process.exitCode = previousExitCode;
|
|
3015
|
-
if (previousDisableAutorun === void 0) {
|
|
3016
|
-
delete process.env.MCPORTER_DISABLE_AUTORUN;
|
|
3017
|
-
} else {
|
|
3018
|
-
process.env.MCPORTER_DISABLE_AUTORUN = previousDisableAutorun;
|
|
3019
|
-
}
|
|
3020
|
-
if (runtime && owned) await runtime.close().catch(() => {
|
|
3021
|
-
});
|
|
3022
|
-
}
|
|
3023
|
-
}
|
|
3024
|
-
async function callWithSharedRuntime(runtime, args) {
|
|
3025
|
-
const selector = args[0];
|
|
3026
|
-
const separator = selector?.indexOf(".") ?? -1;
|
|
3027
|
-
if (!selector || separator <= 0 || separator === selector.length - 1) {
|
|
3028
|
-
stderr.write("mcp call requires <server>.<tool>.\n");
|
|
3029
|
-
return 2;
|
|
3030
|
-
}
|
|
3031
|
-
const server = selector.slice(0, separator);
|
|
3032
|
-
const tool = selector.slice(separator + 1);
|
|
3033
|
-
const normalizedArgs = [...args];
|
|
3034
|
-
for (let index = 1; index < normalizedArgs.length; index += 1) {
|
|
3035
|
-
let token = normalizedArgs[index];
|
|
3036
|
-
const equals = token.indexOf("=");
|
|
3037
|
-
if (equals > 0 && !token.startsWith("--")) {
|
|
3038
|
-
const rawValue = token.slice(equals + 1);
|
|
3039
|
-
try {
|
|
3040
|
-
const decoded = JSON.parse(rawValue);
|
|
3041
|
-
if (typeof decoded === "string") {
|
|
3042
|
-
token = `${token.slice(0, equals + 1)}${decoded}`;
|
|
3043
|
-
normalizedArgs[index] = token;
|
|
3044
|
-
}
|
|
3045
|
-
} catch {
|
|
3046
|
-
}
|
|
3047
|
-
}
|
|
3048
|
-
for (const flag of ["--json", "--timeout", "--output"]) {
|
|
3049
|
-
if (token.startsWith(`${flag}=`)) {
|
|
3050
|
-
normalizedArgs.splice(index, 1, flag, token.slice(flag.length + 1));
|
|
3051
|
-
break;
|
|
3052
|
-
}
|
|
3053
|
-
}
|
|
3054
|
-
if (normalizedArgs[index] === "--json" && normalizedArgs[index + 1] === "-") {
|
|
3055
|
-
normalizedArgs[index + 1] = await readStdin();
|
|
3056
|
-
}
|
|
3057
|
-
}
|
|
3058
|
-
try {
|
|
3059
|
-
const { parseCallArguments, resolveCallTimeout } = await loadMcporterCli();
|
|
3060
|
-
const parsed = parseCallArguments(normalizedArgs);
|
|
3061
|
-
const timeoutMs = resolveCallTimeout(parsed.timeoutMs);
|
|
3062
|
-
const values = await restoreSchemaStringArguments(
|
|
3063
|
-
runtime,
|
|
3064
|
-
server,
|
|
3065
|
-
tool,
|
|
3066
|
-
parsed.args,
|
|
3067
|
-
parsed.schemaStringCoercionCandidates,
|
|
3068
|
-
timeoutMs
|
|
3069
|
-
);
|
|
3070
|
-
const call = callToolWithHandshakeRetry(runtime, server, tool, () => ({
|
|
3071
|
-
args: values,
|
|
3072
|
-
timeoutMs,
|
|
3073
|
-
disableOAuth: true
|
|
3074
|
-
}));
|
|
3075
|
-
const signal = currentMcpCommandContext()?.signal;
|
|
3076
|
-
let cancelled;
|
|
3077
|
-
const raw = signal ? await Promise.race([
|
|
3078
|
-
call,
|
|
3079
|
-
new Promise((_resolve, reject) => {
|
|
3080
|
-
cancelled = () => reject(new Error("MCP command cancelled."));
|
|
3081
|
-
if (signal.aborted) cancelled();
|
|
3082
|
-
else signal.addEventListener("abort", cancelled, { once: true });
|
|
3083
|
-
})
|
|
3084
|
-
]).finally(() => {
|
|
3085
|
-
if (cancelled) signal.removeEventListener("abort", cancelled);
|
|
3086
|
-
}) : await call;
|
|
3087
|
-
const result = createCallResult(raw);
|
|
3088
|
-
const rendered = selectCallOutput(result, raw, parsed.output);
|
|
3089
|
-
const serialized = serializeCallOutput(rendered, parsed.output);
|
|
3090
|
-
const configuredLimit = process.env.PI_RECIPES_MCP_MAX_OUTPUT_BYTES;
|
|
3091
|
-
if (configuredLimit !== void 0) {
|
|
3092
|
-
const limit = Number(configuredLimit);
|
|
3093
|
-
if (!Number.isSafeInteger(limit) || limit <= 0) {
|
|
3094
|
-
stderr.write("PI_RECIPES_MCP_MAX_OUTPUT_BYTES must be a positive integer.\n");
|
|
3095
|
-
return 2;
|
|
3096
|
-
}
|
|
3097
|
-
const size = Buffer.byteLength(serialized, "utf8");
|
|
3098
|
-
if (size > limit) {
|
|
3099
|
-
stderr.write(
|
|
3100
|
-
`MCP result is ${size} bytes, exceeding PI_RECIPES_MCP_MAX_OUTPUT_BYTES=${limit}. Use tool pagination or a narrower field projection.
|
|
3101
|
-
`
|
|
3102
|
-
);
|
|
3103
|
-
return 1;
|
|
3104
|
-
}
|
|
3105
|
-
}
|
|
3106
|
-
stdout.write(`${serialized}
|
|
3107
|
-
`);
|
|
3108
|
-
return asRecord(raw).isError === true ? 1 : 0;
|
|
3109
|
-
} catch (error) {
|
|
3110
|
-
stderr.write(`${describeSharedCallError(error, server, tool)}
|
|
3111
|
-
`);
|
|
3112
|
-
return 1;
|
|
3113
|
-
}
|
|
3114
|
-
}
|
|
3115
|
-
function selectCallOutput(result, raw, format) {
|
|
3116
|
-
const preferred = {
|
|
3117
|
-
auto: ["json", "markdown", "text", "raw"],
|
|
3118
|
-
text: ["text", "markdown", "json", "raw"],
|
|
3119
|
-
markdown: ["markdown", "text", "json", "raw"],
|
|
3120
|
-
json: ["json", "raw"],
|
|
3121
|
-
raw: ["raw"]
|
|
3122
|
-
};
|
|
3123
|
-
for (const kind of preferred[format]) {
|
|
3124
|
-
if (kind === "json") {
|
|
3125
|
-
const value = result.json();
|
|
3126
|
-
if (value !== null) return { kind, value };
|
|
3127
|
-
} else if (kind === "markdown") {
|
|
3128
|
-
const value = result.markdown();
|
|
3129
|
-
if (typeof value === "string") return { kind, value };
|
|
3130
|
-
} else if (kind === "text") {
|
|
3131
|
-
const value = result.text();
|
|
3132
|
-
if (typeof value === "string") return { kind, value };
|
|
3133
|
-
} else {
|
|
3134
|
-
return { kind, value: raw };
|
|
3135
|
-
}
|
|
3136
|
-
}
|
|
3137
|
-
return { kind: "raw", value: raw };
|
|
3138
|
-
}
|
|
3139
|
-
function jsonString(value) {
|
|
3140
|
-
try {
|
|
3141
|
-
return JSON.stringify(value, null, 2);
|
|
3142
|
-
} catch {
|
|
3143
|
-
return void 0;
|
|
3144
|
-
}
|
|
3145
|
-
}
|
|
3146
|
-
function serializeCallOutput(selected, requested) {
|
|
3147
|
-
if (selected.kind === "markdown" || selected.kind === "text") {
|
|
3148
|
-
return String(selected.value);
|
|
3149
|
-
}
|
|
3150
|
-
if (selected.kind === "json") {
|
|
3151
|
-
return jsonString(selected.value) ?? String(selected.value);
|
|
3152
|
-
}
|
|
3153
|
-
if (requested === "json") {
|
|
3154
|
-
return jsonString(selected.value) ?? JSON.stringify(String(selected.value));
|
|
3155
|
-
}
|
|
3156
|
-
if (typeof selected.value === "string") return selected.value;
|
|
3157
|
-
if (selected.value === null) return "null";
|
|
3158
|
-
if (selected.value === void 0) return "undefined";
|
|
3159
|
-
if (typeof selected.value === "bigint" || typeof selected.value === "symbol" || typeof selected.value === "function") {
|
|
3160
|
-
return selected.value.toString();
|
|
3161
|
-
}
|
|
3162
|
-
return inspect(selected.value, {
|
|
3163
|
-
depth: 8,
|
|
3164
|
-
maxStringLength: null,
|
|
3165
|
-
breakLength: 80
|
|
3166
|
-
});
|
|
3167
|
-
}
|
|
3168
|
-
function describeSharedCallError(error, server, tool) {
|
|
3169
|
-
const issue = describeConnectionIssue(error);
|
|
3170
|
-
if (issue.kind === "auth") {
|
|
3171
|
-
return `Authentication is required for MCP server '${server}'. Ask the user to authenticate this MCP connection outside the agent session, then retry.`;
|
|
3172
|
-
}
|
|
3173
|
-
if (issue.kind === "offline") {
|
|
3174
|
-
return `MCP server '${server}' appears offline: ${issue.rawMessage}`;
|
|
3175
|
-
}
|
|
3176
|
-
if (issue.kind === "http") {
|
|
3177
|
-
return `MCP call ${server}.${tool} failed with HTTP ${issue.statusCode ?? "error"}: ` + issue.rawMessage;
|
|
3178
|
-
}
|
|
3179
|
-
if (issue.kind === "stdio-exit") {
|
|
3180
|
-
const exit = typeof issue.stdioExitCode === "number" ? `code ${issue.stdioExitCode}` : "an unknown status";
|
|
3181
|
-
const signal = issue.stdioSignal ? ` (signal ${issue.stdioSignal})` : "";
|
|
3182
|
-
return `MCP server '${server}' exited with ${exit}${signal}.`;
|
|
3183
|
-
}
|
|
3184
|
-
return issue.rawMessage || (error instanceof Error ? error.message : String(error));
|
|
3185
|
-
}
|
|
3186
|
-
function schemaAllowsString(value) {
|
|
3187
|
-
const schema = asRecord(value);
|
|
3188
|
-
if (!schema) return false;
|
|
3189
|
-
if (schema.type === "string") return true;
|
|
3190
|
-
if (Array.isArray(schema.type) && schema.type.includes("string")) return true;
|
|
3191
|
-
return ["anyOf", "oneOf", "allOf"].some((key) => {
|
|
3192
|
-
const branches = schema[key];
|
|
3193
|
-
return Array.isArray(branches) && branches.some(schemaAllowsString);
|
|
3194
|
-
});
|
|
3195
|
-
}
|
|
3196
|
-
async function loadCallInputSchema(runtime, server, tool, timeoutMs) {
|
|
3197
|
-
let cache = callCatalogCache.get(runtime);
|
|
3198
|
-
if (!cache) {
|
|
3199
|
-
cache = /* @__PURE__ */ new Map();
|
|
3200
|
-
callCatalogCache.set(runtime, cache);
|
|
3201
|
-
}
|
|
3202
|
-
let pending = cache.get(server);
|
|
3203
|
-
if (!pending) {
|
|
3204
|
-
pending = (async () => {
|
|
3205
|
-
const sessionServer = (await readSession()).servers.find(
|
|
3206
|
-
(entry) => entry.id === server
|
|
3207
|
-
);
|
|
3208
|
-
if (!sessionServer) return [];
|
|
3209
|
-
return discoverServerCatalog(
|
|
3210
|
-
runtime,
|
|
3211
|
-
sessionServer,
|
|
3212
|
-
DEFAULT_LIST_TIMEOUT_MS
|
|
3213
|
-
);
|
|
3214
|
-
})();
|
|
3215
|
-
cache.set(server, pending);
|
|
3216
|
-
void pending.catch(() => {
|
|
3217
|
-
if (cache?.get(server) === pending) cache.delete(server);
|
|
3218
|
-
});
|
|
3219
|
-
}
|
|
3220
|
-
const catalog = await withListTimeout(pending, timeoutMs).catch(
|
|
3221
|
-
() => void 0
|
|
3222
|
-
);
|
|
3223
|
-
return catalog?.find((entry) => entry.name === tool)?.input_schema;
|
|
3224
|
-
}
|
|
3225
|
-
async function restoreSchemaStringArguments(runtime, server, tool, values, candidates, timeoutMs) {
|
|
3226
|
-
if (!candidates || Object.keys(candidates).length === 0) return values;
|
|
3227
|
-
const inputSchema = await loadCallInputSchema(
|
|
3228
|
-
runtime,
|
|
3229
|
-
server,
|
|
3230
|
-
tool,
|
|
3231
|
-
timeoutMs
|
|
3232
|
-
);
|
|
3233
|
-
const properties = asRecord(inputSchema?.properties);
|
|
3234
|
-
if (!properties) return values;
|
|
3235
|
-
let corrected;
|
|
3236
|
-
for (const [key, rawValue] of Object.entries(candidates)) {
|
|
3237
|
-
if (typeof values[key] !== "number" || !schemaAllowsString(properties[key])) {
|
|
3238
|
-
continue;
|
|
3239
|
-
}
|
|
3240
|
-
corrected ??= { ...values };
|
|
3241
|
-
corrected[key] = rawValue;
|
|
3242
|
-
}
|
|
3243
|
-
return corrected ?? values;
|
|
3244
|
-
}
|
|
3245
|
-
async function main(args = process.argv.slice(2)) {
|
|
3246
|
-
if (args.length === 0 || args[0] === "--help" || args[0] === "-h" || args[0] === "help" && args.length === 1) {
|
|
3247
|
-
stdout.write(`${mcpCliHelpText()}
|
|
3248
|
-
`);
|
|
3249
|
-
return 0;
|
|
3250
|
-
}
|
|
3251
|
-
if (args[0] === "search" && isHelpArg(args[1])) {
|
|
3252
|
-
stdout.write(`${mcpSearchHelpText()}
|
|
3253
|
-
`);
|
|
3254
|
-
return 0;
|
|
3255
|
-
}
|
|
3256
|
-
if (args[0] === "list" && args.slice(1).some(isHelpArg)) {
|
|
3257
|
-
stdout.write(`${mcpListHelpText()}
|
|
3258
|
-
`);
|
|
3259
|
-
return 0;
|
|
3260
|
-
}
|
|
3261
|
-
if (args[0] === "call" && args.slice(1).some(isHelpArg)) {
|
|
3262
|
-
stdout.write(`${mcpCallHelpText()}
|
|
3263
|
-
`);
|
|
3264
|
-
return 0;
|
|
3265
|
-
}
|
|
3266
|
-
if (args[0] === "run" && isHelpArg(args[1])) {
|
|
3267
|
-
stdout.write(`${mcpRunHelpText()}
|
|
3268
|
-
`);
|
|
3269
|
-
return 0;
|
|
3270
|
-
}
|
|
3271
|
-
pinSessionMcporterConfig();
|
|
3272
|
-
if (args[0] === "run") return runCode(args.slice(1));
|
|
3273
|
-
if (args[0] === "search") return searchCatalog(args.slice(1));
|
|
3274
|
-
if (args[0] === "call") {
|
|
3275
|
-
const malformed = malformedCallExpression(args.slice(1));
|
|
3276
|
-
if (malformed) {
|
|
3277
|
-
stderr.write(`${malformed}
|
|
3278
|
-
`);
|
|
3279
|
-
return 2;
|
|
3280
|
-
}
|
|
3281
|
-
const jsonArgumentError = callJsonArgumentError(args.slice(1));
|
|
3282
|
-
if (jsonArgumentError) {
|
|
3283
|
-
stderr.write(`${jsonArgumentError}
|
|
3284
|
-
`);
|
|
3285
|
-
return 2;
|
|
3286
|
-
}
|
|
3287
|
-
}
|
|
3288
|
-
let validated;
|
|
3289
|
-
try {
|
|
3290
|
-
validated = validateDelegatedMcpCommand(args, await sessionCliPolicy());
|
|
3291
|
-
} catch (error) {
|
|
3292
|
-
stderr.write(`mcp: failed to load the session MCP policy: ${error instanceof Error ? error.message : String(error)}
|
|
3293
|
-
`);
|
|
3294
|
-
return 1;
|
|
3295
|
-
}
|
|
3296
|
-
if (validated.error) {
|
|
3297
|
-
stderr.write(`mcp: ${validated.error}
|
|
3298
|
-
`);
|
|
3299
|
-
return 2;
|
|
3300
|
-
}
|
|
3301
|
-
if (!validated.command) {
|
|
3302
|
-
stderr.write("mcp: invalid session command policy result.\n");
|
|
3303
|
-
return 1;
|
|
3304
|
-
}
|
|
3305
|
-
if (args[0] === "call") {
|
|
3306
|
-
const duplicates = duplicateCallArgumentKeys(
|
|
3307
|
-
validated.command.args.slice(1)
|
|
3308
|
-
);
|
|
3309
|
-
if (duplicates.length > 0) {
|
|
3310
|
-
stderr.write(
|
|
3311
|
-
`mcp call: argument${duplicates.length === 1 ? "" : "s"} ${duplicates.map((key) => `'${key}'`).join(", ")} ${duplicates.length === 1 ? "was" : "were"} passed more than once. Pass each argument exactly once.
|
|
3312
|
-
`
|
|
3313
|
-
);
|
|
3314
|
-
return 2;
|
|
3315
|
-
}
|
|
3316
|
-
}
|
|
3317
|
-
const delegatedArgs = validated.command.args;
|
|
3318
|
-
if (delegatedArgs[0] === "list") return compactList(delegatedArgs);
|
|
3319
|
-
if (delegatedArgs[0] === "call") {
|
|
3320
|
-
return callWithMcporter(delegatedArgs.slice(1));
|
|
3321
|
-
}
|
|
3322
|
-
stderr.write(`mcp: command '${delegatedArgs[0]}' is unavailable in recipe sessions.
|
|
3323
|
-
`);
|
|
3324
|
-
return 2;
|
|
3325
|
-
}
|
|
3326
|
-
async function executeMcpCommand(opts) {
|
|
3327
|
-
const context2 = {
|
|
3328
|
-
runtime: opts.runtime,
|
|
3329
|
-
stdin: opts.stdin,
|
|
3330
|
-
stdout: opts.stdout,
|
|
3331
|
-
stderr: opts.stderr,
|
|
3332
|
-
signal: opts.signal
|
|
3333
|
-
};
|
|
3334
|
-
return runWithMcpCommandContext(context2, () => main(opts.args));
|
|
3335
|
-
}
|
|
3336
|
-
|
|
3337
|
-
export {
|
|
3338
|
-
context,
|
|
3339
|
-
installMcpCommandIoRouting,
|
|
3340
|
-
MCP_DAEMON_SOCKET_ENV,
|
|
3341
|
-
MCP_DAEMON_TOKEN_ENV,
|
|
3342
|
-
MCP_DAEMON_FINGERPRINT_ENV,
|
|
3343
|
-
MCP_DAEMON_PARENT_PID_ENV,
|
|
3344
|
-
MCP_DAEMON_MAX_FRAME_BYTES,
|
|
3345
|
-
serializeMcpDaemonEnvelope,
|
|
3346
|
-
mcpDaemonRequestContext,
|
|
3347
|
-
discoverMcpCatalogs,
|
|
3348
|
-
executeMcpCommand
|
|
3349
|
-
};
|