indusagi 0.13.6 → 0.13.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.md +7 -1
- package/dist/cli.js +114 -14
- package/dist/index.js +1618 -51
- package/dist/llmgateway.js +114 -14
- package/dist/mcp.js +812 -3
- package/dist/runtime.js +114 -14
- package/dist/sarvam-mcp.js +960 -0
- package/dist/shell-app.js +116 -14
- package/dist/smithy.js +114 -14
- package/dist/swarm.js +114 -14
- package/dist/tracing.js +37 -0
- package/dist/types/connectors-sarvam/connect.d.ts +14 -0
- package/dist/types/connectors-sarvam/connectors-sarvam.test.d.ts +14 -0
- package/dist/types/connectors-sarvam/index.d.ts +14 -0
- package/dist/types/connectors-sarvam/toolbox.d.ts +19 -0
- package/dist/types/connectors-sarvam/types.d.ts +49 -0
- package/dist/types/connectors-zoho/connect.d.ts +22 -0
- package/dist/types/connectors-zoho/connectors-zoho.test.d.ts +10 -0
- package/dist/types/connectors-zoho/index.d.ts +13 -0
- package/dist/types/connectors-zoho/toolbox.d.ts +19 -0
- package/dist/types/connectors-zoho/types.d.ts +56 -0
- package/dist/types/facade/mcp-core/client.d.ts +32 -0
- package/dist/types/facade/mcp-core/index.d.ts +4 -0
- package/dist/types/facade/mcp-core/oauth/flow.d.ts +72 -0
- package/dist/types/facade/mcp-core/oauth/index.d.ts +18 -0
- package/dist/types/facade/mcp-core/oauth/oauth.test.d.ts +8 -0
- package/dist/types/facade/mcp-core/oauth/provider.d.ts +51 -0
- package/dist/types/facade/mcp-core/oauth/token-store.d.ts +31 -0
- package/dist/types/facade/mcp-core/oauth/types.d.ts +96 -0
- package/dist/types/facade/mcp-core/toolbox-bridge.d.ts +46 -0
- package/dist/types/facade/mcp-core/toolbox-bridge.test.d.ts +8 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/llmgateway/contract/model-card.d.ts +1 -1
- package/dist/types/llmgateway/credentials/secrets.d.ts +2 -0
- package/dist/zoho.js +1451 -0
- package/package.json +11 -4
- package/dist/knowledge/guides/authoring-an-agent.md +0 -53
- package/dist/knowledge/guides/choosing-tools.md +0 -49
- package/dist/knowledge/guides/model-selection.md +0 -51
- package/dist/knowledge/guides/writing-system-prompts.md +0 -53
- package/dist/knowledge/index.ts +0 -19
- package/dist/knowledge/loader.ts +0 -200
- package/dist/knowledge/manifest.json +0 -29
|
@@ -0,0 +1,960 @@
|
|
|
1
|
+
// src/facade/mcp-core/client.ts
|
|
2
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
3
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
4
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
5
|
+
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
|
6
|
+
import {
|
|
7
|
+
UnauthorizedError
|
|
8
|
+
} from "@modelcontextprotocol/sdk/client/auth.js";
|
|
9
|
+
import {
|
|
10
|
+
ListRootsRequestSchema,
|
|
11
|
+
ElicitRequestSchema,
|
|
12
|
+
CreateMessageRequestSchema,
|
|
13
|
+
PingRequestSchema,
|
|
14
|
+
ToolListChangedNotificationSchema,
|
|
15
|
+
ResourceListChangedNotificationSchema,
|
|
16
|
+
ResourceUpdatedNotificationSchema,
|
|
17
|
+
PromptListChangedNotificationSchema,
|
|
18
|
+
ProgressNotificationSchema,
|
|
19
|
+
LoggingMessageNotificationSchema,
|
|
20
|
+
CancelledNotificationSchema
|
|
21
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
22
|
+
|
|
23
|
+
// src/facade/mcp-core/errors.ts
|
|
24
|
+
var MCPError = class extends Error {
|
|
25
|
+
/** Error code */
|
|
26
|
+
code;
|
|
27
|
+
/** Additional error details */
|
|
28
|
+
details;
|
|
29
|
+
/** Server name where error occurred */
|
|
30
|
+
serverName;
|
|
31
|
+
/** Tool name if error occurred during tool execution */
|
|
32
|
+
toolName;
|
|
33
|
+
constructor(message, code, details, options) {
|
|
34
|
+
super(message, options?.cause ? { cause: options.cause } : void 0);
|
|
35
|
+
this.name = "MCPError";
|
|
36
|
+
this.code = code;
|
|
37
|
+
this.details = details;
|
|
38
|
+
this.serverName = options?.serverName;
|
|
39
|
+
this.toolName = options?.toolName;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Convert error to JSON for logging/serialization.
|
|
43
|
+
*/
|
|
44
|
+
toJSON() {
|
|
45
|
+
return {
|
|
46
|
+
name: this.name,
|
|
47
|
+
message: this.message,
|
|
48
|
+
code: this.code,
|
|
49
|
+
details: this.details,
|
|
50
|
+
serverName: this.serverName,
|
|
51
|
+
toolName: this.toolName
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Create a string representation of the error.
|
|
56
|
+
*/
|
|
57
|
+
toString() {
|
|
58
|
+
let str = `${this.name} [${this.code}]: ${this.message}`;
|
|
59
|
+
if (this.serverName) str += ` (server: ${this.serverName})`;
|
|
60
|
+
if (this.toolName) str += ` (tool: ${this.toolName})`;
|
|
61
|
+
return str;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
function createServerError(message, serverName, details) {
|
|
65
|
+
return new MCPError(message, "SERVER_ERROR" /* SERVER_ERROR */, details, { serverName });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// src/facade/mcp-core/client.ts
|
|
69
|
+
var DEFAULT_REQUEST_TIMEOUT = 6e4;
|
|
70
|
+
var DEFAULT_CONNECT_TIMEOUT = 3e4;
|
|
71
|
+
var MCPClient = class {
|
|
72
|
+
constructor(options) {
|
|
73
|
+
this.options = options;
|
|
74
|
+
this.serverName = options.name;
|
|
75
|
+
this.config = options.config;
|
|
76
|
+
this.timeout = options.timeout ?? DEFAULT_REQUEST_TIMEOUT;
|
|
77
|
+
this.logHandler = options.logger;
|
|
78
|
+
this.enableServerLogs = options.enableServerLogs ?? true;
|
|
79
|
+
this.enableProgressTracking = options.enableProgressTracking ?? false;
|
|
80
|
+
this._roots = options.roots ?? [];
|
|
81
|
+
}
|
|
82
|
+
options;
|
|
83
|
+
client;
|
|
84
|
+
transport;
|
|
85
|
+
isConnected = false;
|
|
86
|
+
connectionPromise = null;
|
|
87
|
+
serverCapabilities;
|
|
88
|
+
logHandler;
|
|
89
|
+
enableServerLogs;
|
|
90
|
+
enableProgressTracking;
|
|
91
|
+
_roots;
|
|
92
|
+
// --- Host-overridable handlers (Core of #13) --------------------------------
|
|
93
|
+
// Server-initiated REQUESTS are answered by request handlers registered on the
|
|
94
|
+
// SDK client; the handlers delegate to these host-supplied callbacks when set,
|
|
95
|
+
// and fall back to sensible defaults otherwise.
|
|
96
|
+
elicitationHandler;
|
|
97
|
+
samplingHandler;
|
|
98
|
+
// Server-initiated NOTIFICATIONS are dispatched to these (so the host can, for
|
|
99
|
+
// example, re-list tools when a `tools/list_changed` arrives).
|
|
100
|
+
resourceUpdatedHandler;
|
|
101
|
+
resourceListChangedHandler;
|
|
102
|
+
toolListChangedHandler;
|
|
103
|
+
promptListChangedHandler;
|
|
104
|
+
progressHandler;
|
|
105
|
+
/** Server name */
|
|
106
|
+
serverName;
|
|
107
|
+
/** Server config */
|
|
108
|
+
config;
|
|
109
|
+
/** Request timeout */
|
|
110
|
+
timeout;
|
|
111
|
+
// ========================================================================
|
|
112
|
+
// Connection Lifecycle
|
|
113
|
+
// ========================================================================
|
|
114
|
+
/**
|
|
115
|
+
* Connect to the MCP server.
|
|
116
|
+
* Safe to call multiple times - returns existing connection if already connected.
|
|
117
|
+
*/
|
|
118
|
+
async connect() {
|
|
119
|
+
if (this.isConnected) return;
|
|
120
|
+
if (this.connectionPromise) {
|
|
121
|
+
return this.connectionPromise;
|
|
122
|
+
}
|
|
123
|
+
this.connectionPromise = this.doConnect();
|
|
124
|
+
try {
|
|
125
|
+
await this.connectionPromise;
|
|
126
|
+
} finally {
|
|
127
|
+
this.connectionPromise = null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async doConnect() {
|
|
131
|
+
const transport = this.createTransport(this.config);
|
|
132
|
+
this.transport = transport;
|
|
133
|
+
const client = new Client(
|
|
134
|
+
{ name: "indusagi-coding-agent", version: "0.13.0" },
|
|
135
|
+
{
|
|
136
|
+
capabilities: {
|
|
137
|
+
roots: { listChanged: true },
|
|
138
|
+
elicitation: {},
|
|
139
|
+
sampling: {}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
);
|
|
143
|
+
this.client = client;
|
|
144
|
+
this.registerServerHandlers(client);
|
|
145
|
+
const prevOnClose = transport.onclose;
|
|
146
|
+
transport.onclose = () => {
|
|
147
|
+
this.isConnected = false;
|
|
148
|
+
this.log("debug", "Transport closed");
|
|
149
|
+
prevOnClose?.();
|
|
150
|
+
};
|
|
151
|
+
try {
|
|
152
|
+
await client.connect(transport, { timeout: DEFAULT_CONNECT_TIMEOUT });
|
|
153
|
+
} catch (err) {
|
|
154
|
+
const recovered = await this.tryFinishOAuthAndReconnect(client, transport, err);
|
|
155
|
+
if (!recovered) {
|
|
156
|
+
throw this.wrapConnectError(err);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
this.serverCapabilities = client.getServerCapabilities();
|
|
160
|
+
this.isConnected = true;
|
|
161
|
+
this.log("info", `Connected to MCP server`);
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* If `err` is an OAuth challenge and we have a provider + finishAuth-capable
|
|
165
|
+
* transport, wait for the browser code, exchange tokens, then reconnect on a
|
|
166
|
+
* **fresh** transport (the first transport is already `start()`ed and cannot
|
|
167
|
+
* be reused — see StreamableHTTPClientTransport.start).
|
|
168
|
+
*
|
|
169
|
+
* Matches the official SDK CLI example (`simpleOAuthClient`):
|
|
170
|
+
* finishAuth(code) → new StreamableHTTPClientTransport → client.connect again
|
|
171
|
+
*
|
|
172
|
+
* Client.connect already called `close()` on init failure, so the Client is
|
|
173
|
+
* free to attach a new transport.
|
|
174
|
+
*/
|
|
175
|
+
async tryFinishOAuthAndReconnect(client, transport, err) {
|
|
176
|
+
if (!isAuthRequiredError(err)) return false;
|
|
177
|
+
const provider = this.options.authProvider;
|
|
178
|
+
if (!provider) return false;
|
|
179
|
+
const finishAuth = transport.finishAuth;
|
|
180
|
+
const waitForCode = provider.waitForAuthorizationCode;
|
|
181
|
+
if (typeof finishAuth !== "function" || typeof waitForCode !== "function") {
|
|
182
|
+
this.log(
|
|
183
|
+
"error",
|
|
184
|
+
"MCP server requires authentication but OAuth finish path is incomplete (need authProvider.waitForAuthorizationCode + transport.finishAuth)."
|
|
185
|
+
);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
this.log("info", "MCP server requires OAuth \u2014 complete login in the browser\u2026");
|
|
189
|
+
try {
|
|
190
|
+
const code = await waitForCode.call(provider);
|
|
191
|
+
this.log("info", "OAuth authorization code received \u2014 exchanging tokens\u2026");
|
|
192
|
+
await finishAuth.call(transport, code);
|
|
193
|
+
try {
|
|
194
|
+
await transport.close?.();
|
|
195
|
+
} catch {
|
|
196
|
+
}
|
|
197
|
+
const fresh = this.createTransport(this.config);
|
|
198
|
+
this.transport = fresh;
|
|
199
|
+
const prevOnClose = fresh.onclose;
|
|
200
|
+
fresh.onclose = () => {
|
|
201
|
+
this.isConnected = false;
|
|
202
|
+
this.log("debug", "Transport closed");
|
|
203
|
+
prevOnClose?.();
|
|
204
|
+
};
|
|
205
|
+
this.log("info", "Reconnecting MCP session with OAuth tokens\u2026");
|
|
206
|
+
await client.connect(fresh, { timeout: DEFAULT_CONNECT_TIMEOUT });
|
|
207
|
+
return true;
|
|
208
|
+
} catch (oauthErr) {
|
|
209
|
+
this.log(
|
|
210
|
+
"error",
|
|
211
|
+
`OAuth finish failed: ${oauthErr instanceof Error ? oauthErr.message : String(oauthErr)}`
|
|
212
|
+
);
|
|
213
|
+
throw this.wrapConnectError(oauthErr);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** Turn raw SDK / network errors into a clearer MCPError for callers. */
|
|
217
|
+
wrapConnectError(err) {
|
|
218
|
+
if (err instanceof MCPError) return err;
|
|
219
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
220
|
+
if (isAuthRequiredError(err)) {
|
|
221
|
+
return new MCPError(
|
|
222
|
+
`Authentication required for MCP server "${this.serverName}". Pass auth: "auto" (default) to run the OAuth browser flow, or set a Bearer token via headers. Original: ${message}`,
|
|
223
|
+
"CONNECTION_FAILED" /* CONNECTION_FAILED */,
|
|
224
|
+
err,
|
|
225
|
+
{ serverName: this.serverName, cause: err instanceof Error ? err : void 0 }
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
return new MCPError(
|
|
229
|
+
`Failed to connect to MCP server "${this.serverName}": ${message}`,
|
|
230
|
+
"CONNECTION_FAILED" /* CONNECTION_FAILED */,
|
|
231
|
+
err,
|
|
232
|
+
{ serverName: this.serverName, cause: err instanceof Error ? err : void 0 }
|
|
233
|
+
);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Build the SDK transport for the configured server.
|
|
237
|
+
*
|
|
238
|
+
* - stdio: `StdioClientTransport` (inherits the parent env, merges config.env).
|
|
239
|
+
* - http: `StreamableHTTPClientTransport` (POST + server-push SSE channel,
|
|
240
|
+
* reconnect + session-expiry handled by the SDK), unless the config
|
|
241
|
+
* asks for the legacy `SSEClientTransport`.
|
|
242
|
+
*/
|
|
243
|
+
createTransport(config) {
|
|
244
|
+
if ("command" in config) {
|
|
245
|
+
return new StdioClientTransport({
|
|
246
|
+
command: config.command,
|
|
247
|
+
args: config.args ?? [],
|
|
248
|
+
env: { ...sanitizeEnv(process.env), ...config.env ?? {} },
|
|
249
|
+
cwd: config.cwd,
|
|
250
|
+
stderr: "pipe"
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
if ("url" in config) {
|
|
254
|
+
const requestInit = config.headers ? { headers: config.headers } : void 0;
|
|
255
|
+
if (config.transport === "sse") {
|
|
256
|
+
return new SSEClientTransport(config.url, {
|
|
257
|
+
requestInit,
|
|
258
|
+
...this.options.authProvider ? { authProvider: this.options.authProvider } : {}
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
return new StreamableHTTPClientTransport(config.url, {
|
|
262
|
+
requestInit,
|
|
263
|
+
...this.options.authProvider ? { authProvider: this.options.authProvider } : {}
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
throw new MCPError(
|
|
267
|
+
"Server configuration must include either a command or a url",
|
|
268
|
+
"CONFIG_ERROR" /* CONFIG_ERROR */,
|
|
269
|
+
void 0,
|
|
270
|
+
{ serverName: this.serverName }
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Register handlers for server-initiated REQUESTS and NOTIFICATIONS.
|
|
275
|
+
*
|
|
276
|
+
* REQUESTS (have both `.method` AND `.id`) must be ANSWERED with a JSON-RPC
|
|
277
|
+
* RESPONSE carrying the matching id — the SDK does this automatically for the
|
|
278
|
+
* value a request handler returns (or rejects). The previous hand-rolled
|
|
279
|
+
* transport routed these into the notification path, so they were never
|
|
280
|
+
* answered (bug #13).
|
|
281
|
+
*
|
|
282
|
+
* Defaults:
|
|
283
|
+
* - ping → {}
|
|
284
|
+
* - roots/list → the configured roots
|
|
285
|
+
* - elicitation/create→ decline ({action:"cancel"}) unless a host handler is set
|
|
286
|
+
* - sampling → reject "Method not found" unless a host handler is set
|
|
287
|
+
*/
|
|
288
|
+
registerServerHandlers(client) {
|
|
289
|
+
client.setRequestHandler(PingRequestSchema, async () => ({}));
|
|
290
|
+
client.setRequestHandler(ListRootsRequestSchema, async () => ({
|
|
291
|
+
roots: this._roots.map((r) => ({ uri: r.uri, name: r.name }))
|
|
292
|
+
}));
|
|
293
|
+
client.setRequestHandler(ElicitRequestSchema, async (request) => {
|
|
294
|
+
if (!this.elicitationHandler) {
|
|
295
|
+
return { action: "cancel" };
|
|
296
|
+
}
|
|
297
|
+
const params = request.params;
|
|
298
|
+
const elicitRequest = {
|
|
299
|
+
message: params.message,
|
|
300
|
+
requestedSchema: params.requestedSchema ?? {}
|
|
301
|
+
};
|
|
302
|
+
const result = await this.elicitationHandler(elicitRequest);
|
|
303
|
+
return mapToSdkElicitResult(result);
|
|
304
|
+
});
|
|
305
|
+
client.setRequestHandler(CreateMessageRequestSchema, async (request) => {
|
|
306
|
+
if (!this.samplingHandler) {
|
|
307
|
+
throw new MCPError(
|
|
308
|
+
"Method not found: sampling/createMessage",
|
|
309
|
+
"SERVER_ERROR" /* SERVER_ERROR */,
|
|
310
|
+
{ method: "sampling/createMessage" },
|
|
311
|
+
{ serverName: this.serverName }
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
return await this.samplingHandler(request.params);
|
|
315
|
+
});
|
|
316
|
+
client.setNotificationHandler(ToolListChangedNotificationSchema, () => {
|
|
317
|
+
this.log("debug", "Tool list changed");
|
|
318
|
+
this.toolListChangedHandler?.();
|
|
319
|
+
});
|
|
320
|
+
client.setNotificationHandler(ResourceListChangedNotificationSchema, () => {
|
|
321
|
+
this.log("debug", "Resource list changed");
|
|
322
|
+
this.resourceListChangedHandler?.();
|
|
323
|
+
});
|
|
324
|
+
client.setNotificationHandler(ResourceUpdatedNotificationSchema, (n) => {
|
|
325
|
+
const uri = n.params?.uri;
|
|
326
|
+
this.log("debug", `Resource updated: ${uri}`);
|
|
327
|
+
if (uri) this.resourceUpdatedHandler?.({ uri });
|
|
328
|
+
});
|
|
329
|
+
client.setNotificationHandler(PromptListChangedNotificationSchema, () => {
|
|
330
|
+
this.log("debug", "Prompt list changed");
|
|
331
|
+
this.promptListChangedHandler?.();
|
|
332
|
+
});
|
|
333
|
+
client.setNotificationHandler(ProgressNotificationSchema, (n) => {
|
|
334
|
+
const params = n.params;
|
|
335
|
+
this.log("debug", `Progress: ${JSON.stringify(params)}`);
|
|
336
|
+
if (this.progressHandler && params) {
|
|
337
|
+
const notification = {
|
|
338
|
+
progressToken: params.progressToken,
|
|
339
|
+
progress: params.progress,
|
|
340
|
+
total: params.total,
|
|
341
|
+
message: params.message
|
|
342
|
+
};
|
|
343
|
+
this.progressHandler(notification);
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
client.setNotificationHandler(LoggingMessageNotificationSchema, (n) => {
|
|
347
|
+
if (this.enableServerLogs && n.params) {
|
|
348
|
+
const { level, ...rest } = n.params;
|
|
349
|
+
this.log(level || "info", "[SERVER]", rest);
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
client.setNotificationHandler(CancelledNotificationSchema, (n) => {
|
|
353
|
+
this.log("debug", `Request cancelled: ${JSON.stringify(n.params)}`);
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Disconnect from the MCP server.
|
|
358
|
+
*
|
|
359
|
+
* The SDK's `client.close()` closes the transport and rejects any pending
|
|
360
|
+
* requests — a clean teardown for both stdio (graceful subprocess shutdown)
|
|
361
|
+
* and HTTP (close the push channel / end the session).
|
|
362
|
+
*/
|
|
363
|
+
async disconnect() {
|
|
364
|
+
if (!this.client) {
|
|
365
|
+
this.log("debug", "Disconnect called but not connected");
|
|
366
|
+
this.isConnected = false;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
this.log("debug", "Disconnecting from MCP server");
|
|
370
|
+
try {
|
|
371
|
+
await this.client.close();
|
|
372
|
+
} catch (error) {
|
|
373
|
+
this.log("error", `Error during disconnect: ${error}`);
|
|
374
|
+
} finally {
|
|
375
|
+
this.client = void 0;
|
|
376
|
+
this.transport = void 0;
|
|
377
|
+
this.isConnected = false;
|
|
378
|
+
this.log("debug", "Successfully disconnected");
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Whether the client is connected.
|
|
383
|
+
*/
|
|
384
|
+
get connected() {
|
|
385
|
+
return this.isConnected;
|
|
386
|
+
}
|
|
387
|
+
// ========================================================================
|
|
388
|
+
// Tool Operations
|
|
389
|
+
// ========================================================================
|
|
390
|
+
/**
|
|
391
|
+
* List all tools available from the server.
|
|
392
|
+
*/
|
|
393
|
+
async listTools() {
|
|
394
|
+
this.ensureConnected();
|
|
395
|
+
const result = await this.client.listTools(void 0, {
|
|
396
|
+
timeout: this.timeout
|
|
397
|
+
});
|
|
398
|
+
return result.tools;
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* Call a tool on the server.
|
|
402
|
+
*/
|
|
403
|
+
async callTool(name, args) {
|
|
404
|
+
this.ensureConnected();
|
|
405
|
+
this.log("debug", `Calling tool: ${name}`);
|
|
406
|
+
try {
|
|
407
|
+
const result = await this.client.callTool(
|
|
408
|
+
{ name, arguments: args },
|
|
409
|
+
void 0,
|
|
410
|
+
{ timeout: this.timeout }
|
|
411
|
+
);
|
|
412
|
+
this.log("debug", `Tool ${name} executed successfully`);
|
|
413
|
+
return result;
|
|
414
|
+
} catch (error) {
|
|
415
|
+
this.log("error", `Tool ${name} failed: ${error}`);
|
|
416
|
+
throw this.wrapError(error);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
// ========================================================================
|
|
420
|
+
// Resource Operations
|
|
421
|
+
// ========================================================================
|
|
422
|
+
/**
|
|
423
|
+
* List all resources available from the server.
|
|
424
|
+
*/
|
|
425
|
+
async listResources() {
|
|
426
|
+
this.ensureConnected();
|
|
427
|
+
if (!this.serverCapabilities?.resources) {
|
|
428
|
+
return [];
|
|
429
|
+
}
|
|
430
|
+
const result = await this.client.listResources(void 0, {
|
|
431
|
+
timeout: this.timeout
|
|
432
|
+
});
|
|
433
|
+
return result.resources;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Read a resource from the server.
|
|
437
|
+
*/
|
|
438
|
+
async readResource(uri) {
|
|
439
|
+
this.ensureConnected();
|
|
440
|
+
return await this.client.readResource({ uri }, { timeout: this.timeout });
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Subscribe to resource updates.
|
|
444
|
+
*/
|
|
445
|
+
async subscribeResource(uri) {
|
|
446
|
+
this.ensureConnected();
|
|
447
|
+
await this.client.subscribeResource({ uri }, { timeout: this.timeout });
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Unsubscribe from resource updates.
|
|
451
|
+
*/
|
|
452
|
+
async unsubscribeResource(uri) {
|
|
453
|
+
this.ensureConnected();
|
|
454
|
+
await this.client.unsubscribeResource({ uri }, { timeout: this.timeout });
|
|
455
|
+
}
|
|
456
|
+
// ========================================================================
|
|
457
|
+
// Prompt Operations
|
|
458
|
+
// ========================================================================
|
|
459
|
+
/**
|
|
460
|
+
* List all prompts available from the server.
|
|
461
|
+
*/
|
|
462
|
+
async listPrompts() {
|
|
463
|
+
this.ensureConnected();
|
|
464
|
+
if (!this.serverCapabilities?.prompts) {
|
|
465
|
+
return [];
|
|
466
|
+
}
|
|
467
|
+
const result = await this.client.listPrompts(void 0, {
|
|
468
|
+
timeout: this.timeout
|
|
469
|
+
});
|
|
470
|
+
return result.prompts;
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Get a prompt from the server.
|
|
474
|
+
*/
|
|
475
|
+
async getPrompt(name, args) {
|
|
476
|
+
this.ensureConnected();
|
|
477
|
+
return await this.client.getPrompt(
|
|
478
|
+
{ name, arguments: args },
|
|
479
|
+
{ timeout: this.timeout }
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
// ========================================================================
|
|
483
|
+
// Roots Operations
|
|
484
|
+
// ========================================================================
|
|
485
|
+
/**
|
|
486
|
+
* Get the configured roots.
|
|
487
|
+
*/
|
|
488
|
+
get roots() {
|
|
489
|
+
return [...this._roots];
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Update the roots and notify the server.
|
|
493
|
+
*/
|
|
494
|
+
async setRoots(roots) {
|
|
495
|
+
this.log("debug", `Updating roots to ${roots.length} entries`);
|
|
496
|
+
this._roots = [...roots];
|
|
497
|
+
if (this.isConnected && this.client) {
|
|
498
|
+
try {
|
|
499
|
+
await this.client.sendRootsListChanged();
|
|
500
|
+
} catch (error) {
|
|
501
|
+
this.log("debug", `Failed to send roots/list_changed: ${error}`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
// ========================================================================
|
|
506
|
+
// Handler Registration
|
|
507
|
+
//
|
|
508
|
+
// Setters STORE the host handler (and, for notifications, the SDK handler
|
|
509
|
+
// registered in `registerServerHandlers` delegates to the stored callback).
|
|
510
|
+
// This is the host-overridable layer at the core of bug #13.
|
|
511
|
+
// ========================================================================
|
|
512
|
+
/**
|
|
513
|
+
* Set a handler for resource updated notifications.
|
|
514
|
+
*/
|
|
515
|
+
setResourceUpdatedHandler(handler) {
|
|
516
|
+
this.resourceUpdatedHandler = handler;
|
|
517
|
+
this.log("debug", "Resource updated handler registered");
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Set a handler for resource list changed notifications.
|
|
521
|
+
*/
|
|
522
|
+
setResourceListChangedHandler(handler) {
|
|
523
|
+
this.resourceListChangedHandler = handler;
|
|
524
|
+
this.log("debug", "Resource list changed handler registered");
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Set a handler for tool list changed notifications.
|
|
528
|
+
*/
|
|
529
|
+
setToolListChangedHandler(handler) {
|
|
530
|
+
this.toolListChangedHandler = handler;
|
|
531
|
+
this.log("debug", "Tool list changed handler registered");
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Set a handler for prompt list changed notifications.
|
|
535
|
+
*/
|
|
536
|
+
setPromptListChangedHandler(handler) {
|
|
537
|
+
this.promptListChangedHandler = handler;
|
|
538
|
+
this.log("debug", "Prompt list changed handler registered");
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* Set a handler for elicitation requests. When set, the server's
|
|
542
|
+
* `elicitation/create` REQUEST is answered with the host's decision; when
|
|
543
|
+
* unset the request is declined ({action:"cancel"}).
|
|
544
|
+
*/
|
|
545
|
+
setElicitationHandler(handler) {
|
|
546
|
+
this.elicitationHandler = handler;
|
|
547
|
+
this.log("debug", "Elicitation handler registered");
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Set a handler for sampling (`sampling/createMessage`) requests. When set,
|
|
551
|
+
* the server request is answered with the host's result; when unset the
|
|
552
|
+
* request is rejected with "Method not found".
|
|
553
|
+
*/
|
|
554
|
+
setSamplingHandler(handler) {
|
|
555
|
+
this.samplingHandler = handler;
|
|
556
|
+
this.log("debug", "Sampling handler registered");
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Set a handler for progress notifications.
|
|
560
|
+
*/
|
|
561
|
+
setProgressHandler(handler) {
|
|
562
|
+
this.progressHandler = handler;
|
|
563
|
+
this.log("debug", "Progress handler registered");
|
|
564
|
+
}
|
|
565
|
+
// ========================================================================
|
|
566
|
+
// Private Methods
|
|
567
|
+
// ========================================================================
|
|
568
|
+
ensureConnected() {
|
|
569
|
+
if (!this.isConnected || !this.client) {
|
|
570
|
+
throw new MCPError(
|
|
571
|
+
"Not connected to MCP server",
|
|
572
|
+
"NOT_CONNECTED" /* NOT_CONNECTED */,
|
|
573
|
+
void 0,
|
|
574
|
+
{ serverName: this.serverName }
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Normalize an SDK/transport error into an MCPError. Session-expiry style
|
|
580
|
+
* failures (404 session / -32001) are surfaced as SESSION_ERROR so callers
|
|
581
|
+
* (the pool) can decide to reconnect; the SDK's StreamableHTTP transport
|
|
582
|
+
* already attempts a bounded reconnect re-using the session id before this.
|
|
583
|
+
*/
|
|
584
|
+
wrapError(error) {
|
|
585
|
+
if (error instanceof MCPError) return error;
|
|
586
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
587
|
+
const code = error.code;
|
|
588
|
+
if (code === -32001 || /\b404\b|session/i.test(message)) {
|
|
589
|
+
return new MCPError(message, "SESSION_ERROR" /* SESSION_ERROR */, { code }, {
|
|
590
|
+
serverName: this.serverName
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return new MCPError(message, "SERVER_ERROR" /* SERVER_ERROR */, { code }, {
|
|
594
|
+
serverName: this.serverName
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
log(level, message, details) {
|
|
598
|
+
const msg = `[${this.serverName}] ${message}`;
|
|
599
|
+
if (this.logHandler) {
|
|
600
|
+
this.logHandler({
|
|
601
|
+
level,
|
|
602
|
+
message: msg,
|
|
603
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
604
|
+
serverName: this.serverName,
|
|
605
|
+
details
|
|
606
|
+
});
|
|
607
|
+
} else {
|
|
608
|
+
if (process.env.INDUSAGI_DEBUG || level === "error") {
|
|
609
|
+
const prefix = `[MCP:${level.toUpperCase()}]`;
|
|
610
|
+
if (details) {
|
|
611
|
+
if (level === "error") {
|
|
612
|
+
console.error(prefix, msg, details);
|
|
613
|
+
} else {
|
|
614
|
+
console.log(prefix, msg, details);
|
|
615
|
+
}
|
|
616
|
+
} else {
|
|
617
|
+
if (level === "error") {
|
|
618
|
+
console.error(prefix, msg);
|
|
619
|
+
} else {
|
|
620
|
+
console.log(prefix, msg);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
function mapToSdkElicitResult(result) {
|
|
628
|
+
if (result.action === "accept") {
|
|
629
|
+
return {
|
|
630
|
+
action: "accept",
|
|
631
|
+
content: result.content ?? {}
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
return { action: result.action };
|
|
635
|
+
}
|
|
636
|
+
function isAuthRequiredError(err) {
|
|
637
|
+
if (err == null) return false;
|
|
638
|
+
if (err instanceof UnauthorizedError) return true;
|
|
639
|
+
if (typeof err === "object") {
|
|
640
|
+
const code = err.code;
|
|
641
|
+
if (code === 401 || code === "401") return true;
|
|
642
|
+
}
|
|
643
|
+
if (err instanceof Error) {
|
|
644
|
+
const msg = err.message;
|
|
645
|
+
if (/unauthorized/i.test(msg)) return true;
|
|
646
|
+
if (/authentication required/i.test(msg)) return true;
|
|
647
|
+
if (/auth required/i.test(msg)) return true;
|
|
648
|
+
if (err.name === "UnauthorizedError") return true;
|
|
649
|
+
}
|
|
650
|
+
return false;
|
|
651
|
+
}
|
|
652
|
+
function sanitizeEnv(env) {
|
|
653
|
+
const out = {};
|
|
654
|
+
for (const [k, v] of Object.entries(env)) {
|
|
655
|
+
if (typeof v === "string") out[k] = v;
|
|
656
|
+
}
|
|
657
|
+
return out;
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
// src/capabilities/kernel/spec.ts
|
|
661
|
+
function coerceInput(raw) {
|
|
662
|
+
if (typeof raw === "string") {
|
|
663
|
+
const trimmed = raw.trim();
|
|
664
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
|
|
665
|
+
try {
|
|
666
|
+
return JSON.parse(trimmed);
|
|
667
|
+
} catch {
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return raw;
|
|
671
|
+
}
|
|
672
|
+
if (raw === null || raw === void 0) {
|
|
673
|
+
return {};
|
|
674
|
+
}
|
|
675
|
+
return raw;
|
|
676
|
+
}
|
|
677
|
+
function describeThrow(err) {
|
|
678
|
+
if (err instanceof Error) return err.message;
|
|
679
|
+
if (typeof err === "string") return err;
|
|
680
|
+
try {
|
|
681
|
+
return JSON.stringify(err);
|
|
682
|
+
} catch {
|
|
683
|
+
return String(err);
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
function projectOutcome(id, result) {
|
|
687
|
+
const blocks = result.content;
|
|
688
|
+
let output;
|
|
689
|
+
if (blocks.length === 1) {
|
|
690
|
+
const only = blocks[0];
|
|
691
|
+
output = only.kind === "text" ? only.text : only.value;
|
|
692
|
+
} else {
|
|
693
|
+
output = blocks;
|
|
694
|
+
}
|
|
695
|
+
return { id, output, isError: result.isError === true };
|
|
696
|
+
}
|
|
697
|
+
function defineTool(spec) {
|
|
698
|
+
return {
|
|
699
|
+
name: spec.name,
|
|
700
|
+
// Facade `AgentTool` surface: top-level schema fields + an `execute` adapter
|
|
701
|
+
// so the tool is usable by the high-level `Agent` as well as the kernel.
|
|
702
|
+
label: spec.name,
|
|
703
|
+
description: spec.description,
|
|
704
|
+
parameters: spec.parameters,
|
|
705
|
+
async execute(_toolCallId, params, signal) {
|
|
706
|
+
const ctx = {
|
|
707
|
+
cwd: process.cwd(),
|
|
708
|
+
signal: signal ?? new AbortController().signal
|
|
709
|
+
};
|
|
710
|
+
try {
|
|
711
|
+
const result = await spec.run(coerceInput(params), ctx);
|
|
712
|
+
return {
|
|
713
|
+
content: result.content.map(
|
|
714
|
+
(block) => block.kind === "text" ? { type: "text", text: block.text } : { type: "text", text: JSON.stringify(block.value) }
|
|
715
|
+
),
|
|
716
|
+
details: {},
|
|
717
|
+
isError: result.isError ?? false
|
|
718
|
+
};
|
|
719
|
+
} catch (err) {
|
|
720
|
+
return {
|
|
721
|
+
content: [{ type: "text", text: `${spec.name} did not finish: ${describeThrow(err)}` }],
|
|
722
|
+
details: {},
|
|
723
|
+
isError: true
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
},
|
|
727
|
+
descriptor() {
|
|
728
|
+
return {
|
|
729
|
+
name: spec.name,
|
|
730
|
+
description: spec.description,
|
|
731
|
+
parameters: spec.parameters
|
|
732
|
+
};
|
|
733
|
+
},
|
|
734
|
+
async invoke(call, ctx) {
|
|
735
|
+
if (ctx.signal.aborted) {
|
|
736
|
+
return {
|
|
737
|
+
id: call.id,
|
|
738
|
+
output: `Cancelled before ${spec.name} could begin.`,
|
|
739
|
+
isError: true
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
try {
|
|
743
|
+
const input = coerceInput(call.input);
|
|
744
|
+
const result = await spec.run(input, ctx);
|
|
745
|
+
return projectOutcome(call.id, result);
|
|
746
|
+
} catch (err) {
|
|
747
|
+
return {
|
|
748
|
+
id: call.id,
|
|
749
|
+
output: `${spec.name} did not finish: ${describeThrow(err)}`,
|
|
750
|
+
isError: true
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/facade/mcp-core/toolbox-bridge.ts
|
|
758
|
+
var NOOP_FS_NOT_SUPPORTED = "not supported in MCP-wrapped tools";
|
|
759
|
+
var noopFs = {
|
|
760
|
+
readFile: () => {
|
|
761
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
762
|
+
},
|
|
763
|
+
writeFile: () => {
|
|
764
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
765
|
+
},
|
|
766
|
+
stat: () => {
|
|
767
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
768
|
+
},
|
|
769
|
+
readdir: () => {
|
|
770
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
771
|
+
},
|
|
772
|
+
mkdir: () => {
|
|
773
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
774
|
+
},
|
|
775
|
+
rm: () => {
|
|
776
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
777
|
+
},
|
|
778
|
+
exists: () => {
|
|
779
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
var noopShell = {
|
|
783
|
+
exec: () => {
|
|
784
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
785
|
+
},
|
|
786
|
+
spawn: () => {
|
|
787
|
+
throw new MCPError(NOOP_FS_NOT_SUPPORTED, "CONFIG_ERROR");
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
function makeToolContext(signal) {
|
|
791
|
+
return {
|
|
792
|
+
cwd: process.cwd(),
|
|
793
|
+
fs: noopFs,
|
|
794
|
+
shell: noopShell,
|
|
795
|
+
signal,
|
|
796
|
+
budget: { kind: "tail", maxBytes: 5e4 }
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
function describeThrow2(err) {
|
|
800
|
+
if (err instanceof Error) return err.message;
|
|
801
|
+
if (typeof err === "string") return err;
|
|
802
|
+
try {
|
|
803
|
+
return JSON.stringify(err);
|
|
804
|
+
} catch {
|
|
805
|
+
return String(err);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
function projectMcpResult(result, logger) {
|
|
809
|
+
const blocks = [];
|
|
810
|
+
if (result.content && result.content.length > 0) {
|
|
811
|
+
for (const block of result.content) {
|
|
812
|
+
if (block.type === "text") {
|
|
813
|
+
blocks.push({ kind: "text", text: block.text });
|
|
814
|
+
} else if (block.type === "image") {
|
|
815
|
+
const len = typeof block.data === "string" ? block.data.length : 0;
|
|
816
|
+
blocks.push({ kind: "text", text: `[image ${block.mimeType}, ${len} chars base64]` });
|
|
817
|
+
logger?.debug(`mcp bridge: image block collapsed to text mention (${block.mimeType})`);
|
|
818
|
+
} else if (block.type === "resource") {
|
|
819
|
+
blocks.push({ kind: "text", text: `[resource ${block.resource.uri}]` });
|
|
820
|
+
} else {
|
|
821
|
+
blocks.push({ kind: "text", text: "[unknown content block]" });
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
if (result.structuredContent !== void 0) {
|
|
826
|
+
blocks.push({ kind: "json", value: result.structuredContent });
|
|
827
|
+
}
|
|
828
|
+
const content = blocks.length > 0 ? blocks : [{ kind: "text", text: "(no content)" }];
|
|
829
|
+
return {
|
|
830
|
+
content,
|
|
831
|
+
...result.isError === true ? { isError: true } : {}
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
function makeRunner(client, remoteName, logger) {
|
|
835
|
+
return async (input, ctx) => {
|
|
836
|
+
if (ctx.signal.aborted) {
|
|
837
|
+
return {
|
|
838
|
+
content: [{ kind: "text", text: "Cancelled before tool could start." }],
|
|
839
|
+
isError: true
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
try {
|
|
843
|
+
const args = input ?? {};
|
|
844
|
+
const result = await client.callTool(remoteName, args);
|
|
845
|
+
return projectMcpResult(result, logger);
|
|
846
|
+
} catch (err) {
|
|
847
|
+
const wrapped = err instanceof MCPError ? err : createServerError(describeThrow2(err), client.serverName);
|
|
848
|
+
logger?.error(`mcp bridge: tool "${remoteName}" failed: ${wrapped.message}`, wrapped);
|
|
849
|
+
return {
|
|
850
|
+
content: [{ kind: "text", text: `MCP tool failed: ${wrapped.message}` }],
|
|
851
|
+
isError: true
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
async function mcpClientToToolBox(client, options = {}) {
|
|
857
|
+
const prefix = options.namePrefix ?? "mcp";
|
|
858
|
+
const logger = options.logger;
|
|
859
|
+
const tools = await client.listTools();
|
|
860
|
+
const filtered = typeof options.filter === "function" ? tools.filter((t) => options.filter(t)) : tools;
|
|
861
|
+
const byName = /* @__PURE__ */ new Map();
|
|
862
|
+
for (const tool of filtered) {
|
|
863
|
+
const remoteName = tool.name;
|
|
864
|
+
const prefixed = `${prefix}__${remoteName}`;
|
|
865
|
+
const description = tool.description && tool.description.length > 0 ? tool.description : `<tool "${remoteName}" from MCP server "${client.serverName}">`;
|
|
866
|
+
const parameters = tool.inputSchema;
|
|
867
|
+
const def = defineTool({
|
|
868
|
+
name: prefixed,
|
|
869
|
+
description,
|
|
870
|
+
parameters,
|
|
871
|
+
run: makeRunner(client, remoteName, logger)
|
|
872
|
+
});
|
|
873
|
+
byName.set(prefixed, def);
|
|
874
|
+
}
|
|
875
|
+
const runner = {
|
|
876
|
+
async run(call, signal) {
|
|
877
|
+
const def = byName.get(call.name);
|
|
878
|
+
if (!def) {
|
|
879
|
+
return {
|
|
880
|
+
id: call.id,
|
|
881
|
+
output: `No tool "${call.name}" on MCP server "${client.serverName}".`,
|
|
882
|
+
isError: true
|
|
883
|
+
};
|
|
884
|
+
}
|
|
885
|
+
return def.invoke(call, makeToolContext(signal));
|
|
886
|
+
}
|
|
887
|
+
};
|
|
888
|
+
return {
|
|
889
|
+
descriptors() {
|
|
890
|
+
return Array.from(byName.values()).map((d) => d.descriptor());
|
|
891
|
+
},
|
|
892
|
+
runner
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
// src/connectors-sarvam/connect.ts
|
|
897
|
+
function resolveHome(p) {
|
|
898
|
+
if (!p.startsWith("~")) return p;
|
|
899
|
+
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
|
900
|
+
return home.length > 0 ? p.replace(/^~/, home) : p;
|
|
901
|
+
}
|
|
902
|
+
async function connectSarvamMcp(options) {
|
|
903
|
+
const id = options.id ?? "sarvam";
|
|
904
|
+
const apiKey = (options.apiKey?.trim() || process.env.SARVAM_API_KEY?.trim() || "").trim();
|
|
905
|
+
if (!apiKey) {
|
|
906
|
+
throw new Error(
|
|
907
|
+
"connectSarvamMcp: SARVAM_API_KEY missing (pass apiKey or set the env var)."
|
|
908
|
+
);
|
|
909
|
+
}
|
|
910
|
+
const baseUrl = options.baseUrl ?? process.env.SARVAM_API_BASE_URL ?? "https://api.sarvam.ai";
|
|
911
|
+
const basePath = resolveHome(options.basePath ?? process.env.SARVAM_MCP_BASE_PATH ?? "~/Desktop");
|
|
912
|
+
const command = options.command ?? "uvx";
|
|
913
|
+
const args = [...options.args ?? ["sarvam-mcp"]];
|
|
914
|
+
const env = {
|
|
915
|
+
...options.env ? { ...options.env } : {},
|
|
916
|
+
SARVAM_API_KEY: apiKey,
|
|
917
|
+
SARVAM_API_BASE_URL: baseUrl,
|
|
918
|
+
SARVAM_MCP_BASE_PATH: basePath
|
|
919
|
+
};
|
|
920
|
+
const client = new MCPClient({
|
|
921
|
+
name: id,
|
|
922
|
+
config: { command, args, env },
|
|
923
|
+
timeout: options.timeoutMs ?? 6e4
|
|
924
|
+
});
|
|
925
|
+
await client.connect();
|
|
926
|
+
const toolBox = await mcpClientToToolBox(client, {
|
|
927
|
+
namePrefix: id,
|
|
928
|
+
logger: options.logger
|
|
929
|
+
});
|
|
930
|
+
const tools = await client.listTools();
|
|
931
|
+
const prefixed = tools.map((t) => `${id}__${t.name}`);
|
|
932
|
+
let closed = false;
|
|
933
|
+
return {
|
|
934
|
+
id,
|
|
935
|
+
toolBox,
|
|
936
|
+
toolNames: prefixed,
|
|
937
|
+
client,
|
|
938
|
+
async close() {
|
|
939
|
+
if (closed) return;
|
|
940
|
+
closed = true;
|
|
941
|
+
try {
|
|
942
|
+
await client.disconnect();
|
|
943
|
+
} catch (e) {
|
|
944
|
+
options.logger?.error(`sarvam close failed: ${e.message}`, e);
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
// src/connectors-sarvam/toolbox.ts
|
|
951
|
+
async function sarvamToolBoxFromClient(client, options) {
|
|
952
|
+
return mcpClientToToolBox(client, {
|
|
953
|
+
...options,
|
|
954
|
+
namePrefix: options?.id ?? "sarvam"
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
export {
|
|
958
|
+
connectSarvamMcp,
|
|
959
|
+
sarvamToolBoxFromClient
|
|
960
|
+
};
|