@inkeep/agents-core 0.35.1 → 0.35.3

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 (43) hide show
  1. package/dist/auth/auth-schema.d.ts +1097 -0
  2. package/dist/auth/auth-schema.js +1 -0
  3. package/dist/auth/auth-validation-schemas.d.ts +1881 -0
  4. package/dist/auth/auth-validation-schemas.js +39 -0
  5. package/dist/auth/auth.d.ts +118 -0
  6. package/dist/auth/auth.js +95 -0
  7. package/dist/auth/permissions.d.ts +273 -0
  8. package/dist/auth/permissions.js +1 -0
  9. package/dist/chunk-4JZT4QEE.js +162 -0
  10. package/dist/chunk-F5WWOOIX.js +62 -0
  11. package/dist/{chunk-YZ5ZBVHJ.js → chunk-NFYCSHD3.js} +3 -81
  12. package/dist/chunk-NOPEANIU.js +82 -0
  13. package/dist/{chunk-J5AHY6M2.js → chunk-SPRTYWRV.js} +1 -1
  14. package/dist/{chunk-OP3KPT4T.js → chunk-TGESM3JG.js} +1 -160
  15. package/dist/{chunk-DYGTCLJO.js → chunk-VBCCPAZK.js} +1 -1
  16. package/dist/chunk-ZYSTJ4XY.js +948 -0
  17. package/dist/client-CPYOMZF2.d.ts +19 -0
  18. package/dist/client-exports.js +4 -3
  19. package/dist/db/schema.d.ts +2 -1
  20. package/dist/db/schema.js +2 -1
  21. package/dist/index.d.ts +9 -154
  22. package/dist/index.js +1565 -2498
  23. package/dist/{schema-BWd551GM.d.ts → schema-5N2lPWNV.d.ts} +2 -1095
  24. package/dist/validation/index.js +2 -2
  25. package/package.json +17 -1
  26. package/dist/auth-detection-CGqhPDnj.d.cts +0 -435
  27. package/dist/client-exports.cjs +0 -2833
  28. package/dist/client-exports.d.cts +0 -289
  29. package/dist/constants/models.cjs +0 -40
  30. package/dist/constants/models.d.cts +0 -42
  31. package/dist/db/schema.cjs +0 -1090
  32. package/dist/db/schema.d.cts +0 -7
  33. package/dist/index.cjs +0 -227898
  34. package/dist/index.d.cts +0 -4893
  35. package/dist/props-validation-BMR1qNiy.d.cts +0 -15
  36. package/dist/schema-D4WR42em.d.cts +0 -6352
  37. package/dist/types/index.cjs +0 -39
  38. package/dist/types/index.d.cts +0 -132
  39. package/dist/utility-DbltUp2Q.d.cts +0 -17079
  40. package/dist/utils/schema-conversion.cjs +0 -232
  41. package/dist/utils/schema-conversion.d.cts +0 -26
  42. package/dist/validation/index.cjs +0 -2930
  43. package/dist/validation/index.d.cts +0 -279
@@ -0,0 +1,162 @@
1
+ import { registerClient, startAuthorization, exchangeAuthorization, discoverOAuthProtectedResourceMetadata, discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
2
+
3
+ // src/utils/auth-detection.ts
4
+ function discoverScopes(resourceMetadata, metadata) {
5
+ const resourceScopes = resourceMetadata?.scopes_supported;
6
+ const oauthScopes = metadata?.scopes_supported;
7
+ const scopes = (resourceScopes?.length ? resourceScopes : oauthScopes) || [];
8
+ return scopes.length > 0 ? scopes.join(" ") : void 0;
9
+ }
10
+ async function discoverMcpMetadata(mcpServerUrl, logger) {
11
+ try {
12
+ let resourceMetadata = null;
13
+ let authServerUrl = new URL(mcpServerUrl);
14
+ try {
15
+ resourceMetadata = await discoverOAuthProtectedResourceMetadata(mcpServerUrl);
16
+ if (resourceMetadata?.authorization_servers?.length && resourceMetadata.authorization_servers[0]) {
17
+ authServerUrl = new URL(resourceMetadata.authorization_servers[0]);
18
+ }
19
+ } catch {
20
+ }
21
+ const metadata = await discoverAuthorizationServerMetadata(authServerUrl.href);
22
+ if (!metadata) {
23
+ throw new Error("Failed to discover OAuth authorization server metadata");
24
+ }
25
+ logger?.debug(
26
+ {
27
+ tokenEndpoint: metadata.token_endpoint,
28
+ authEndpoint: metadata.authorization_endpoint
29
+ },
30
+ "MCP metadata discovery successful"
31
+ );
32
+ const discoveredScopes = discoverScopes(resourceMetadata ?? void 0, metadata);
33
+ return {
34
+ success: true,
35
+ metadata,
36
+ ...resourceMetadata && { resourceMetadata },
37
+ ...discoveredScopes && { scopes: discoveredScopes }
38
+ };
39
+ } catch (err) {
40
+ const errorMessage = err instanceof Error ? err.message : String(err);
41
+ logger?.debug({ error: errorMessage }, "MCP metadata discovery failed");
42
+ return { success: false, error: errorMessage };
43
+ }
44
+ }
45
+ async function initiateMcpOAuthFlow({
46
+ mcpServerUrl,
47
+ redirectUri,
48
+ state,
49
+ clientName = "Inkeep Agent Framework",
50
+ clientUri = "https://inkeep.com",
51
+ logoUri,
52
+ defaultClientId = "mcp-client",
53
+ logger
54
+ }) {
55
+ const discoveryResult = await discoverMcpMetadata(mcpServerUrl, logger);
56
+ if (!discoveryResult.success || !discoveryResult.metadata) {
57
+ throw new Error(`OAuth not supported by this server: ${discoveryResult.error}`);
58
+ }
59
+ const { metadata, resourceMetadata, scopes: discoveredScopes } = discoveryResult;
60
+ const clientMetadata = {
61
+ redirect_uris: [redirectUri],
62
+ token_endpoint_auth_method: "none",
63
+ // PKCE - no client secret
64
+ grant_types: ["authorization_code", "refresh_token"],
65
+ response_types: ["code"],
66
+ client_name: clientName,
67
+ client_uri: clientUri,
68
+ ...logoUri && { logo_uri: logoUri }
69
+ };
70
+ let clientInformation;
71
+ if (metadata.registration_endpoint) {
72
+ clientInformation = await registerClient(mcpServerUrl, {
73
+ metadata,
74
+ clientMetadata
75
+ });
76
+ } else {
77
+ clientInformation = {
78
+ client_id: defaultClientId,
79
+ ...clientMetadata
80
+ };
81
+ }
82
+ const resource = resourceMetadata?.resource ? new globalThis.URL(resourceMetadata.resource) : void 0;
83
+ const authResult = await startAuthorization(mcpServerUrl, {
84
+ metadata,
85
+ clientInformation,
86
+ redirectUrl: redirectUri,
87
+ state,
88
+ scope: discoveredScopes || "",
89
+ ...resource && { resource }
90
+ });
91
+ logger?.debug(
92
+ {
93
+ authorizationUrl: authResult.authorizationUrl.href,
94
+ scopes: discoveredScopes,
95
+ clientId: clientInformation.client_id
96
+ },
97
+ "MCP OAuth flow initiated successfully"
98
+ );
99
+ return {
100
+ authorizationUrl: authResult.authorizationUrl.href,
101
+ codeVerifier: authResult.codeVerifier,
102
+ state,
103
+ clientInformation,
104
+ metadata,
105
+ resourceUrl: resource?.href || void 0,
106
+ ...discoveredScopes && { scopes: discoveredScopes }
107
+ };
108
+ }
109
+ async function exchangeMcpAuthorizationCode({
110
+ mcpServerUrl,
111
+ metadata,
112
+ clientInformation,
113
+ authorizationCode,
114
+ codeVerifier,
115
+ redirectUri,
116
+ resourceUrl,
117
+ logger
118
+ }) {
119
+ const resource = resourceUrl ? new globalThis.URL(resourceUrl) : void 0;
120
+ const tokens = await exchangeAuthorization(mcpServerUrl, {
121
+ metadata,
122
+ clientInformation,
123
+ authorizationCode,
124
+ codeVerifier,
125
+ redirectUri,
126
+ ...resource && { resource }
127
+ });
128
+ logger?.debug(
129
+ {
130
+ tokenType: tokens.token_type,
131
+ hasRefreshToken: !!tokens.refresh_token,
132
+ expiresIn: tokens.expires_in
133
+ },
134
+ "MCP token exchange successful"
135
+ );
136
+ return {
137
+ access_token: tokens.access_token,
138
+ refresh_token: tokens.refresh_token,
139
+ expires_at: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1e3) : void 0,
140
+ token_type: tokens.token_type || "Bearer",
141
+ scope: tokens.scope
142
+ };
143
+ }
144
+ var detectAuthenticationRequired = async ({
145
+ serverUrl,
146
+ error,
147
+ logger
148
+ }) => {
149
+ try {
150
+ const discoveryResult = await discoverMcpMetadata(serverUrl, logger);
151
+ if (discoveryResult.success && discoveryResult.metadata) {
152
+ logger?.info({ serverUrl }, "MCP OAuth support confirmed via metadata discovery");
153
+ return true;
154
+ }
155
+ } catch (discoveryError) {
156
+ logger?.debug({ discoveryError }, "MCP OAuth metadata discovery failed");
157
+ }
158
+ logger?.debug({ error: error?.message }, "No MCP OAuth authentication requirement detected");
159
+ return false;
160
+ };
161
+
162
+ export { detectAuthenticationRequired, exchangeMcpAuthorizationCode, initiateMcpOAuthFlow };
@@ -0,0 +1,62 @@
1
+ import { createAccessControl } from 'better-auth/plugins/access';
2
+ import { defaultStatements, adminAc } from 'better-auth/plugins/organization/access';
3
+
4
+ // src/auth/permissions.ts
5
+ var statement = {
6
+ ...defaultStatements,
7
+ project: ["create", "read", "update", "delete"],
8
+ agent: ["create", "read", "update", "delete"],
9
+ sub_agent: ["create", "read", "update", "delete"],
10
+ tool: ["create", "read", "update", "delete"],
11
+ api_key: ["create", "read", "update", "delete"],
12
+ credential: ["create", "read", "update", "delete"],
13
+ data_component: ["create", "read", "update", "delete"],
14
+ artifact_component: ["create", "read", "update", "delete"],
15
+ external_agent: ["create", "read", "update", "delete"],
16
+ function: ["create", "read", "update", "delete"],
17
+ context_config: ["create", "read", "update", "delete"]
18
+ };
19
+ var ac = createAccessControl(statement);
20
+ var memberRole = ac.newRole({
21
+ project: ["read"],
22
+ agent: ["read"],
23
+ sub_agent: ["read"],
24
+ tool: ["read"],
25
+ api_key: ["read"],
26
+ credential: ["read"],
27
+ data_component: ["read"],
28
+ artifact_component: ["read"],
29
+ external_agent: ["read"],
30
+ function: ["read"],
31
+ context_config: ["read"]
32
+ });
33
+ var adminRole = ac.newRole({
34
+ project: ["create", "read", "update"],
35
+ agent: ["create", "read", "update"],
36
+ sub_agent: ["create", "read", "update"],
37
+ tool: ["create", "read", "update"],
38
+ api_key: ["create", "read", "update"],
39
+ credential: ["create", "read", "update"],
40
+ data_component: ["create", "read", "update"],
41
+ artifact_component: ["create", "read", "update"],
42
+ external_agent: ["create", "read", "update"],
43
+ function: ["create", "read", "update"],
44
+ context_config: ["create", "read", "update"],
45
+ ...adminAc.statements
46
+ });
47
+ var ownerRole = ac.newRole({
48
+ project: ["create", "read", "update", "delete"],
49
+ agent: ["create", "read", "update", "delete"],
50
+ sub_agent: ["create", "read", "update", "delete"],
51
+ tool: ["create", "read", "update", "delete"],
52
+ api_key: ["create", "read", "update", "delete"],
53
+ credential: ["create", "read", "update", "delete"],
54
+ data_component: ["create", "read", "update", "delete"],
55
+ artifact_component: ["create", "read", "update", "delete"],
56
+ external_agent: ["create", "read", "update", "delete"],
57
+ function: ["create", "read", "update", "delete"],
58
+ context_config: ["create", "read", "update", "delete"],
59
+ ...adminAc.statements
60
+ });
61
+
62
+ export { ac, adminRole, memberRole, ownerRole };
@@ -1,6 +1,7 @@
1
+ import { verification, user, ssoProvider, session, organization, member, invitation, account } from './chunk-NOPEANIU.js';
1
2
  import { __export } from './chunk-SIAA4J6H.js';
2
3
  import { relations } from 'drizzle-orm';
3
- import { pgTable, timestamp, text, boolean, varchar, jsonb, primaryKey, foreignKey, integer, index, unique } from 'drizzle-orm/pg-core';
4
+ import { pgTable, varchar, text, timestamp, jsonb, primaryKey, foreignKey, integer, index, unique } from 'drizzle-orm/pg-core';
4
5
 
5
6
  // src/db/schema.ts
6
7
  var schema_exports = {};
@@ -64,85 +65,6 @@ __export(schema_exports, {
64
65
  user: () => user,
65
66
  verification: () => verification
66
67
  });
67
- var user = pgTable("user", {
68
- id: text("id").primaryKey(),
69
- name: text("name").notNull(),
70
- email: text("email").notNull().unique(),
71
- emailVerified: boolean("email_verified").default(false).notNull(),
72
- image: text("image"),
73
- createdAt: timestamp("created_at").defaultNow().notNull(),
74
- updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
75
- });
76
- var session = pgTable("session", {
77
- id: text("id").primaryKey(),
78
- expiresAt: timestamp("expires_at").notNull(),
79
- token: text("token").notNull().unique(),
80
- createdAt: timestamp("created_at").defaultNow().notNull(),
81
- updatedAt: timestamp("updated_at").$onUpdate(() => /* @__PURE__ */ new Date()).notNull(),
82
- ipAddress: text("ip_address"),
83
- userAgent: text("user_agent"),
84
- userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
85
- activeOrganizationId: text("active_organization_id")
86
- });
87
- var account = pgTable("account", {
88
- id: text("id").primaryKey(),
89
- accountId: text("account_id").notNull(),
90
- providerId: text("provider_id").notNull(),
91
- userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
92
- accessToken: text("access_token"),
93
- refreshToken: text("refresh_token"),
94
- idToken: text("id_token"),
95
- accessTokenExpiresAt: timestamp("access_token_expires_at"),
96
- refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
97
- scope: text("scope"),
98
- password: text("password"),
99
- createdAt: timestamp("created_at").defaultNow().notNull(),
100
- updatedAt: timestamp("updated_at").$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
101
- });
102
- var verification = pgTable("verification", {
103
- id: text("id").primaryKey(),
104
- identifier: text("identifier").notNull(),
105
- value: text("value").notNull(),
106
- expiresAt: timestamp("expires_at").notNull(),
107
- createdAt: timestamp("created_at").defaultNow().notNull(),
108
- updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
109
- });
110
- var ssoProvider = pgTable("sso_provider", {
111
- id: text("id").primaryKey(),
112
- issuer: text("issuer").notNull(),
113
- oidcConfig: text("oidc_config"),
114
- samlConfig: text("saml_config"),
115
- userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
116
- providerId: text("provider_id").notNull().unique(),
117
- organizationId: text("organization_id"),
118
- domain: text("domain").notNull()
119
- });
120
- var organization = pgTable("organization", {
121
- id: text("id").primaryKey(),
122
- name: text("name").notNull(),
123
- slug: text("slug").notNull().unique(),
124
- logo: text("logo"),
125
- createdAt: timestamp("created_at").notNull(),
126
- metadata: text("metadata")
127
- });
128
- var member = pgTable("member", {
129
- id: text("id").primaryKey(),
130
- organizationId: text("organization_id").notNull().references(() => organization.id, { onDelete: "cascade" }),
131
- userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
132
- role: text("role").default("member").notNull(),
133
- createdAt: timestamp("created_at").notNull()
134
- });
135
- var invitation = pgTable("invitation", {
136
- id: text("id").primaryKey(),
137
- organizationId: text("organization_id").notNull().references(() => organization.id, { onDelete: "cascade" }),
138
- email: text("email").notNull(),
139
- role: text("role"),
140
- status: text("status").default("pending").notNull(),
141
- expiresAt: timestamp("expires_at").notNull(),
142
- inviterId: text("inviter_id").notNull().references(() => user.id, { onDelete: "cascade" })
143
- });
144
-
145
- // src/db/schema.ts
146
68
  var tenantScoped = {
147
69
  tenantId: varchar("tenant_id", { length: 256 }).notNull(),
148
70
  id: varchar("id", { length: 256 }).notNull()
@@ -1090,4 +1012,4 @@ var subAgentTeamAgentRelationsRelations = relations(
1090
1012
  })
1091
1013
  );
1092
1014
 
1093
- export { account, agentRelations, agentToolRelationsRelations, agents, apiKeys, apiKeysRelations, artifactComponents, artifactComponentsRelations, contextCache, contextCacheRelations, contextConfigs, contextConfigsRelations, conversations, conversationsRelations, credentialReferences, credentialReferencesRelations, dataComponents, dataComponentsRelations, externalAgents, externalAgentsRelations, functionTools, functionToolsRelations, functions, functionsRelations, invitation, ledgerArtifacts, ledgerArtifactsRelations, member, messages, messagesRelations, organization, projects, projectsRelations, schema_exports, session, ssoProvider, subAgentArtifactComponents, subAgentArtifactComponentsRelations, subAgentDataComponents, subAgentDataComponentsRelations, subAgentExternalAgentRelations, subAgentExternalAgentRelationsRelations, subAgentFunctionToolRelations, subAgentFunctionToolRelationsRelations, subAgentRelations, subAgentRelationsRelations, subAgentTeamAgentRelations, subAgentTeamAgentRelationsRelations, subAgentToolRelations, subAgents, subAgentsRelations, taskRelations, taskRelationsRelations, tasks, tasksRelations, tools, toolsRelations, user, verification };
1015
+ export { agentRelations, agentToolRelationsRelations, agents, apiKeys, apiKeysRelations, artifactComponents, artifactComponentsRelations, contextCache, contextCacheRelations, contextConfigs, contextConfigsRelations, conversations, conversationsRelations, credentialReferences, credentialReferencesRelations, dataComponents, dataComponentsRelations, externalAgents, externalAgentsRelations, functionTools, functionToolsRelations, functions, functionsRelations, ledgerArtifacts, ledgerArtifactsRelations, messages, messagesRelations, projects, projectsRelations, schema_exports, subAgentArtifactComponents, subAgentArtifactComponentsRelations, subAgentDataComponents, subAgentDataComponentsRelations, subAgentExternalAgentRelations, subAgentExternalAgentRelationsRelations, subAgentFunctionToolRelations, subAgentFunctionToolRelationsRelations, subAgentRelations, subAgentRelationsRelations, subAgentTeamAgentRelations, subAgentTeamAgentRelationsRelations, subAgentToolRelations, subAgents, subAgentsRelations, taskRelations, taskRelationsRelations, tasks, tasksRelations, tools, toolsRelations };
@@ -0,0 +1,82 @@
1
+ import { pgTable, timestamp, text, boolean } from 'drizzle-orm/pg-core';
2
+
3
+ // src/auth/auth-schema.ts
4
+ var user = pgTable("user", {
5
+ id: text("id").primaryKey(),
6
+ name: text("name").notNull(),
7
+ email: text("email").notNull().unique(),
8
+ emailVerified: boolean("email_verified").default(false).notNull(),
9
+ image: text("image"),
10
+ createdAt: timestamp("created_at").defaultNow().notNull(),
11
+ updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
12
+ });
13
+ var session = pgTable("session", {
14
+ id: text("id").primaryKey(),
15
+ expiresAt: timestamp("expires_at").notNull(),
16
+ token: text("token").notNull().unique(),
17
+ createdAt: timestamp("created_at").defaultNow().notNull(),
18
+ updatedAt: timestamp("updated_at").$onUpdate(() => /* @__PURE__ */ new Date()).notNull(),
19
+ ipAddress: text("ip_address"),
20
+ userAgent: text("user_agent"),
21
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
22
+ activeOrganizationId: text("active_organization_id")
23
+ });
24
+ var account = pgTable("account", {
25
+ id: text("id").primaryKey(),
26
+ accountId: text("account_id").notNull(),
27
+ providerId: text("provider_id").notNull(),
28
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
29
+ accessToken: text("access_token"),
30
+ refreshToken: text("refresh_token"),
31
+ idToken: text("id_token"),
32
+ accessTokenExpiresAt: timestamp("access_token_expires_at"),
33
+ refreshTokenExpiresAt: timestamp("refresh_token_expires_at"),
34
+ scope: text("scope"),
35
+ password: text("password"),
36
+ createdAt: timestamp("created_at").defaultNow().notNull(),
37
+ updatedAt: timestamp("updated_at").$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
38
+ });
39
+ var verification = pgTable("verification", {
40
+ id: text("id").primaryKey(),
41
+ identifier: text("identifier").notNull(),
42
+ value: text("value").notNull(),
43
+ expiresAt: timestamp("expires_at").notNull(),
44
+ createdAt: timestamp("created_at").defaultNow().notNull(),
45
+ updatedAt: timestamp("updated_at").defaultNow().$onUpdate(() => /* @__PURE__ */ new Date()).notNull()
46
+ });
47
+ var ssoProvider = pgTable("sso_provider", {
48
+ id: text("id").primaryKey(),
49
+ issuer: text("issuer").notNull(),
50
+ oidcConfig: text("oidc_config"),
51
+ samlConfig: text("saml_config"),
52
+ userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
53
+ providerId: text("provider_id").notNull().unique(),
54
+ organizationId: text("organization_id"),
55
+ domain: text("domain").notNull()
56
+ });
57
+ var organization = pgTable("organization", {
58
+ id: text("id").primaryKey(),
59
+ name: text("name").notNull(),
60
+ slug: text("slug").notNull().unique(),
61
+ logo: text("logo"),
62
+ createdAt: timestamp("created_at").notNull(),
63
+ metadata: text("metadata")
64
+ });
65
+ var member = pgTable("member", {
66
+ id: text("id").primaryKey(),
67
+ organizationId: text("organization_id").notNull().references(() => organization.id, { onDelete: "cascade" }),
68
+ userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
69
+ role: text("role").default("member").notNull(),
70
+ createdAt: timestamp("created_at").notNull()
71
+ });
72
+ var invitation = pgTable("invitation", {
73
+ id: text("id").primaryKey(),
74
+ organizationId: text("organization_id").notNull().references(() => organization.id, { onDelete: "cascade" }),
75
+ email: text("email").notNull(),
76
+ role: text("role"),
77
+ status: text("status").default("pending").notNull(),
78
+ expiresAt: timestamp("expires_at").notNull(),
79
+ inviterId: text("inviter_id").notNull().references(() => user.id, { onDelete: "cascade" })
80
+ });
81
+
82
+ export { account, invitation, member, organization, session, ssoProvider, user, verification };
@@ -1,4 +1,4 @@
1
- import { AgentWithinContextOfProjectSchema, resourceIdSchema, MAX_ID_LENGTH } from './chunk-DYGTCLJO.js';
1
+ import { AgentWithinContextOfProjectSchema, resourceIdSchema, MAX_ID_LENGTH } from './chunk-VBCCPAZK.js';
2
2
  import { z } from 'zod';
3
3
 
4
4
  // src/validation/cycleDetection.ts
@@ -1,5 +1,3 @@
1
- import { registerClient, startAuthorization, exchangeAuthorization, discoverOAuthProtectedResourceMetadata, discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
2
-
3
1
  // src/constants/otel-attributes.ts
4
2
  var DELEGATION_FROM_SUB_AGENT_ID = "delegation.from_sub_agent_id";
5
3
  var DELEGATION_TO_SUB_AGENT_ID = "delegation.to_sub_agent_id";
@@ -281,162 +279,5 @@ var QUERY_DEFAULTS = {
281
279
  LIMIT_UNLIMITED: 1e4,
282
280
  EMPTY_GROUP_BY: []
283
281
  };
284
- function discoverScopes(resourceMetadata, metadata) {
285
- const resourceScopes = resourceMetadata?.scopes_supported;
286
- const oauthScopes = metadata?.scopes_supported;
287
- const scopes = (resourceScopes?.length ? resourceScopes : oauthScopes) || [];
288
- return scopes.length > 0 ? scopes.join(" ") : void 0;
289
- }
290
- async function discoverMcpMetadata(mcpServerUrl, logger) {
291
- try {
292
- let resourceMetadata = null;
293
- let authServerUrl = new URL(mcpServerUrl);
294
- try {
295
- resourceMetadata = await discoverOAuthProtectedResourceMetadata(mcpServerUrl);
296
- if (resourceMetadata?.authorization_servers?.length && resourceMetadata.authorization_servers[0]) {
297
- authServerUrl = new URL(resourceMetadata.authorization_servers[0]);
298
- }
299
- } catch {
300
- }
301
- const metadata = await discoverAuthorizationServerMetadata(authServerUrl.href);
302
- if (!metadata) {
303
- throw new Error("Failed to discover OAuth authorization server metadata");
304
- }
305
- logger?.debug(
306
- {
307
- tokenEndpoint: metadata.token_endpoint,
308
- authEndpoint: metadata.authorization_endpoint
309
- },
310
- "MCP metadata discovery successful"
311
- );
312
- const discoveredScopes = discoverScopes(resourceMetadata ?? void 0, metadata);
313
- return {
314
- success: true,
315
- metadata,
316
- ...resourceMetadata && { resourceMetadata },
317
- ...discoveredScopes && { scopes: discoveredScopes }
318
- };
319
- } catch (err) {
320
- const errorMessage = err instanceof Error ? err.message : String(err);
321
- logger?.debug({ error: errorMessage }, "MCP metadata discovery failed");
322
- return { success: false, error: errorMessage };
323
- }
324
- }
325
- async function initiateMcpOAuthFlow({
326
- mcpServerUrl,
327
- redirectUri,
328
- state,
329
- clientName = "Inkeep Agent Framework",
330
- clientUri = "https://inkeep.com",
331
- logoUri,
332
- defaultClientId = "mcp-client",
333
- logger
334
- }) {
335
- const discoveryResult = await discoverMcpMetadata(mcpServerUrl, logger);
336
- if (!discoveryResult.success || !discoveryResult.metadata) {
337
- throw new Error(`OAuth not supported by this server: ${discoveryResult.error}`);
338
- }
339
- const { metadata, resourceMetadata, scopes: discoveredScopes } = discoveryResult;
340
- const clientMetadata = {
341
- redirect_uris: [redirectUri],
342
- token_endpoint_auth_method: "none",
343
- // PKCE - no client secret
344
- grant_types: ["authorization_code", "refresh_token"],
345
- response_types: ["code"],
346
- client_name: clientName,
347
- client_uri: clientUri,
348
- ...logoUri && { logo_uri: logoUri }
349
- };
350
- let clientInformation;
351
- if (metadata.registration_endpoint) {
352
- clientInformation = await registerClient(mcpServerUrl, {
353
- metadata,
354
- clientMetadata
355
- });
356
- } else {
357
- clientInformation = {
358
- client_id: defaultClientId,
359
- ...clientMetadata
360
- };
361
- }
362
- const resource = resourceMetadata?.resource ? new globalThis.URL(resourceMetadata.resource) : void 0;
363
- const authResult = await startAuthorization(mcpServerUrl, {
364
- metadata,
365
- clientInformation,
366
- redirectUrl: redirectUri,
367
- state,
368
- scope: discoveredScopes || "",
369
- ...resource && { resource }
370
- });
371
- logger?.debug(
372
- {
373
- authorizationUrl: authResult.authorizationUrl.href,
374
- scopes: discoveredScopes,
375
- clientId: clientInformation.client_id
376
- },
377
- "MCP OAuth flow initiated successfully"
378
- );
379
- return {
380
- authorizationUrl: authResult.authorizationUrl.href,
381
- codeVerifier: authResult.codeVerifier,
382
- state,
383
- clientInformation,
384
- metadata,
385
- resourceUrl: resource?.href || void 0,
386
- ...discoveredScopes && { scopes: discoveredScopes }
387
- };
388
- }
389
- async function exchangeMcpAuthorizationCode({
390
- mcpServerUrl,
391
- metadata,
392
- clientInformation,
393
- authorizationCode,
394
- codeVerifier,
395
- redirectUri,
396
- resourceUrl,
397
- logger
398
- }) {
399
- const resource = resourceUrl ? new globalThis.URL(resourceUrl) : void 0;
400
- const tokens = await exchangeAuthorization(mcpServerUrl, {
401
- metadata,
402
- clientInformation,
403
- authorizationCode,
404
- codeVerifier,
405
- redirectUri,
406
- ...resource && { resource }
407
- });
408
- logger?.debug(
409
- {
410
- tokenType: tokens.token_type,
411
- hasRefreshToken: !!tokens.refresh_token,
412
- expiresIn: tokens.expires_in
413
- },
414
- "MCP token exchange successful"
415
- );
416
- return {
417
- access_token: tokens.access_token,
418
- refresh_token: tokens.refresh_token,
419
- expires_at: tokens.expires_in ? new Date(Date.now() + tokens.expires_in * 1e3) : void 0,
420
- token_type: tokens.token_type || "Bearer",
421
- scope: tokens.scope
422
- };
423
- }
424
- var detectAuthenticationRequired = async ({
425
- serverUrl,
426
- error,
427
- logger
428
- }) => {
429
- try {
430
- const discoveryResult = await discoverMcpMetadata(serverUrl, logger);
431
- if (discoveryResult.success && discoveryResult.metadata) {
432
- logger?.info({ serverUrl }, "MCP OAuth support confirmed via metadata discovery");
433
- return true;
434
- }
435
- } catch (discoveryError) {
436
- logger?.debug({ discoveryError }, "MCP OAuth metadata discovery failed");
437
- }
438
- logger?.debug({ error: error?.message }, "No MCP OAuth authentication requirement detected");
439
- return false;
440
- };
441
282
 
442
- 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, exchangeMcpAuthorizationCode, initiateMcpOAuthFlow };
283
+ 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 };
@@ -1,5 +1,5 @@
1
- import { subAgents, subAgentRelations, agents, tasks, taskRelations, conversations, messages, contextCache, dataComponents, subAgentDataComponents, artifactComponents, subAgentArtifactComponents, externalAgents, apiKeys, credentialReferences, tools, functionTools, functions, contextConfigs, subAgentToolRelations, subAgentExternalAgentRelations, subAgentTeamAgentRelations, ledgerArtifacts, projects } from './chunk-YZ5ZBVHJ.js';
2
1
  import { VALID_RELATION_TYPES, MCPTransportType, TOOL_STATUS_VALUES, CredentialStoreType, MCPServerType } from './chunk-YFHT5M2R.js';
2
+ import { subAgents, subAgentRelations, agents, tasks, taskRelations, conversations, messages, contextCache, dataComponents, subAgentDataComponents, artifactComponents, subAgentArtifactComponents, externalAgents, apiKeys, credentialReferences, tools, functionTools, functions, contextConfigs, subAgentToolRelations, subAgentExternalAgentRelations, subAgentTeamAgentRelations, ledgerArtifacts, projects } from './chunk-NFYCSHD3.js';
3
3
  import { z } from '@hono/zod-openapi';
4
4
  import { createSelectSchema as createSelectSchema$1, createInsertSchema as createInsertSchema$1 } from 'drizzle-zod';
5
5
  import Ajv from 'ajv';