managed-deepagents 0.10.5-dev.3 → 0.10.5-dev.5

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.
Files changed (35) hide show
  1. package/README.md +48 -19
  2. package/dist/connection-authorization.d.ts +1 -21
  3. package/dist/connection-authorization.d.ts.map +1 -1
  4. package/dist/connection-authorization.js +1 -30
  5. package/dist/connection-authorization.js.map +1 -1
  6. package/dist/connectors/mcp/index.d.ts +4 -10
  7. package/dist/connectors/mcp/index.d.ts.map +1 -1
  8. package/dist/connectors/mcp/index.js +61 -474
  9. package/dist/connectors/mcp/index.js.map +1 -1
  10. package/dist/connectors/mcp/schema.d.ts.map +1 -1
  11. package/dist/connectors/mcp/schema.js +37 -12
  12. package/dist/connectors/mcp/schema.js.map +1 -1
  13. package/dist/connectors/mcp/types.d.ts +10 -7
  14. package/dist/connectors/mcp/types.d.ts.map +1 -1
  15. package/dist/credential-gate.d.ts +14 -12
  16. package/dist/credential-gate.d.ts.map +1 -1
  17. package/dist/credential-gate.js +28 -171
  18. package/dist/credential-gate.js.map +1 -1
  19. package/dist/tool-gateway/auth.d.ts +50 -0
  20. package/dist/tool-gateway/auth.d.ts.map +1 -0
  21. package/dist/tool-gateway/auth.js +99 -0
  22. package/dist/tool-gateway/auth.js.map +1 -0
  23. package/dist/tool-gateway/cards.d.ts +19 -0
  24. package/dist/tool-gateway/cards.d.ts.map +1 -0
  25. package/dist/tool-gateway/cards.js +198 -0
  26. package/dist/tool-gateway/cards.js.map +1 -0
  27. package/dist/tool-gateway/connect-first.d.ts +21 -0
  28. package/dist/tool-gateway/connect-first.d.ts.map +1 -0
  29. package/dist/tool-gateway/connect-first.js +94 -0
  30. package/dist/tool-gateway/connect-first.js.map +1 -0
  31. package/package.json +7 -7
  32. package/dist/connectors/mcp/langsmith-url.d.ts +0 -5
  33. package/dist/connectors/mcp/langsmith-url.d.ts.map +0 -1
  34. package/dist/connectors/mcp/langsmith-url.js +0 -35
  35. package/dist/connectors/mcp/langsmith-url.js.map +0 -1
@@ -29,21 +29,21 @@
29
29
  * notion: {
30
30
  * transport: "http",
31
31
  * url: "https://api.smith.langchain.com/v1/managed-tools/servers/68a8938f-f90d-40a9-a1db-0c6263696e70/mcp",
32
+ * auth: "langsmith",
32
33
  * },
33
34
  * },
34
35
  * });
35
36
  * ```
36
37
  */
37
38
  import { loadMcpTools, MCPAdapter, } from "@langchain/mcp-adapters";
38
- import { AGENT_AUTH_TIMEOUT_MS, agentAuthHeaders, AgentAuth, } from "../../agent-auth.js";
39
- import { CONNECT_ON_USE_METADATA, raiseCredentialAuthorizationRequired, readUserConnectionGrant, ToolCredentialRequiredError, } from "../../connection-authorization.js";
39
+ import { AgentAuth } from "../../agent-auth.js";
40
+ import { readUserConnectionGrant, } from "../../connection-authorization.js";
40
41
  import { defineExtension } from "../../extension.js";
41
42
  import { connections, isConnectionReference, } from "../../connections.js";
42
- import { fetchWithTimeout } from "../../runtime/http.js";
43
- import { logger } from "../../runtime/log.js";
44
- import { isRecord } from "../../values.js";
43
+ import { langsmithHeaders, langsmithProfile, onLangSmithOrigin, toolGatewayContext, usesLangSmithAuth, } from "../../tool-gateway/auth.js";
44
+ import { withCards } from "../../tool-gateway/cards.js";
45
+ import { connectionNeeded, needsAConnection, } from "../../tool-gateway/connect-first.js";
45
46
  import { mcpServersConfig } from "./schema.js";
46
- import { isLangSmithManagedToolsPath, isLangSmithManagedToolsUrl, } from "./langsmith-url.js";
47
47
  import { selectTools } from "../tool-selection.js";
48
48
  /**
49
49
  * MCP tools loaded per connector declaration, cached for its object lifetime.
@@ -91,7 +91,9 @@ export function clearManagedMcpToolsCacheForTests(connectors) {
91
91
  * The credential gate's view of the declared MCP connectors.
92
92
  *
93
93
  * One consumer per declaration that names a user-owned connection or a
94
- * LangSmith-managed server. Both load after caller identity is available.
94
+ * server with LangSmith auth. User-connected servers need a person; servers
95
+ * with LangSmith auth load as the run's person, or as the agent in an
96
+ * agent-owned schedule.
95
97
  */
96
98
  export function mcpCredentialConsumers(connectors) {
97
99
  const out = [];
@@ -103,7 +105,7 @@ export function mcpCredentialConsumers(connectors) {
103
105
  }
104
106
  const definition = connector;
105
107
  const userConnections = userConnectionReferences(definition);
106
- const hasLangSmith = Object.values(definition.servers).some(isLangSmithServer);
108
+ const hasLangSmith = Object.values(definition.servers).some(usesLangSmithAuth);
107
109
  if (userConnections.length === 0 && !hasLangSmith) {
108
110
  continue;
109
111
  }
@@ -112,10 +114,7 @@ export function mcpCredentialConsumers(connectors) {
112
114
  credentials: userConnections,
113
115
  requiresIdentity: userConnections.length > 0,
114
116
  collectPendingCredentials: hasLangSmith
115
- ? (context) => collectPendingManagedToolsCredentials(definition, context)
116
- : undefined,
117
- connectLinks: hasLangSmith && definition.jitAuth === true
118
- ? (context, wanted) => managedToolsConnectLinks(definition, context, wanted)
117
+ ? (context) => connectionsNeeded(definition, context)
119
118
  : undefined,
120
119
  load: (accessTokens, context) => loadCallerMcpTools(definition, accessTokens, context),
121
120
  });
@@ -157,7 +156,7 @@ function mcpRequirements(name, connectors) {
157
156
  autoReply: false,
158
157
  requiredPermissions: [],
159
158
  requiredEnv: [],
160
- needsDeveloperPrincipal: Object.values(connectors.servers).some((server) => isLangSmithManagedToolsPath(server.url)),
159
+ needsDeveloperPrincipal: Object.values(connectors.servers).some(usesLangSmithAuth),
161
160
  userConnections: userSlugs,
162
161
  agentConnections: agentSlugs,
163
162
  providerConfig: {},
@@ -169,8 +168,8 @@ async function createClientAndLoadTools(connectors) {
169
168
  warnDeferredUserConnectionServers(userConnection);
170
169
  }
171
170
  if (langsmith.length > 0) {
172
- console.warn(`[managed-deepagents] LangSmith MCP server(s) ${langsmith.join(", ")} ` +
173
- "load per authenticated caller.");
171
+ console.warn(`[managed-deepagents] MCP server(s) ${langsmith.join(", ")} with ` +
172
+ 'auth "langsmith" load per run.');
174
173
  }
175
174
  if (Object.keys(eager).length === 0) {
176
175
  return [];
@@ -183,20 +182,17 @@ async function createClientAndLoadTools(connectors) {
183
182
  *
184
183
  * Not process-cached here: grants are per caller, so the gate owns both the
185
184
  * cache and closing the returned adapter. Acting as the agent (no principal),
186
- * only LangSmith servers load.
185
+ * only servers with LangSmith auth load.
187
186
  */
188
187
  async function loadCallerMcpTools(connectors, accessTokens, context) {
189
- const { userConnection, langsmith } = partitionMcpServers(connectors.servers);
188
+ const { userConnection } = partitionMcpServers(connectors.servers);
190
189
  const agentAuth = new AgentAuth(context);
191
190
  const connectable = {};
192
191
  for (const name of context.principalId ? userConnection : []) {
193
192
  const server = connectors.servers[name];
194
193
  const connection = server?.connection;
195
- if (!server ||
196
- isLangSmithServer(server) ||
197
- !isConnectionReference(connection)) {
194
+ if (!server || !isConnectionReference(connection))
198
195
  continue;
199
- }
200
196
  const accessToken = accessTokens.get(connection.slug);
201
197
  if (!accessToken) {
202
198
  throw new Error(`MCP user connection "${connection.slug}" has no access token`);
@@ -204,356 +200,41 @@ async function loadCallerMcpTools(connectors, accessTokens, context) {
204
200
  const slug = connection.slug;
205
201
  connectable[name] = withConnectionProvider(server, slug, accessToken, () => readUserConnectionGrant(agentAuth, slug).then((grant) => grant.token));
206
202
  }
207
- const { servers: loadableLangsmith, deferred } = await loadableLangSmithServers(connectors, langsmith, context);
208
- Object.assign(connectable, loadableLangsmith);
203
+ const gateway = langsmithServers(connectors, context);
204
+ Object.assign(connectable, gateway);
209
205
  if (Object.keys(connectable).length === 0) {
210
206
  return { tools: [], close: async () => { } };
211
207
  }
212
- const { tools, client } = await loadToolsFromServers(connectors, connectable, {
213
- stored: deferred,
214
- askToConnect: new Set(connectors.jitAuth === true ? Object.keys(loadableLangsmith) : []),
215
- });
208
+ const { tools, client } = await loadToolsFromServers(connectors, connectable, new Set(Object.keys(gateway)));
216
209
  return { tools, close: () => client.close() };
217
210
  }
218
211
  /**
219
- * Probe LangSmith MCP servers once: ready configs, pending and deferred credentials.
220
- *
221
- * Shared by load (interrupt if pending) and the credential-gate collector
222
- * (return pending only). With `jitAuth`, a kit's missing credentials that
223
- * come with stored tools are deferred to first use instead of pending.
224
- * Transport failures follow `throwOnLoadError`; authorization failures are
225
- * never skipped.
226
- */
227
- async function resolveLangSmithServers(connectors, serverNames, context) {
228
- const prepared = prepareLangSmithServers(connectors, serverNames, context);
229
- if (!prepared)
230
- return { servers: {}, pending: [], deferred: {} };
231
- const { matching, headers } = prepared;
232
- const servers = {};
233
- const pending = [];
234
- const deferred = {};
235
- for (const { name, declared, url } of matching) {
236
- let probe;
237
- try {
238
- probe = await probeLangSmithServer(url, headers);
239
- }
240
- catch (error) {
241
- if (connectors.throwOnLoadError !== false)
242
- throw error;
243
- console.warn(`[managed-deepagents] MCP server "${name}" failed to load and was skipped: ${error}`);
244
- continue;
245
- }
246
- if (!context.principalId &&
247
- (probe.status === 409 || probe.status === 428)) {
248
- warnAgentCredentialMissing(name);
249
- continue;
250
- }
251
- const required = credentialsFromLangSmithProbe(name, probe, connectors.jitAuth === true);
252
- if (!context.principalId &&
253
- (required.pending.length > 0 || required.deferred.length > 0)) {
254
- // No one can connect the agent's credentials during the run.
255
- warnAgentCredentialMissing(name);
256
- required.pending = [];
257
- required.deferred = [];
258
- }
259
- if (required.pending.length > 0) {
260
- pending.push(...required.pending);
261
- continue;
262
- }
263
- const server = {
264
- ...declared,
265
- transport: "http",
266
- headers,
267
- };
268
- // A call that declares elicitation makes LangSmith answer with a bare URL
269
- // elicitation instead of the 428 naming the credential to connect.
270
- servers[name] =
271
- connectors.jitAuth === true && server.mode !== "legacy"
272
- ? { ...server, elicitation: false }
273
- : server;
274
- if (required.deferred.length > 0)
275
- deferred[name] = required.deferred;
276
- }
277
- return { servers, pending, deferred };
278
- }
279
- async function loadableLangSmithServers(connectors, serverNames, context) {
280
- const { servers, pending, deferred } = await resolveLangSmithServers(connectors, serverNames, context);
281
- // Authorization failures must still stop the load so it remains uncached.
282
- if (pending.length > 0) {
283
- raiseCredentialAuthorizationRequired(pending);
284
- }
285
- return { servers, deferred };
286
- }
287
- /**
288
- * Collect pending Managed Tools credentials without interrupting.
289
- *
290
- * Incomplete 428s still throw a clear Error. Used by the credential
291
- * gate so Managed Tools misses combine with ordinary connection misses.
292
- */
293
- export async function collectPendingManagedToolsCredentials(connectors, context) {
294
- const serverNames = Object.entries(connectors.servers)
295
- .filter(([, server]) => isLangSmithServer(server))
296
- .map(([name]) => name);
297
- return (await resolveLangSmithServers(connectors, serverNames, context))
298
- .pending;
299
- }
300
- /**
301
- * Fresh connect links for the wanted slugs of each kit, and only those kits.
302
- *
303
- * The gate caches loaded tools, so the links their metadata carries can
304
- * predate a connection; a new listing names only what is still missing.
305
- */
306
- async function managedToolsConnectLinks(connectors, context, wanted) {
307
- const prepared = prepareLangSmithServers(connectors, [...wanted.keys()], context);
308
- if (!prepared)
309
- return [];
310
- const links = [];
311
- for (const { name, url } of prepared.matching) {
312
- let pending;
313
- try {
314
- const probe = await probeLangSmithServer(url, prepared.headers);
315
- pending = credentialsFromLangSmithProbe(name, probe, false).pending;
316
- }
317
- catch (error) {
318
- // Each refused call still asks on its own with the link from its 428.
319
- logger.warn("could not list connect links for LangSmith MCP server " +
320
- `"${logger.logIdentifier(name)}": ${logger.safeErrorLabel(error)}`);
321
- continue;
322
- }
323
- const slugs = wanted.get(name);
324
- links.push(...pending.filter((credential) => slugs?.has(credential.slug)));
325
- }
326
- return links;
327
- }
328
- function prepareLangSmithServers(connectors, serverNames, context) {
329
- if (serverNames.length === 0)
330
- return undefined;
331
- const matching = [];
332
- for (const name of serverNames) {
333
- const declared = connectors.servers[name];
334
- if (!declared || !isLangSmithServer(declared))
335
- continue;
336
- if (!isLangSmithManagedToolsUrl(declared.url, context.baseUrl)) {
337
- console.warn(`[managed-deepagents] MCP server "${name}" is not a LangSmith ` +
338
- "managed-tools URL for this deployment origin and was skipped.");
339
- continue;
340
- }
341
- matching.push({ name, declared, url: declared.url });
342
- }
343
- if (matching.length === 0)
344
- return undefined;
345
- if (!context.apiKey?.trim()) {
346
- throw new Error("LangSmith MCP servers require LANGSMITH_API_KEY at runtime");
347
- }
348
- return {
349
- matching,
350
- // Name exactly one owner: the caller's principal, or the agent when there is none.
351
- headers: {
352
- ...agentAuthHeaders(context),
353
- ...(context.principalId
354
- ? { "x-langsmith-identity": context.principalId }
355
- : {}),
356
- },
357
- };
358
- }
359
- function warnAgentCredentialMissing(serverName) {
360
- logger.warn(`LangSmith MCP server "${logger.logIdentifier(serverName)}" skipped or ` +
361
- "partly loaded: the agent has no credential for it. A workspace admin " +
362
- "can connect it for the agent environment.");
363
- }
364
- /**
365
- * Map a Managed Tools probe result to pending credentials from a complete 428
366
- * or a partial kit's `_meta`, or throw for incomplete 428s. With `jitAuth`,
367
- * `_meta` entries that carry stored tools are deferred instead of pending. No
368
- * pending credentials means the server's connected tools load.
369
- */
370
- function credentialsFromLangSmithProbe(serverName, probe, jitAuth) {
371
- if (probe.status === 200) {
372
- return credentialsFromLangSmithMeta(probe.body, serverName, jitAuth);
373
- }
374
- if (probe.status !== 428)
375
- return { pending: [], deferred: [] };
376
- const credentials = probe.body.credentials;
377
- if (Array.isArray(credentials)) {
378
- return {
379
- pending: pendingCredentialsFromLangsmithGateway428(credentials, serverName),
380
- deferred: [],
381
- };
382
- }
383
- const pending = pendingCredentialFromLangsmith428(probe.body, serverName);
384
- if (pending !== undefined)
385
- return { pending: [pending], deferred: [] };
386
- const verificationUrl = probe.body.verification_url;
387
- if (typeof verificationUrl === "string" && verificationUrl) {
388
- throw new Error(`LangSmith MCP server "${serverName}" requires authorization. ` +
389
- `Connect at ${verificationUrl}, or in LangSmith Tools, then retry the run`);
390
- }
391
- throw new Error(`LangSmith MCP server "${serverName}" requires credentials; ` +
392
- "connect it in LangSmith Tools before running the agent");
393
- }
394
- /**
395
- * Map the missing credentials an ALLOW_PARTIAL tool kit lists in `_meta`.
396
- *
397
- * The kit's connected tools work without these, so entries without a
398
- * complete link are skipped with a warning instead of failing the run.
399
- * With `jitAuth`, an entry with at least one valid stored tool is deferred to
400
- * first use; invalid stored definitions are skipped with a warning.
401
- */
402
- function credentialsFromLangSmithMeta(body, serverName, jitAuth) {
403
- const meta = isRecord(body.result) ? body.result._meta : undefined;
404
- const entries = isRecord(meta)
405
- ? meta["com.langchain.langsmith/missingCredentials"]
406
- : undefined;
407
- if (!Array.isArray(entries))
408
- return { pending: [], deferred: [] };
409
- const pending = [];
410
- const deferred = [];
411
- for (const entry of entries) {
412
- const credential = isRecord(entry)
413
- ? pendingCredentialFromLangsmith428(entry, serverName)
414
- : undefined;
415
- if (!isRecord(entry) || credential === undefined) {
416
- warnSkippedMetaCredential(serverName, entry);
417
- continue;
418
- }
419
- const tools = jitAuth ? storedToolDefinitions(serverName, entry.tools) : [];
420
- if (tools.length > 0) {
421
- deferred.push({ credential, tools });
422
- continue;
423
- }
424
- pending.push(credential);
425
- }
426
- return { pending, deferred };
427
- }
428
- /** The valid MCP tool definitions LMT stored for a provider; warns if any were not. */
429
- function storedToolDefinitions(serverName, tools) {
430
- if (!Array.isArray(tools))
431
- return [];
432
- const valid = tools.filter(isMcpTool);
433
- if (valid.length < tools.length) {
434
- logger.warn("skipped invalid stored tools for LangSmith MCP server " +
435
- `"${logger.logIdentifier(serverName)}"`);
436
- }
437
- return valid;
438
- }
439
- function isMcpTool(value) {
440
- if (!isRecord(value))
441
- return false;
442
- const { name, title, description, inputSchema, annotations } = value;
443
- return (typeof name === "string" &&
444
- name.length > 0 &&
445
- (title === undefined || typeof title === "string") &&
446
- (description === undefined || typeof description === "string") &&
447
- isRecord(inputSchema) &&
448
- inputSchema.type === "object" &&
449
- (annotations === undefined || isRecord(annotations)));
450
- }
451
- /** Name the skipped entry's provider and missing fields, never their values. */
452
- function warnSkippedMetaCredential(serverName, entry) {
453
- const server = logger.logIdentifier(serverName);
454
- if (typeof entry !== "object" || entry === null) {
455
- logger.warn(`skipped missing credential for LangSmith MCP server "${server}": entry is not an object`);
456
- return;
457
- }
458
- const fields = entry;
459
- const label = fields.display_name || fields.slug;
460
- const provider = typeof label === "string" && label
461
- ? logger.logIdentifier(label)
462
- : "unknown";
463
- const missing = ["slug", "verification_url", "auth_id"].filter((field) => typeof fields[field] !== "string" || !fields[field]);
464
- logger.warn(`skipped missing credential for LangSmith MCP server "${server}" ` +
465
- `(provider=${provider}): missing ${missing.join(", ")}`);
466
- }
467
- /**
468
- * Map every entry of a gateway 428 to an interrupt credential.
469
- *
470
- * Entries without a complete link cannot be completed from an interrupt, so
471
- * any of them throw with every missing name before an interrupt is shown.
212
+ * The servers with LangSmith auth on the deployment's origin, with the headers
213
+ * that name whose credentials Tool Gateway uses.
472
214
  */
473
- function pendingCredentialsFromLangsmithGateway428(credentials, serverName) {
474
- const { pending, unresolved } = partitionLangSmith428Entries(credentials, serverName);
475
- if (unresolved.length > 0 || pending.length === 0) {
476
- const names = unresolved.length > 0 ? unresolved.join(", ") : serverName;
477
- throw new Error(`LangSmith MCP server "${serverName}" requires credentials for ${names}; ` +
478
- "connect them in LangSmith Tools before running the agent");
479
- }
480
- return pending;
481
- }
482
- /**
483
- * Split 428 entries into interrupt credentials and the labels of entries
484
- * without a complete link (`display_name`, `slug`, else the server name).
485
- */
486
- function partitionLangSmith428Entries(entries, serverName) {
487
- const pending = [];
488
- const unresolved = [];
489
- for (const entry of entries) {
490
- const credential = isRecord(entry)
491
- ? pendingCredentialFromLangsmith428(entry, serverName)
492
- : undefined;
493
- if (credential !== undefined) {
494
- pending.push(credential);
215
+ function langsmithServers(connectors, context) {
216
+ const gateway = toolGatewayContext(context);
217
+ const out = {};
218
+ for (const [name, server] of Object.entries(connectors.servers)) {
219
+ if (!usesLangSmithAuth(server) ||
220
+ !onLangSmithOrigin(name, server, gateway.baseUrl)) {
495
221
  continue;
496
222
  }
497
- const label = isRecord(entry)
498
- ? entry.display_name || entry.slug
499
- : undefined;
500
- unresolved.push(typeof label === "string" && label ? label : serverName);
223
+ const headers = langsmithHeaders(gateway, langsmithProfile(server));
224
+ out[name] = { ...server, headers: { ...server.headers, ...headers } };
501
225
  }
502
- return { pending, unresolved };
503
- }
504
- /**
505
- * Build an interrupt credential only when LMT returns the full triple.
506
- * LMT marks API-key servers with `kind: "secret"`; every other 428 is OAuth.
507
- * `provider` labels the credential when LMT does not return `display_name`.
508
- */
509
- function pendingCredentialFromLangsmith428(body, provider) {
510
- const verificationUrl = body.verification_url;
511
- const authId = body.auth_id;
512
- const slug = body.slug;
513
- if (typeof verificationUrl !== "string" ||
514
- !verificationUrl ||
515
- typeof authId !== "string" ||
516
- !authId ||
517
- typeof slug !== "string" ||
518
- !slug) {
519
- return undefined;
520
- }
521
- const displayName = body.display_name;
522
- return {
523
- slug,
524
- kind: body.kind === "secret" ? "secret" : "oauth2",
525
- connect_url: verificationUrl,
526
- auth_id: authId,
527
- provider: typeof displayName === "string" && displayName ? displayName : provider,
528
- };
226
+ return out;
529
227
  }
530
- async function probeLangSmithServer(url, headers) {
531
- const response = await fetchWithTimeout(url, {
532
- method: "POST",
533
- redirect: "error",
534
- headers,
535
- body: JSON.stringify({
536
- jsonrpc: "2.0",
537
- id: "mda-auth-probe",
538
- method: "tools/list",
539
- }),
540
- }, AGENT_AUTH_TIMEOUT_MS);
541
- return {
542
- status: response.status,
543
- body: (await response.json().catch((error) => {
544
- // Keep 428 authoritative even when its response body is unavailable.
545
- if (response.status === 428 || error instanceof SyntaxError)
546
- return {};
547
- throw error;
548
- })),
549
- };
228
+ /** Temporary (see `connect-first`): connections servers need before they list tools. */
229
+ async function connectionsNeeded(connectors, context) {
230
+ const servers = Object.values(langsmithServers(connectors, context));
231
+ const pending = await Promise.all(servers.map((server) => connectionNeeded(server.url, server.headers ?? {})));
232
+ return pending.flat();
550
233
  }
551
234
  /** Hand each agent-owned connection to the adapter as an `AuthProvider`. */
552
235
  async function withAgentConnections(servers) {
553
236
  const out = {};
554
237
  for (const [name, server] of Object.entries(servers)) {
555
- if (isLangSmithServer(server))
556
- continue;
557
238
  const connection = server.connection;
558
239
  if (!isConnectionReference(connection)) {
559
240
  out[name] = server;
@@ -597,15 +278,12 @@ function usesUserConnection(server) {
597
278
  return (isConnectionReference(server.connection) &&
598
279
  server.connection.owner.type === "user");
599
280
  }
600
- function isLangSmithServer(server) {
601
- return (typeof server.url === "string" && isLangSmithManagedToolsPath(server.url));
602
- }
603
281
  function partitionMcpServers(servers) {
604
282
  const eager = {};
605
283
  const userConnection = [];
606
284
  const langsmith = [];
607
285
  for (const [name, server] of Object.entries(servers)) {
608
- if (isLangSmithServer(server)) {
286
+ if (usesLangSmithAuth(server)) {
609
287
  langsmith.push(name);
610
288
  }
611
289
  else if (usesUserConnection(server)) {
@@ -622,18 +300,24 @@ function warnDeferredUserConnectionServers(serverNames) {
622
300
  `a user connection; tools load after the pre-run credential gate ` +
623
301
  `confirms grants for the caller.`);
624
302
  }
625
- async function loadToolsFromServers(connectors, connectable, kits = {}) {
303
+ async function loadToolsFromServers(connectors, connectable, gateway = new Set()) {
626
304
  const { prefixToolNameWithServerName, throwOnLoadError, onConnectionError } = connectors;
627
305
  const client = new MCPAdapter({
628
- servers: Object.fromEntries(Object.entries(connectable).map(([name, { includeTools: _includeTools, excludeTools: _excludeTools, connection: _connection, ...server },]) => [name, server])),
306
+ servers: Object.fromEntries(Object.entries(connectable).map(([name, { includeTools: _includeTools, excludeTools: _excludeTools, connection: _connection, auth: _auth, ...server },]) => [name, server])),
629
307
  prefixToolNameWithServerName,
630
308
  throwOnLoadError,
631
- onConnectionError,
309
+ onConnectionError: gateway.size > 0
310
+ ? ({ serverName, error }) => {
311
+ // Temporary (see `connect-first`): skip a server until it is connected.
312
+ if (!(gateway.has(serverName) && needsAConnection(serverName, error)))
313
+ throw error;
314
+ }
315
+ : onConnectionError,
632
316
  });
633
317
  // The adapter prefixes by default; tool selection strips the same prefix.
634
318
  const prefixed = prefixToolNameWithServerName ?? true;
635
319
  try {
636
- const tools = await loadToolsByServer(client, connectable, prefixed, kits);
320
+ const tools = await loadToolsByServer(client, connectable, prefixed, gateway, throwOnLoadError);
637
321
  assertNoToolNameCollisions(tools);
638
322
  return { tools, client };
639
323
  }
@@ -642,135 +326,38 @@ async function loadToolsFromServers(connectors, connectable, kits = {}) {
642
326
  throw error;
643
327
  }
644
328
  }
645
- async function loadToolsByServer(client, servers, prefixToolNameWithServerName, { stored = {}, askToConnect = new Set() } = {}) {
329
+ async function loadToolsByServer(client, servers, prefixToolNameWithServerName, gateway, throwOnLoadError) {
646
330
  // One discovery: listTools(name) would rediscover every server on each call.
647
331
  const toolsets = await client.listToolsets();
648
332
  const tools = [];
649
333
  for (const [serverName, server] of Object.entries(servers)) {
650
- let serverTools = toolsets[serverName] ?? [];
651
- const definitions = stored[serverName] ?? [];
652
- if (serverName in toolsets && definitions.length > 0) {
653
- serverTools = [
654
- ...serverTools,
655
- ...(await storedTools(client, serverName, server, definitions, serverTools, prefixToolNameWithServerName)),
656
- ];
657
- }
658
- if (askToConnect.has(serverName)) {
659
- serverTools = serverTools.map((tool) => askingToConnect(serverName, tool));
660
- }
334
+ if (!(serverName in toolsets))
335
+ continue;
336
+ const serverTools = gateway.has(serverName)
337
+ ? await toolsWithCards(client, serverName, server, prefixToolNameWithServerName, throwOnLoadError)
338
+ : (toolsets[serverName] ?? []);
661
339
  tools.push(...filterToolsForServer(serverName, server, serverTools, prefixToolNameWithServerName));
662
340
  }
663
341
  return tools;
664
342
  }
665
343
  /**
666
- * Bind a kit's stored definitions through the adapter's own tool path: the
667
- * server's connected client serves them as its listing, so calls reach the
668
- * kit by raw name exactly as live tools do. Live tools win a name clash.
669
- *
670
- * Each carries the credential it needs, so the gate can ask once per model step.
344
+ * A Tool Gateway server's tools, calling it through `withCards` so its
345
+ * questions show as the cards Studio and Slack render.
671
346
  */
672
- async function storedTools(adapter, serverName, server, deferred, live, prefixToolNameWithServerName) {
673
- const connected = await adapter.getClient(serverName);
674
- if (!connected) {
675
- logger.warn("skipped stored tools for LangSmith MCP server " +
676
- `"${logger.logIdentifier(serverName)}": it is not connected`);
347
+ async function toolsWithCards(adapter, serverName, server, prefixToolNameWithServerName, throwOnLoadError) {
348
+ const client = await adapter.getClient(serverName);
349
+ if (!client)
677
350
  return [];
678
- }
679
- const names = new Set(live.map((tool) => tool.name));
680
- const listing = [];
681
- const connects = new Map();
682
- for (const { credential, tools } of deferred) {
683
- for (const definition of tools) {
684
- const name = prefixToolNameWithServerName
685
- ? `${serverName}_${definition.name}`
686
- : definition.name;
687
- if (names.has(name))
688
- continue;
689
- names.add(name);
690
- listing.push(definition);
691
- connects.set(name, { server: serverName, credential });
692
- }
693
- }
694
- if (listing.length === 0)
695
- return [];
696
- const listTools = async () => ({ tools: listing });
697
- // The live listing omits unconnected tools, so loadMcpTools builds them from
698
- // the stored definitions.
699
- const view = new Proxy(connected, {
700
- get(target, property) {
701
- if (property === "listTools")
702
- return listTools;
703
- const value = Reflect.get(target, property, target);
704
- return typeof value === "function" ? value.bind(target) : value;
705
- },
706
- });
351
+ const prefix = (name) => prefixToolNameWithServerName ? `${serverName}_${name}` : name;
707
352
  const { defaultToolTimeout, outputHandling, logLevel } = server;
708
- const tools = await loadMcpTools(serverName, view, {
353
+ return loadMcpTools(serverName, withCards(client, prefix), {
709
354
  prefixToolNameWithServerName,
710
- throwOnLoadError: false,
711
- // Stored tools exist only with jitAuth; see `resolveLangSmithServers`.
355
+ throwOnLoadError: throwOnLoadError ?? true,
712
356
  elicitation: false,
713
357
  ...(defaultToolTimeout !== undefined && { defaultToolTimeout }),
714
358
  ...(outputHandling !== undefined && { outputHandling }),
715
359
  ...(logLevel !== undefined && { logLevel }),
716
360
  });
717
- for (const tool of tools) {
718
- tool.metadata = {
719
- ...tool.metadata,
720
- [CONNECT_ON_USE_METADATA]: connects.get(tool.name),
721
- };
722
- }
723
- return tools;
724
- }
725
- /** Turn a kit's 428 for one call into a {@link ToolCredentialRequiredError}. */
726
- function askingToConnect(serverName, tool) {
727
- const call = tool.func.bind(tool);
728
- tool.func = async (...args) => {
729
- try {
730
- return await call(...args);
731
- }
732
- catch (error) {
733
- throw toolCredentialRequired(serverName, error) ?? error;
734
- }
735
- };
736
- return tool;
737
- }
738
- /**
739
- * Map a kit's 428 anywhere in `error`'s cause chain; credentials stay empty
740
- * without a complete link. The SDK transport reports the status and body as
741
- * an HTTP error's `data`, which the adapter wraps in a `ToolException`.
742
- */
743
- function toolCredentialRequired(serverName, error) {
744
- for (let cause = error; cause instanceof Error; cause = cause.cause) {
745
- // The SDK's `SdkHttpError` carries `data: { status, text }`, but neither
746
- // the adapter nor a direct dependency exports that class to check against.
747
- const data = cause.data;
748
- if (isRecord(data) && data.status === 428) {
749
- return refusalFromLangSmith428(serverName, data.text);
750
- }
751
- }
752
- return undefined;
753
- }
754
- function refusalFromLangSmith428(serverName, text) {
755
- let body;
756
- try {
757
- body = typeof text === "string" ? JSON.parse(text) : undefined;
758
- }
759
- catch {
760
- body = undefined;
761
- }
762
- const listed = isRecord(body) ? body.credentials : undefined;
763
- const { pending, unresolved } = partitionLangSmith428Entries(Array.isArray(listed) ? listed : [body], serverName);
764
- if (unresolved.length > 0 || pending.length === 0) {
765
- logger.warn("could not read the connect link from a LangSmith MCP server " +
766
- `"${logger.logIdentifier(serverName)}" refusal`);
767
- const labels = [...new Set(unresolved)].join(", ");
768
- return new ToolCredentialRequiredError(labels || serverName, []);
769
- }
770
- const provider = [
771
- ...new Set(pending.map((credential) => credential.provider ?? serverName)),
772
- ].join(", ");
773
- return new ToolCredentialRequiredError(provider, pending);
774
361
  }
775
362
  function filterToolsForServer(serverName, selection, tools, prefixToolNameWithServerName) {
776
363
  return selectTools(`MCP server "${serverName}"`, selection, tools, (tool) => {