@inkeep/agents-core 0.22.11 → 0.23.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.
@@ -1,8 +1,9 @@
1
- export { h as ACTIVITY_NAMES, f as ACTIVITY_STATUS, e as ACTIVITY_TYPES, g as AGENT_IDS, o as AGGREGATE_OPERATORS, A as AI_OPERATIONS, i as AI_TOOL_TYPES, n as DATA_SOURCES, j as DATA_TYPES, D as DELEGATION_FROM_SUB_AGENT_ID, b as DELEGATION_ID, a as DELEGATION_TO_SUB_AGENT_ID, F as FIELD_TYPES, O as OPERATORS, l as ORDER_DIRECTIONS, P as PANEL_TYPES, p as QUERY_DEFAULTS, k as QUERY_EXPRESSIONS, Q as QUERY_FIELD_CONFIGS, m as QUERY_TYPES, R as REDUCE_OPERATIONS, d as SPAN_KEYS, S as SPAN_NAMES, T as TRANSFER_FROM_SUB_AGENT_ID, c as TRANSFER_TO_SUB_AGENT_ID, U as UNKNOWN_VALUE } from './signoz-queries-Bqpkx5sK.js';
1
+ export { i as ACTIVITY_NAMES, g as ACTIVITY_STATUS, f as ACTIVITY_TYPES, h as AGENT_IDS, p as AGGREGATE_OPERATORS, A as AI_OPERATIONS, j as AI_TOOL_TYPES, o as DATA_SOURCES, k as DATA_TYPES, D as DELEGATION_FROM_SUB_AGENT_ID, b as DELEGATION_ID, a as DELEGATION_TO_SUB_AGENT_ID, F as FIELD_TYPES, O as OPERATORS, m as ORDER_DIRECTIONS, P as PANEL_TYPES, q as QUERY_DEFAULTS, l as QUERY_EXPRESSIONS, Q as QUERY_FIELD_CONFIGS, n as QUERY_TYPES, R as REDUCE_OPERATIONS, e as SPAN_KEYS, S as SPAN_NAMES, T as TRANSFER_FROM_SUB_AGENT_ID, c as TRANSFER_TO_SUB_AGENT_ID, U as UNKNOWN_VALUE, d as detectAuthenticationRequired } from './auth-detection-BO8bSpe4.js';
2
2
  import { z } from 'zod';
3
- import { C as ConversationHistoryConfig, F as FunctionApiInsertSchema, A as ApiKeyApiUpdateSchema, a as FullAgentAgentInsertSchema } from './utility-06QUJeMa.js';
4
- export { e as AgentStopWhen, b as AgentStopWhenSchema, h as CredentialStoreType, j as FunctionApiSelectSchema, k as FunctionApiUpdateSchema, i as MCPTransportType, g as ModelSettings, M as ModelSettingsSchema, d as StopWhen, S as StopWhenSchema, f as SubAgentStopWhen, c as SubAgentStopWhenSchema } from './utility-06QUJeMa.js';
3
+ import { C as ConversationHistoryConfig, F as FunctionApiInsertSchema, A as ApiKeyApiUpdateSchema, a as FullAgentAgentInsertSchema } from './utility-mGrlR4Ta.js';
4
+ export { e as AgentStopWhen, b as AgentStopWhenSchema, h as CredentialStoreType, j as FunctionApiSelectSchema, k as FunctionApiUpdateSchema, i as MCPTransportType, g as ModelSettings, M as ModelSettingsSchema, d as StopWhen, S as StopWhenSchema, f as SubAgentStopWhen, c as SubAgentStopWhenSchema } from './utility-mGrlR4Ta.js';
5
5
  export { v as validatePropsAsJsonSchema } from './props-validation-BMR1qNiy.js';
6
+ import 'pino';
6
7
  import 'drizzle-zod';
7
8
  import 'drizzle-orm/sqlite-core';
8
9
  import '@hono/zod-openapi';
@@ -128,8 +129,8 @@ declare const DataComponentApiInsertSchema: z.ZodObject<{
128
129
  props: z.ZodRecord<z.ZodString, z.ZodUnknown>;
129
130
  }, z.core.$strip>;
130
131
  declare const ArtifactComponentApiInsertSchema: z.ZodObject<{
131
- name: z.ZodString;
132
132
  id: z.ZodString;
133
+ name: z.ZodString;
133
134
  description: z.ZodString;
134
135
  props: z.ZodOptional<z.ZodNullable<z.ZodType<Record<string, unknown>, Record<string, unknown>, z.core.$ZodTypeInternals<Record<string, unknown>, Record<string, unknown>>>>>;
135
136
  }, {
@@ -164,11 +165,12 @@ declare const FullAgentDefinitionSchema: z.ZodObject<{
164
165
  description: z.ZodOptional<z.ZodString>;
165
166
  defaultSubAgentId: z.ZodOptional<z.ZodString>;
166
167
  subAgents: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodObject<{
167
- name: z.ZodString;
168
168
  id: z.ZodString;
169
+ name: z.ZodString;
170
+ description: z.ZodString;
171
+ prompt: z.ZodString;
169
172
  createdAt: z.ZodOptional<z.ZodString>;
170
173
  updatedAt: z.ZodOptional<z.ZodString>;
171
- description: z.ZodString;
172
174
  models: z.ZodOptional<z.ZodObject<{
173
175
  base: z.ZodOptional<z.ZodObject<{
174
176
  model: z.ZodOptional<z.ZodString>;
@@ -192,7 +194,6 @@ declare const FullAgentDefinitionSchema: z.ZodObject<{
192
194
  }, {
193
195
  stepCountIs?: number | undefined;
194
196
  }>>>>;
195
- prompt: z.ZodString;
196
197
  conversationHistoryConfig: z.ZodOptional<z.ZodNullable<z.ZodType<ConversationHistoryConfig, ConversationHistoryConfig, z.core.$ZodTypeInternals<ConversationHistoryConfig, ConversationHistoryConfig>>>>;
197
198
  type: z.ZodLiteral<"internal">;
198
199
  canUse: z.ZodArray<z.ZodObject<{
@@ -1,6 +1,6 @@
1
- export { ACTIVITY_NAMES, ACTIVITY_STATUS, ACTIVITY_TYPES, AGENT_IDS, AGGREGATE_OPERATORS, AI_OPERATIONS, AI_TOOL_TYPES, DATA_SOURCES, DATA_TYPES, DELEGATION_FROM_SUB_AGENT_ID, DELEGATION_ID, DELEGATION_TO_SUB_AGENT_ID, FIELD_TYPES, OPERATORS, ORDER_DIRECTIONS, PANEL_TYPES, QUERY_DEFAULTS, QUERY_EXPRESSIONS, QUERY_FIELD_CONFIGS, QUERY_TYPES, REDUCE_OPERATIONS, SPAN_KEYS, SPAN_NAMES, TRANSFER_FROM_SUB_AGENT_ID, TRANSFER_TO_SUB_AGENT_ID, UNKNOWN_VALUE } from './chunk-QFIITHNT.js';
2
- import { ModelSettingsSchema, FullAgentAgentInsertSchema, ArtifactComponentApiInsertSchema } from './chunk-4SE2FOJY.js';
3
- export { AgentStopWhenSchema, FunctionApiInsertSchema, FunctionApiSelectSchema, FunctionApiUpdateSchema, ModelSettingsSchema, StopWhenSchema, SubAgentStopWhenSchema, validatePropsAsJsonSchema } from './chunk-4SE2FOJY.js';
1
+ export { ACTIVITY_NAMES, ACTIVITY_STATUS, ACTIVITY_TYPES, AGENT_IDS, AGGREGATE_OPERATORS, AI_OPERATIONS, AI_TOOL_TYPES, DATA_SOURCES, DATA_TYPES, DELEGATION_FROM_SUB_AGENT_ID, DELEGATION_ID, DELEGATION_TO_SUB_AGENT_ID, FIELD_TYPES, OPERATORS, ORDER_DIRECTIONS, PANEL_TYPES, QUERY_DEFAULTS, QUERY_EXPRESSIONS, QUERY_FIELD_CONFIGS, QUERY_TYPES, REDUCE_OPERATIONS, SPAN_KEYS, SPAN_NAMES, TRANSFER_FROM_SUB_AGENT_ID, TRANSFER_TO_SUB_AGENT_ID, UNKNOWN_VALUE, detectAuthenticationRequired } from './chunk-5GAUAB2P.js';
2
+ import { ModelSettingsSchema, FullAgentAgentInsertSchema, ArtifactComponentApiInsertSchema } from './chunk-HN77JIDP.js';
3
+ export { AgentStopWhenSchema, FunctionApiInsertSchema, FunctionApiSelectSchema, FunctionApiUpdateSchema, ModelSettingsSchema, StopWhenSchema, SubAgentStopWhenSchema, validatePropsAsJsonSchema } from './chunk-HN77JIDP.js';
4
4
  import { CredentialStoreType } from './chunk-YFHT5M2R.js';
5
5
  export { CredentialStoreType, MCPTransportType } from './chunk-YFHT5M2R.js';
6
6
  import { z } from 'zod';
@@ -1,7 +1,7 @@
1
1
  import 'drizzle-orm';
2
2
  import 'drizzle-orm/sqlite-core';
3
- import '../utility-06QUJeMa.cjs';
4
- export { E as agentRelations, H as agentToolRelationsRelations, a as agents, w as apiKeys, G as apiKeysRelations, j as artifactComponents, M as artifactComponentsRelations, b as contextCache, C as contextCacheRelations, c as contextConfigs, B as contextConfigsRelations, r as conversations, K as conversationsRelations, x as credentialReferences, I as credentialReferencesRelations, h as dataComponents, O as dataComponentsRelations, f as externalAgents, F as externalAgentsRelations, m as functionTools, T as functionToolsRelations, n as functions, R as functionsRelations, v as ledgerArtifacts, Q as ledgerArtifactsRelations, u as messages, L as messagesRelations, p as projects, z as projectsRelations, k as subAgentArtifactComponents, N as subAgentArtifactComponentsRelations, i as subAgentDataComponents, P as subAgentDataComponentsRelations, q as subAgentFunctionToolRelations, U as subAgentFunctionToolRelationsRelations, e as subAgentRelations, S as subAgentRelationsRelations, o as subAgentToolRelations, d as subAgents, D as subAgentsRelations, g as taskRelations, A as taskRelationsRelations, t as tasks, y as tasksRelations, l as tools, J as toolsRelations } from '../schema-B8-O-pmG.cjs';
3
+ import '../utility-mGrlR4Ta.cjs';
4
+ export { E as agentRelations, H as agentToolRelationsRelations, a as agents, w as apiKeys, G as apiKeysRelations, j as artifactComponents, M as artifactComponentsRelations, b as contextCache, C as contextCacheRelations, c as contextConfigs, B as contextConfigsRelations, r as conversations, K as conversationsRelations, x as credentialReferences, I as credentialReferencesRelations, h as dataComponents, O as dataComponentsRelations, f as externalAgents, F as externalAgentsRelations, m as functionTools, T as functionToolsRelations, n as functions, R as functionsRelations, v as ledgerArtifacts, Q as ledgerArtifactsRelations, u as messages, L as messagesRelations, p as projects, z as projectsRelations, k as subAgentArtifactComponents, N as subAgentArtifactComponentsRelations, i as subAgentDataComponents, P as subAgentDataComponentsRelations, q as subAgentFunctionToolRelations, U as subAgentFunctionToolRelationsRelations, e as subAgentRelations, S as subAgentRelationsRelations, o as subAgentToolRelations, d as subAgents, D as subAgentsRelations, g as taskRelations, A as taskRelationsRelations, t as tasks, y as tasksRelations, l as tools, J as toolsRelations } from '../schema-B8NMPwEM.cjs';
5
5
  import 'zod';
6
6
  import 'drizzle-zod';
7
7
  import '@hono/zod-openapi';
@@ -1,7 +1,7 @@
1
1
  import 'drizzle-orm';
2
2
  import 'drizzle-orm/sqlite-core';
3
- import '../utility-06QUJeMa.js';
4
- export { E as agentRelations, H as agentToolRelationsRelations, a as agents, w as apiKeys, G as apiKeysRelations, j as artifactComponents, M as artifactComponentsRelations, b as contextCache, C as contextCacheRelations, c as contextConfigs, B as contextConfigsRelations, r as conversations, K as conversationsRelations, x as credentialReferences, I as credentialReferencesRelations, h as dataComponents, O as dataComponentsRelations, f as externalAgents, F as externalAgentsRelations, m as functionTools, T as functionToolsRelations, n as functions, R as functionsRelations, v as ledgerArtifacts, Q as ledgerArtifactsRelations, u as messages, L as messagesRelations, p as projects, z as projectsRelations, k as subAgentArtifactComponents, N as subAgentArtifactComponentsRelations, i as subAgentDataComponents, P as subAgentDataComponentsRelations, q as subAgentFunctionToolRelations, U as subAgentFunctionToolRelationsRelations, e as subAgentRelations, S as subAgentRelationsRelations, o as subAgentToolRelations, d as subAgents, D as subAgentsRelations, g as taskRelations, A as taskRelationsRelations, t as tasks, y as tasksRelations, l as tools, J as toolsRelations } from '../schema-BPRMaYtZ.js';
3
+ import '../utility-mGrlR4Ta.js';
4
+ export { E as agentRelations, H as agentToolRelationsRelations, a as agents, w as apiKeys, G as apiKeysRelations, j as artifactComponents, M as artifactComponentsRelations, b as contextCache, C as contextCacheRelations, c as contextConfigs, B as contextConfigsRelations, r as conversations, K as conversationsRelations, x as credentialReferences, I as credentialReferencesRelations, h as dataComponents, O as dataComponentsRelations, f as externalAgents, F as externalAgentsRelations, m as functionTools, T as functionToolsRelations, n as functions, R as functionsRelations, v as ledgerArtifacts, Q as ledgerArtifactsRelations, u as messages, L as messagesRelations, p as projects, z as projectsRelations, k as subAgentArtifactComponents, N as subAgentArtifactComponentsRelations, i as subAgentDataComponents, P as subAgentDataComponentsRelations, q as subAgentFunctionToolRelations, U as subAgentFunctionToolRelationsRelations, e as subAgentRelations, S as subAgentRelationsRelations, o as subAgentToolRelations, d as subAgents, D as subAgentsRelations, g as taskRelations, A as taskRelationsRelations, t as tasks, y as tasksRelations, l as tools, J as toolsRelations } from '../schema-PgBNwsV-.js';
5
5
  import 'zod';
6
6
  import 'drizzle-zod';
7
7
  import '@hono/zod-openapi';
package/dist/index.cjs CHANGED
@@ -13,6 +13,7 @@ var client = require('@libsql/client');
13
13
  var libsql = require('drizzle-orm/libsql');
14
14
  var crypto = require('crypto');
15
15
  var util = require('util');
16
+ var auth_js = require('@modelcontextprotocol/sdk/client/auth.js');
16
17
  var httpException = require('hono/http-exception');
17
18
  var index_js = require('@modelcontextprotocol/sdk/client/index.js');
18
19
  var sse_js = require('@modelcontextprotocol/sdk/client/sse.js');
@@ -214719,7 +214720,8 @@ var McpToolSchema = ToolInsertSchema.extend({
214719
214720
  status: ToolStatusSchema.default("unknown"),
214720
214721
  version: zodOpenapi.z.string().optional(),
214721
214722
  createdAt: zodOpenapi.z.date(),
214722
- updatedAt: zodOpenapi.z.date()
214723
+ updatedAt: zodOpenapi.z.date(),
214724
+ expiresAt: zodOpenapi.z.date().optional()
214723
214725
  });
214724
214726
  var MCPToolConfigSchema = McpToolSchema.omit({
214725
214727
  config: true,
@@ -217182,71 +217184,146 @@ function extractPublicId(key) {
217182
217184
  function maskApiKey(keyPrefix) {
217183
217185
  return `${keyPrefix}...`;
217184
217186
  }
217185
-
217186
- // src/utils/auth-detection.ts
217187
- var getWellKnownUrls = (baseUrl) => [
217188
- `${baseUrl}/.well-known/oauth-authorization-server`,
217189
- `${baseUrl}/.well-known/openid-configuration`
217190
- ];
217191
- var validateOAuthMetadata = (metadata) => {
217192
- return metadata.code_challenge_methods_supported?.includes("S256");
217193
- };
217194
- var buildOAuthConfig = (metadata) => ({
217195
- authorizationUrl: metadata.authorization_endpoint,
217196
- tokenUrl: metadata.token_endpoint,
217197
- registrationUrl: metadata.registration_endpoint,
217198
- supportsDynamicRegistration: !!metadata.registration_endpoint
217199
- });
217200
- var tryWellKnownEndpoints = async (baseUrl, logger14) => {
217201
- const wellKnownUrls = getWellKnownUrls(baseUrl);
217202
- for (const wellKnownUrl of wellKnownUrls) {
217187
+ function discoverScopes(resourceMetadata, metadata) {
217188
+ const resourceScopes = resourceMetadata?.scopes_supported;
217189
+ const oauthScopes = metadata?.scopes_supported;
217190
+ const scopes = (resourceScopes?.length ? resourceScopes : oauthScopes) || [];
217191
+ return scopes.length > 0 ? scopes.join(" ") : void 0;
217192
+ }
217193
+ async function discoverMcpMetadata(mcpServerUrl, logger14) {
217194
+ try {
217195
+ let resourceMetadata = null;
217196
+ let authServerUrl = new URL(mcpServerUrl);
217203
217197
  try {
217204
- const response = await fetch(wellKnownUrl);
217205
- if (response.ok) {
217206
- const metadata = await response.json();
217207
- if (validateOAuthMetadata(metadata)) {
217208
- logger14?.debug({ baseUrl, wellKnownUrl }, "OAuth 2.1/PKCE support detected");
217209
- return buildOAuthConfig(metadata);
217210
- }
217198
+ resourceMetadata = await auth_js.discoverOAuthProtectedResourceMetadata(mcpServerUrl);
217199
+ if (resourceMetadata?.authorization_servers?.length && resourceMetadata.authorization_servers[0]) {
217200
+ authServerUrl = new URL(resourceMetadata.authorization_servers[0]);
217211
217201
  }
217212
- } catch (error) {
217213
- logger14?.debug({ wellKnownUrl, error }, "OAuth endpoint check failed");
217202
+ } catch {
217203
+ }
217204
+ const metadata = await auth_js.discoverAuthorizationServerMetadata(authServerUrl);
217205
+ if (!metadata) {
217206
+ throw new Error("Failed to discover OAuth authorization server metadata");
217214
217207
  }
217208
+ logger14?.debug(
217209
+ {
217210
+ tokenEndpoint: metadata.token_endpoint,
217211
+ authEndpoint: metadata.authorization_endpoint
217212
+ },
217213
+ "MCP metadata discovery successful"
217214
+ );
217215
+ const discoveredScopes = discoverScopes(resourceMetadata ?? void 0, metadata);
217216
+ return {
217217
+ success: true,
217218
+ metadata,
217219
+ ...resourceMetadata && { resourceMetadata },
217220
+ ...discoveredScopes && { scopes: discoveredScopes }
217221
+ };
217222
+ } catch (err) {
217223
+ const errorMessage = err instanceof Error ? err.message : String(err);
217224
+ logger14?.debug({ error: errorMessage }, "MCP metadata discovery failed");
217225
+ return { success: false, error: errorMessage };
217215
217226
  }
217216
- return null;
217217
- };
217218
- var checkForOAuthEndpoints = async (serverUrl, logger14) => {
217219
- const config = await discoverOAuthEndpoints(serverUrl, logger14);
217220
- return config !== null;
217221
- };
217222
- var discoverOAuthEndpoints = async (serverUrl, logger14) => {
217223
- try {
217224
- const response = await fetch(serverUrl, {
217225
- method: "POST",
217226
- headers: { "Content-Type": "application/json" },
217227
- body: JSON.stringify({})
217227
+ }
217228
+ async function initiateMcpOAuthFlow({
217229
+ mcpServerUrl,
217230
+ redirectUri,
217231
+ state,
217232
+ clientName = "Inkeep Agent Framework",
217233
+ clientUri = "https://inkeep.com",
217234
+ logoUri,
217235
+ defaultClientId = "mcp-client",
217236
+ logger: logger14
217237
+ }) {
217238
+ const discoveryResult = await discoverMcpMetadata(mcpServerUrl, logger14);
217239
+ if (!discoveryResult.success || !discoveryResult.metadata) {
217240
+ throw new Error(`OAuth not supported by this server: ${discoveryResult.error}`);
217241
+ }
217242
+ const { metadata, resourceMetadata, scopes: discoveredScopes } = discoveryResult;
217243
+ const clientMetadata = {
217244
+ redirect_uris: [redirectUri],
217245
+ token_endpoint_auth_method: "none",
217246
+ // PKCE - no client secret
217247
+ grant_types: ["authorization_code", "refresh_token"],
217248
+ response_types: ["code"],
217249
+ client_name: clientName,
217250
+ client_uri: clientUri,
217251
+ ...logoUri && { logo_uri: logoUri }
217252
+ };
217253
+ let clientInformation;
217254
+ if (metadata.registration_endpoint) {
217255
+ clientInformation = await auth_js.registerClient(mcpServerUrl, {
217256
+ metadata,
217257
+ clientMetadata
217228
217258
  });
217229
- if (response.status === 401) {
217230
- const wwwAuth = response.headers.get("WWW-Authenticate");
217231
- if (wwwAuth) {
217232
- const metadataMatch = wwwAuth.match(/as_uri="([^"]+)"/);
217233
- if (metadataMatch) {
217234
- const metadataResponse = await fetch(metadataMatch[1]);
217235
- if (metadataResponse.ok) {
217236
- const metadata = await metadataResponse.json();
217237
- if (metadata.authorization_servers?.length > 0) {
217238
- return await tryWellKnownEndpoints(metadata.authorization_servers[0], logger14);
217239
- }
217240
- }
217241
- }
217242
- }
217243
- }
217244
- } catch (_error) {
217259
+ } else {
217260
+ clientInformation = {
217261
+ client_id: defaultClientId,
217262
+ ...clientMetadata
217263
+ };
217245
217264
  }
217246
- const url = new URL(serverUrl);
217247
- const baseUrl = `${url.protocol}//${url.host}`;
217248
- return await tryWellKnownEndpoints(baseUrl, logger14);
217249
- };
217265
+ const resource = resourceMetadata?.resource ? new URL(resourceMetadata.resource) : void 0;
217266
+ const authResult = await auth_js.startAuthorization(mcpServerUrl, {
217267
+ metadata,
217268
+ clientInformation,
217269
+ redirectUrl: redirectUri,
217270
+ state,
217271
+ scope: discoveredScopes || "",
217272
+ ...resource && { resource }
217273
+ });
217274
+ logger14?.debug(
217275
+ {
217276
+ authorizationUrl: authResult.authorizationUrl.href,
217277
+ scopes: discoveredScopes,
217278
+ clientId: clientInformation.client_id
217279
+ },
217280
+ "MCP OAuth flow initiated successfully"
217281
+ );
217282
+ return {
217283
+ authorizationUrl: authResult.authorizationUrl.href,
217284
+ codeVerifier: authResult.codeVerifier,
217285
+ state,
217286
+ clientInformation,
217287
+ metadata,
217288
+ resourceUrl: resource?.href || void 0,
217289
+ ...discoveredScopes && { scopes: discoveredScopes }
217290
+ };
217291
+ }
217292
+ async function exchangeMcpAuthorizationCode({
217293
+ mcpServerUrl,
217294
+ metadata,
217295
+ clientInformation,
217296
+ authorizationCode,
217297
+ codeVerifier,
217298
+ redirectUri,
217299
+ resourceUrl,
217300
+ logger: logger14
217301
+ }) {
217302
+ const resource = resourceUrl ? new URL(resourceUrl) : void 0;
217303
+ const tokens = await auth_js.exchangeAuthorization(mcpServerUrl, {
217304
+ metadata,
217305
+ clientInformation,
217306
+ authorizationCode,
217307
+ codeVerifier,
217308
+ redirectUri,
217309
+ ...resource && { resource }
217310
+ });
217311
+ logger14?.debug(
217312
+ {
217313
+ tokenType: tokens.token_type,
217314
+ hasRefreshToken: !!tokens.refresh_token,
217315
+ expiresIn: tokens.expires_in
217316
+ },
217317
+ "MCP token exchange successful"
217318
+ );
217319
+ return {
217320
+ access_token: tokens.access_token,
217321
+ refresh_token: tokens.refresh_token,
217322
+ expires_at: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1e3) : void 0,
217323
+ token_type: tokens.token_type || "Bearer",
217324
+ scope: tokens.scope
217325
+ };
217326
+ }
217250
217327
  var detectAuthenticationRequired = async ({
217251
217328
  serverUrl,
217252
217329
  toolId,
@@ -217254,53 +217331,17 @@ var detectAuthenticationRequired = async ({
217254
217331
  logger: logger14
217255
217332
  }) => {
217256
217333
  try {
217257
- const hasOAuthEndpoints = await checkForOAuthEndpoints(serverUrl, logger14);
217258
- if (hasOAuthEndpoints) {
217259
- logger14?.info(
217260
- { toolId, serverUrl },
217261
- "OAuth 2.1/PKCE support confirmed via endpoint discovery"
217262
- );
217334
+ const discoveryResult = await discoverMcpMetadata(serverUrl, logger14);
217335
+ if (discoveryResult.success && discoveryResult.metadata) {
217336
+ logger14?.info({ toolId, serverUrl }, "MCP OAuth support confirmed via metadata discovery");
217263
217337
  return true;
217264
217338
  }
217265
217339
  } catch (discoveryError) {
217266
- logger14?.debug({ toolId, discoveryError }, "OAuth endpoint discovery failed");
217267
- }
217268
- try {
217269
- const response = await fetch(serverUrl, {
217270
- method: "POST",
217271
- headers: { "Content-Type": "application/json" },
217272
- body: JSON.stringify({
217273
- jsonrpc: "2.0",
217274
- method: "initialize",
217275
- id: 1,
217276
- params: { protocolVersion: "2024-11-05", capabilities: {} }
217277
- })
217278
- });
217279
- if (response.status === 401) {
217280
- const wwwAuth = response.headers.get("WWW-Authenticate");
217281
- if (wwwAuth) {
217282
- const authLower = wwwAuth.toLowerCase();
217283
- const hasActiveOAuthFlow = authLower.includes("authorization_uri") || authLower.includes("as_uri=") || authLower.includes("bearer") && (authLower.includes("scope=") || authLower.includes("error_uri="));
217284
- if (hasActiveOAuthFlow) {
217285
- logger14?.info(
217286
- { toolId, wwwAuth },
217287
- "Active OAuth flow detected via WWW-Authenticate parameters"
217288
- );
217289
- return true;
217290
- } else {
217291
- logger14?.debug(
217292
- { toolId, wwwAuth },
217293
- "Bearer authentication detected - likely simple token auth, not OAuth"
217294
- );
217295
- }
217296
- }
217297
- }
217298
- } catch (fetchError) {
217299
- logger14?.debug({ toolId, fetchError }, "Direct fetch authentication check failed");
217340
+ logger14?.debug({ toolId, discoveryError }, "MCP OAuth metadata discovery failed");
217300
217341
  }
217301
217342
  logger14?.debug(
217302
- { toolId, error: error.message },
217303
- "No OAuth 2.1/PKCE authentication requirement detected"
217343
+ { toolId, error: error?.message },
217344
+ "No MCP OAuth authentication requirement detected"
217304
217345
  );
217305
217346
  return false;
217306
217347
  };
@@ -218007,7 +218048,7 @@ var discoverToolsFromServer = async (tool2, dbClient, credentialStoreRegistry) =
218007
218048
  id: credentialReferenceId
218008
218049
  });
218009
218050
  if (!credentialReference) {
218010
- throw new Error(`Credential store not found: ${credentialReferenceId}`);
218051
+ throw new Error(`Credential reference not found: ${credentialReferenceId}`);
218011
218052
  }
218012
218053
  const storeReference = {
218013
218054
  credentialStoreId: credentialReference.credentialStoreId,
@@ -218086,6 +218127,38 @@ var dbResultToMcpTool = async (dbResult, dbClient, credentialStoreRegistry) => {
218086
218127
  let availableTools = [];
218087
218128
  let status = "unknown";
218088
218129
  let lastErrorComputed;
218130
+ let expiresAt;
218131
+ if (credentialReferenceId) {
218132
+ const credentialReference = await getCredentialReference(dbClient)({
218133
+ scopes: { tenantId: dbResult.tenantId, projectId: dbResult.projectId },
218134
+ id: credentialReferenceId
218135
+ });
218136
+ if (credentialReference?.retrievalParams) {
218137
+ const credentialStore = credentialStoreRegistry?.get(credentialReference.credentialStoreId);
218138
+ if (credentialStore && credentialStore.type !== CredentialStoreType.memory) {
218139
+ const lookupKey = getCredentialStoreLookupKeyFromRetrievalParams({
218140
+ retrievalParams: credentialReference.retrievalParams,
218141
+ credentialStoreType: credentialStore.type
218142
+ });
218143
+ if (lookupKey) {
218144
+ const credentialDataString = await credentialStore.get(lookupKey);
218145
+ if (credentialDataString) {
218146
+ if (credentialStore.type === CredentialStoreType.nango) {
218147
+ const nangoCredentialData = JSON.parse(credentialDataString);
218148
+ if (nangoCredentialData.expiresAt) {
218149
+ expiresAt = nangoCredentialData.expiresAt;
218150
+ }
218151
+ } else if (credentialStore.type === CredentialStoreType.keychain) {
218152
+ const oauthTokens = JSON.parse(credentialDataString);
218153
+ if (oauthTokens.expires_at) {
218154
+ expiresAt = new Date(oauthTokens.expires_at);
218155
+ }
218156
+ }
218157
+ }
218158
+ }
218159
+ }
218160
+ }
218161
+ }
218089
218162
  try {
218090
218163
  availableTools = await discoverToolsFromServer(dbResult, dbClient, credentialStoreRegistry);
218091
218164
  status = "healthy";
@@ -218117,6 +218190,7 @@ var dbResultToMcpTool = async (dbResult, dbClient, credentialStoreRegistry) => {
218117
218190
  credentialReferenceId: credentialReferenceId || void 0,
218118
218191
  createdAt: new Date(createdAt),
218119
218192
  updatedAt: new Date(now),
218193
+ expiresAt,
218120
218194
  lastError: lastErrorComputed,
218121
218195
  headers: headers2 || void 0,
218122
218196
  imageUrl: imageUrl || void 0
@@ -224698,7 +224772,8 @@ var NangoCredentialStore = class {
224698
224772
  case "OAUTH2":
224699
224773
  return {
224700
224774
  token: extractAccessTokenForBearerType(credentials.access_token),
224701
- refresh_token: credentials.refresh_token
224775
+ refresh_token: credentials.refresh_token,
224776
+ expiresAt: credentials.expires_at
224702
224777
  };
224703
224778
  case "OAUTH2_CC":
224704
224779
  return {
@@ -225576,9 +225651,9 @@ exports.deleteSubAgentRelation = deleteSubAgentRelation;
225576
225651
  exports.deleteTool = deleteTool;
225577
225652
  exports.detectAuthenticationRequired = detectAuthenticationRequired;
225578
225653
  exports.determineContextTrigger = determineContextTrigger;
225579
- exports.discoverOAuthEndpoints = discoverOAuthEndpoints;
225580
225654
  exports.errorResponseSchema = errorResponseSchema;
225581
225655
  exports.errorSchemaFactory = errorSchemaFactory;
225656
+ exports.exchangeMcpAuthorizationCode = exchangeMcpAuthorizationCode;
225582
225657
  exports.externalAgentExists = externalAgentExists;
225583
225658
  exports.externalAgentUrlExists = externalAgentUrlExists;
225584
225659
  exports.externalAgents = externalAgents;
@@ -225663,6 +225738,7 @@ exports.hasContextConfig = hasContextConfig;
225663
225738
  exports.hasCredentialReference = hasCredentialReference;
225664
225739
  exports.hashApiKey = hashApiKey;
225665
225740
  exports.headers = headers;
225741
+ exports.initiateMcpOAuthFlow = initiateMcpOAuthFlow;
225666
225742
  exports.invalidateHeadersCache = invalidateHeadersCache;
225667
225743
  exports.invalidateInvocationDefinitionsCache = invalidateInvocationDefinitionsCache;
225668
225744
  exports.isApiKeyExpired = isApiKeyExpired;