@inkeep/agents-manage-api 0.0.0-dev-20250910232631

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 (108) hide show
  1. package/LICENSE.md +49 -0
  2. package/README.md +176 -0
  3. package/dist/__tests__/setup.d.ts +2 -0
  4. package/dist/__tests__/setup.d.ts.map +1 -0
  5. package/dist/__tests__/setup.js +26 -0
  6. package/dist/__tests__/utils/testProject.d.ts +18 -0
  7. package/dist/__tests__/utils/testProject.d.ts.map +1 -0
  8. package/dist/__tests__/utils/testProject.js +26 -0
  9. package/dist/__tests__/utils/testRequest.d.ts +2 -0
  10. package/dist/__tests__/utils/testRequest.d.ts.map +1 -0
  11. package/dist/__tests__/utils/testRequest.js +11 -0
  12. package/dist/__tests__/utils/testTenant.d.ts +64 -0
  13. package/dist/__tests__/utils/testTenant.d.ts.map +1 -0
  14. package/dist/__tests__/utils/testTenant.js +71 -0
  15. package/dist/app.d.ts +5 -0
  16. package/dist/app.d.ts.map +1 -0
  17. package/dist/app.js +151 -0
  18. package/dist/data/conversations.d.ts +59 -0
  19. package/dist/data/conversations.d.ts.map +1 -0
  20. package/dist/data/conversations.js +216 -0
  21. package/dist/data/db/clean.d.ts +6 -0
  22. package/dist/data/db/clean.d.ts.map +1 -0
  23. package/dist/data/db/clean.js +77 -0
  24. package/dist/data/db/dbClient.d.ts +3 -0
  25. package/dist/data/db/dbClient.d.ts.map +1 -0
  26. package/dist/data/db/dbClient.js +13 -0
  27. package/dist/data/graphFull.d.ts +11 -0
  28. package/dist/data/graphFull.d.ts.map +1 -0
  29. package/dist/data/graphFull.js +90 -0
  30. package/dist/data/graphFullClient.d.ts +22 -0
  31. package/dist/data/graphFullClient.d.ts.map +1 -0
  32. package/dist/data/graphFullClient.js +189 -0
  33. package/dist/data/tools.d.ts +82 -0
  34. package/dist/data/tools.d.ts.map +1 -0
  35. package/dist/data/tools.js +271 -0
  36. package/dist/env.d.ts +41 -0
  37. package/dist/env.d.ts.map +1 -0
  38. package/dist/env.js +59 -0
  39. package/dist/index.d.ts +10 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +27 -0
  42. package/dist/logger.d.ts +4 -0
  43. package/dist/logger.d.ts.map +1 -0
  44. package/dist/logger.js +32 -0
  45. package/dist/middleware/auth.d.ts +12 -0
  46. package/dist/middleware/auth.d.ts.map +1 -0
  47. package/dist/middleware/auth.js +36 -0
  48. package/dist/openapi.d.ts +2 -0
  49. package/dist/openapi.d.ts.map +1 -0
  50. package/dist/openapi.js +38 -0
  51. package/dist/routes/agentArtifactComponents.d.ts +4 -0
  52. package/dist/routes/agentArtifactComponents.d.ts.map +1 -0
  53. package/dist/routes/agentArtifactComponents.js +228 -0
  54. package/dist/routes/agentDataComponents.d.ts +4 -0
  55. package/dist/routes/agentDataComponents.d.ts.map +1 -0
  56. package/dist/routes/agentDataComponents.js +224 -0
  57. package/dist/routes/agentGraph.d.ts +4 -0
  58. package/dist/routes/agentGraph.d.ts.map +1 -0
  59. package/dist/routes/agentGraph.js +287 -0
  60. package/dist/routes/agentRelations.d.ts +4 -0
  61. package/dist/routes/agentRelations.d.ts.map +1 -0
  62. package/dist/routes/agentRelations.js +289 -0
  63. package/dist/routes/agentToolRelations.d.ts +4 -0
  64. package/dist/routes/agentToolRelations.d.ts.map +1 -0
  65. package/dist/routes/agentToolRelations.js +342 -0
  66. package/dist/routes/agents.d.ts +4 -0
  67. package/dist/routes/agents.d.ts.map +1 -0
  68. package/dist/routes/agents.js +212 -0
  69. package/dist/routes/apiKeys.d.ts +4 -0
  70. package/dist/routes/apiKeys.d.ts.map +1 -0
  71. package/dist/routes/apiKeys.js +235 -0
  72. package/dist/routes/artifactComponents.d.ts +4 -0
  73. package/dist/routes/artifactComponents.d.ts.map +1 -0
  74. package/dist/routes/artifactComponents.js +201 -0
  75. package/dist/routes/contextConfigs.d.ts +4 -0
  76. package/dist/routes/contextConfigs.d.ts.map +1 -0
  77. package/dist/routes/contextConfigs.js +180 -0
  78. package/dist/routes/credentials.d.ts +10 -0
  79. package/dist/routes/credentials.d.ts.map +1 -0
  80. package/dist/routes/credentials.js +218 -0
  81. package/dist/routes/dataComponents.d.ts +4 -0
  82. package/dist/routes/dataComponents.d.ts.map +1 -0
  83. package/dist/routes/dataComponents.js +187 -0
  84. package/dist/routes/externalAgents.d.ts +4 -0
  85. package/dist/routes/externalAgents.d.ts.map +1 -0
  86. package/dist/routes/externalAgents.js +215 -0
  87. package/dist/routes/graphFull.d.ts +4 -0
  88. package/dist/routes/graphFull.d.ts.map +1 -0
  89. package/dist/routes/graphFull.js +247 -0
  90. package/dist/routes/index.d.ts +4 -0
  91. package/dist/routes/index.d.ts.map +1 -0
  92. package/dist/routes/index.js +37 -0
  93. package/dist/routes/oauth.d.ts +21 -0
  94. package/dist/routes/oauth.d.ts.map +1 -0
  95. package/dist/routes/oauth.js +191 -0
  96. package/dist/routes/projects.d.ts +4 -0
  97. package/dist/routes/projects.d.ts.map +1 -0
  98. package/dist/routes/projects.js +220 -0
  99. package/dist/routes/tools.d.ts +11 -0
  100. package/dist/routes/tools.d.ts.map +1 -0
  101. package/dist/routes/tools.js +554 -0
  102. package/dist/utils/auth-detection.d.ts +22 -0
  103. package/dist/utils/auth-detection.d.ts.map +1 -0
  104. package/dist/utils/auth-detection.js +149 -0
  105. package/dist/utils/oauth-service.d.ts +88 -0
  106. package/dist/utils/oauth-service.d.ts.map +1 -0
  107. package/dist/utils/oauth-service.js +240 -0
  108. package/package.json +69 -0
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Client-side functions for interacting with the Full Graph API
3
+ * These functions make HTTP requests to the server instead of direct database calls
4
+ */
5
+ import { getLogger } from '../logger';
6
+ const logger = getLogger('graphFullClient');
7
+ /**
8
+ * Create a full graph via HTTP API
9
+ */
10
+ export async function createFullGraphViaAPI(tenantId, projectId, apiUrl, graphData) {
11
+ logger.info({
12
+ tenantId,
13
+ projectId,
14
+ graphId: graphData.id,
15
+ apiUrl,
16
+ }, 'Creating full graph via API');
17
+ const url = `${apiUrl}/tenants/${tenantId}/crud/projects/${projectId}/graph`;
18
+ const response = await fetch(url, {
19
+ method: 'POST',
20
+ headers: {
21
+ 'Content-Type': 'application/json',
22
+ },
23
+ body: JSON.stringify(graphData),
24
+ });
25
+ if (!response.ok) {
26
+ const errorText = await response.text();
27
+ let errorMessage = `Failed to create graph: ${response.status} ${response.statusText}`;
28
+ try {
29
+ const errorJson = JSON.parse(errorText);
30
+ if (errorJson.error) {
31
+ errorMessage = errorJson.error;
32
+ }
33
+ }
34
+ catch {
35
+ // Use the text as-is if not JSON
36
+ if (errorText) {
37
+ errorMessage = errorText;
38
+ }
39
+ }
40
+ logger.error({
41
+ status: response.status,
42
+ error: errorMessage,
43
+ }, 'Failed to create graph via API');
44
+ throw new Error(errorMessage);
45
+ }
46
+ const result = await response.json();
47
+ logger.info({
48
+ graphId: graphData.id,
49
+ }, 'Successfully created graph via API');
50
+ return result.data;
51
+ }
52
+ /**
53
+ * Update a full graph via HTTP API (upsert behavior)
54
+ */
55
+ export async function updateFullGraphViaAPI(tenantId, projectId, apiUrl, graphId, graphData) {
56
+ logger.info({
57
+ tenantId,
58
+ projectId,
59
+ graphId,
60
+ apiUrl,
61
+ }, 'Updating full graph via API');
62
+ const url = `${apiUrl}/tenants/${tenantId}/crud/projects/${projectId}/graph/${graphId}`;
63
+ const response = await fetch(url, {
64
+ method: 'PUT',
65
+ headers: {
66
+ 'Content-Type': 'application/json',
67
+ },
68
+ body: JSON.stringify(graphData),
69
+ });
70
+ if (!response.ok) {
71
+ const errorText = await response.text();
72
+ let errorMessage = `Failed to update graph: ${response.status} ${response.statusText}`;
73
+ try {
74
+ const errorJson = JSON.parse(errorText);
75
+ if (errorJson.error) {
76
+ errorMessage = errorJson.error;
77
+ }
78
+ }
79
+ catch {
80
+ // Use the text as-is if not JSON
81
+ if (errorText) {
82
+ errorMessage = errorText;
83
+ }
84
+ }
85
+ logger.error({
86
+ status: response.status,
87
+ error: errorMessage,
88
+ }, 'Failed to update graph via API');
89
+ throw new Error(errorMessage);
90
+ }
91
+ const result = await response.json();
92
+ logger.info({
93
+ graphId,
94
+ }, 'Successfully updated graph via API');
95
+ return result.data;
96
+ }
97
+ /**
98
+ * Get a full graph via HTTP API
99
+ */
100
+ export async function getFullGraphViaAPI(tenantId, projectId, apiUrl, graphId) {
101
+ logger.info({
102
+ tenantId,
103
+ projectId,
104
+ graphId,
105
+ apiUrl,
106
+ }, 'Getting full graph via API');
107
+ const url = `${apiUrl}/tenants/${tenantId}/crud/projects/${projectId}/graph/${graphId}`;
108
+ const response = await fetch(url, {
109
+ method: 'GET',
110
+ headers: {
111
+ 'Content-Type': 'application/json',
112
+ },
113
+ });
114
+ if (response.status === 404) {
115
+ return null;
116
+ }
117
+ if (!response.ok) {
118
+ const errorText = await response.text();
119
+ let errorMessage = `Failed to get graph: ${response.status} ${response.statusText}`;
120
+ try {
121
+ const errorJson = JSON.parse(errorText);
122
+ if (errorJson.error) {
123
+ errorMessage = errorJson.error;
124
+ }
125
+ }
126
+ catch {
127
+ // Use the text as-is if not JSON
128
+ if (errorText) {
129
+ errorMessage = errorText;
130
+ }
131
+ }
132
+ logger.error({
133
+ status: response.status,
134
+ error: errorMessage,
135
+ }, 'Failed to get graph via API');
136
+ throw new Error(errorMessage);
137
+ }
138
+ const result = await response.json();
139
+ logger.info({
140
+ graphId,
141
+ }, 'Successfully retrieved graph via API');
142
+ return result.data;
143
+ }
144
+ /**
145
+ * Delete a full graph via HTTP API
146
+ */
147
+ export async function deleteFullGraphViaAPI(tenantId, projectId, apiUrl, graphId) {
148
+ logger.info({
149
+ tenantId,
150
+ projectId,
151
+ graphId,
152
+ apiUrl,
153
+ }, 'Deleting full graph via API');
154
+ const url = `${apiUrl}/tenants/${tenantId}/crud/projects/${projectId}/graph/${graphId}`;
155
+ const response = await fetch(url, {
156
+ method: 'DELETE',
157
+ headers: {
158
+ 'Content-Type': 'application/json',
159
+ },
160
+ });
161
+ if (response.status === 404) {
162
+ return false;
163
+ }
164
+ if (!response.ok) {
165
+ const errorText = await response.text();
166
+ let errorMessage = `Failed to delete graph: ${response.status} ${response.statusText}`;
167
+ try {
168
+ const errorJson = JSON.parse(errorText);
169
+ if (errorJson.error) {
170
+ errorMessage = errorJson.error;
171
+ }
172
+ }
173
+ catch {
174
+ // Use the text as-is if not JSON
175
+ if (errorText) {
176
+ errorMessage = errorText;
177
+ }
178
+ }
179
+ logger.error({
180
+ status: response.status,
181
+ error: errorMessage,
182
+ }, 'Failed to delete graph via API');
183
+ throw new Error(errorMessage);
184
+ }
185
+ logger.info({
186
+ graphId,
187
+ }, 'Successfully deleted graph via API');
188
+ return true;
189
+ }
@@ -0,0 +1,82 @@
1
+ import { type CredentialStoreRegistry, type McpServerCapabilities, type McpTool, type McpToolDefinition, type McpToolStatus } from '@inkeep/agents-core';
2
+ export declare const updateToolHealth: ({ tenantId, projectId, toolId, status, error, }: {
3
+ tenantId: string;
4
+ projectId: string;
5
+ toolId: string;
6
+ status: McpToolStatus;
7
+ error?: string;
8
+ }) => Promise<{
9
+ name: string;
10
+ headers: Record<string, string> | null;
11
+ id: string;
12
+ tenantId: string;
13
+ projectId: string;
14
+ createdAt: string;
15
+ updatedAt: string;
16
+ credentialReferenceId: string | null;
17
+ status: string;
18
+ config: {
19
+ type: "mcp";
20
+ mcp: import("@inkeep/agents-core").ToolMcpConfig;
21
+ };
22
+ imageUrl: string | null;
23
+ capabilities: import("@inkeep/agents-core").ToolServerCapabilities | null;
24
+ lastHealthCheck: string | null;
25
+ lastError: string | null;
26
+ availableTools: McpToolDefinition[] | null;
27
+ lastToolsSync: string | null;
28
+ }>;
29
+ export declare const checkToolHealth: (tool: McpTool, credentialStoreRegistry?: CredentialStoreRegistry) => Promise<{
30
+ status: McpToolStatus;
31
+ error?: string;
32
+ capabilities?: McpServerCapabilities;
33
+ }>;
34
+ export declare const discoverToolsFromServer: (tool: McpTool, credentialStoreRegistry?: CredentialStoreRegistry) => Promise<McpToolDefinition[]>;
35
+ export declare const syncToolDefinitions: ({ tenantId, projectId, toolId, credentialStoreRegistry, }: {
36
+ tenantId: string;
37
+ projectId: string;
38
+ toolId: string;
39
+ credentialStoreRegistry?: CredentialStoreRegistry;
40
+ }) => Promise<{
41
+ name: string;
42
+ headers: Record<string, string> | null;
43
+ id: string;
44
+ tenantId: string;
45
+ projectId: string;
46
+ createdAt: string;
47
+ updatedAt: string;
48
+ credentialReferenceId: string | null;
49
+ status: string;
50
+ config: {
51
+ type: "mcp";
52
+ mcp: import("@inkeep/agents-core").ToolMcpConfig;
53
+ };
54
+ imageUrl: string | null;
55
+ capabilities: import("@inkeep/agents-core").ToolServerCapabilities | null;
56
+ lastHealthCheck: string | null;
57
+ lastError: string | null;
58
+ availableTools: McpToolDefinition[] | null;
59
+ lastToolsSync: string | null;
60
+ }>;
61
+ export declare const checkAllToolsHealth: (tenantId: string, projectId: string, credentialStoreRegistry?: CredentialStoreRegistry) => Promise<PromiseSettledResult<{
62
+ name: string;
63
+ headers: Record<string, string> | null;
64
+ id: string;
65
+ tenantId: string;
66
+ projectId: string;
67
+ createdAt: string;
68
+ updatedAt: string;
69
+ credentialReferenceId: string | null;
70
+ status: string;
71
+ config: {
72
+ type: "mcp";
73
+ mcp: import("@inkeep/agents-core").ToolMcpConfig;
74
+ };
75
+ imageUrl: string | null;
76
+ capabilities: import("@inkeep/agents-core").ToolServerCapabilities | null;
77
+ lastHealthCheck: string | null;
78
+ lastError: string | null;
79
+ availableTools: McpToolDefinition[] | null;
80
+ lastToolsSync: string | null;
81
+ }>[]>;
82
+ //# sourceMappingURL=tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/data/tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,uBAAuB,EAS5B,KAAK,qBAAqB,EAI1B,KAAK,OAAO,EACZ,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAGnB,MAAM,qBAAqB,CAAC;AAkD7B,eAAO,MAAM,gBAAgB,GAAU,iDAMpC;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,aAAa,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;;;;;;;;;;;;;;;;;;;;EAmBA,CAAC;AAEF,eAAO,MAAM,eAAe,GAC1B,MAAM,OAAO,EACb,0BAA0B,uBAAuB,KAChD,OAAO,CAAC;IACT,MAAM,EAAE,aAAa,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,qBAAqB,CAAC;CACtC,CAqGA,CAAC;AAGF,eAAO,MAAM,uBAAuB,GAClC,MAAM,OAAO,EACb,0BAA0B,uBAAuB,KAChD,OAAO,CAAC,iBAAiB,EAAE,CAuF7B,CAAC;AAEF,eAAO,MAAM,mBAAmB,GAAU,2DAKvC;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,uBAAuB,CAAC,EAAE,uBAAuB,CAAC;CACnD;;;;;;;;;;;;;;;;;;;;EA+CA,CAAC;AAGF,eAAO,MAAM,mBAAmB,GAC9B,UAAU,MAAM,EAChB,WAAW,MAAM,EACjB,0BAA0B,uBAAuB;;;;;;;;;;;;;;;;;;;;KAkBlD,CAAC"}
@@ -0,0 +1,271 @@
1
+ import { ContextResolver, CredentialStuffer, dbResultToMcpTool, detectAuthenticationRequired, getCredentialReference, getToolById, listTools, McpClient, updateTool, } from '@inkeep/agents-core';
2
+ import { getLogger } from '../logger';
3
+ import dbClient from './db/dbClient';
4
+ /**
5
+ * Extract input schema from MCP tool definition, handling multiple formats
6
+ * Different MCP servers may use different schema structures:
7
+ * - inputSchema (direct) - e.g., Notion MCP
8
+ * - parameters.properties - e.g., some other MCP servers
9
+ * - parameters (direct) - alternative format
10
+ * - schema - another possible location
11
+ */
12
+ function extractInputSchema(toolDef) {
13
+ // Try different possible locations for the input schema
14
+ if (toolDef.inputSchema) {
15
+ return toolDef.inputSchema;
16
+ }
17
+ if (toolDef.parameters?.properties) {
18
+ return toolDef.parameters.properties;
19
+ }
20
+ if (toolDef.parameters && typeof toolDef.parameters === 'object') {
21
+ return toolDef.parameters;
22
+ }
23
+ if (toolDef.schema) {
24
+ return toolDef.schema;
25
+ }
26
+ // If none found, return empty object
27
+ return {};
28
+ }
29
+ const logger = getLogger('tools');
30
+ // Helper function to convert McpTool to MCPToolConfig format for CredentialStuffer
31
+ const convertToMCPToolConfig = (tool) => {
32
+ return {
33
+ id: tool.id,
34
+ name: tool.name,
35
+ description: tool.name, // Use name as description fallback
36
+ serverUrl: tool.config.mcp.server.url,
37
+ mcpType: tool.config.mcp.server.url.includes('api.nango.dev') ? 'nango' : 'generic',
38
+ transport: tool.config.mcp.transport,
39
+ headers: tool.headers,
40
+ };
41
+ };
42
+ // Health checking and monitoring
43
+ export const updateToolHealth = async ({ tenantId, projectId, toolId, status, error, }) => {
44
+ const now = new Date().toISOString();
45
+ const updateData = {
46
+ status,
47
+ lastHealthCheck: now,
48
+ updatedAt: now,
49
+ };
50
+ if (error !== undefined) {
51
+ updateData.lastError = error;
52
+ }
53
+ const tool = await updateTool(dbClient)({
54
+ scopes: { tenantId, projectId },
55
+ toolId,
56
+ data: updateData,
57
+ });
58
+ return tool;
59
+ };
60
+ export const checkToolHealth = async (tool, credentialStoreRegistry) => {
61
+ try {
62
+ const transportType = tool.config.mcp.transport?.type || 'streamable_http';
63
+ const baseConfig = {
64
+ url: tool.config.mcp.server.url,
65
+ };
66
+ const credentialReferenceId = tool.credentialReferenceId;
67
+ let serverConfig;
68
+ // Build server config with credentials if available
69
+ if (credentialReferenceId) {
70
+ // Get credential store configuration
71
+ const credentialReference = await getCredentialReference(dbClient)({
72
+ scopes: { tenantId: tool.tenantId, projectId: tool.projectId },
73
+ id: credentialReferenceId,
74
+ });
75
+ if (!credentialReference) {
76
+ throw new Error(`Credential store not found: ${credentialReferenceId}`);
77
+ }
78
+ const storeReference = {
79
+ credentialStoreId: credentialReference.credentialStoreId,
80
+ retrievalParams: credentialReference.retrievalParams || {},
81
+ };
82
+ // Use CredentialStuffer to build proper config with auth headers
83
+ if (!credentialStoreRegistry) {
84
+ throw new Error('CredentialStoreRegistry is required for authenticated tools');
85
+ }
86
+ const contextResolver = new ContextResolver(tool.tenantId, tool.projectId, dbClient, credentialStoreRegistry);
87
+ const credentialStuffer = new CredentialStuffer(credentialStoreRegistry, contextResolver);
88
+ serverConfig = await credentialStuffer.buildMcpServerConfig({ tenantId: tool.tenantId, projectId: tool.projectId }, convertToMCPToolConfig(tool), storeReference);
89
+ }
90
+ else {
91
+ if (transportType === 'sse') {
92
+ serverConfig = {
93
+ type: 'sse',
94
+ url: baseConfig.url,
95
+ activeTools: tool.config.mcp.activeTools,
96
+ eventSourceInit: tool.config.mcp.transport?.eventSourceInit,
97
+ };
98
+ }
99
+ else {
100
+ serverConfig = {
101
+ type: 'streamable_http',
102
+ url: baseConfig.url,
103
+ activeTools: tool.config.mcp.activeTools,
104
+ requestInit: tool.config.mcp.transport?.requestInit,
105
+ eventSourceInit: tool.config.mcp.transport?.eventSourceInit,
106
+ reconnectionOptions: tool.config.mcp.transport?.reconnectionOptions,
107
+ sessionId: tool.config.mcp.transport?.sessionId,
108
+ };
109
+ }
110
+ }
111
+ const client = new McpClient({
112
+ name: tool.name,
113
+ server: serverConfig,
114
+ });
115
+ await client.connect();
116
+ // Try to list tools to verify connection
117
+ await client.tools();
118
+ await client.disconnect();
119
+ return {
120
+ status: 'healthy',
121
+ capabilities: {
122
+ tools: true,
123
+ resources: false, // Could be enhanced to check actual capabilities
124
+ prompts: false,
125
+ logging: false,
126
+ },
127
+ };
128
+ }
129
+ catch (error) {
130
+ logger.error({ toolId: tool.id, error }, 'Tool health check failed');
131
+ // Check if error indicates authentication is required
132
+ if (error instanceof Error && (await detectAuthenticationRequired(tool, error))) {
133
+ return {
134
+ status: 'needs_auth',
135
+ error: 'Authentication required - OAuth login needed',
136
+ };
137
+ }
138
+ return {
139
+ status: 'unhealthy',
140
+ error: error instanceof Error ? error.message : 'Unknown error',
141
+ };
142
+ }
143
+ };
144
+ // Tool discovery
145
+ export const discoverToolsFromServer = async (tool, credentialStoreRegistry) => {
146
+ try {
147
+ const credentialReferenceId = tool.credentialReferenceId;
148
+ let serverConfig;
149
+ // Build server config with credentials if available
150
+ if (credentialReferenceId) {
151
+ // Get credential store configuration
152
+ const credentialReference = await getCredentialReference(dbClient)({
153
+ scopes: { tenantId: tool.tenantId, projectId: tool.projectId },
154
+ id: credentialReferenceId,
155
+ });
156
+ if (!credentialReference) {
157
+ throw new Error(`Credential store not found: ${credentialReferenceId}`);
158
+ }
159
+ const storeReference = {
160
+ credentialStoreId: credentialReference.credentialStoreId,
161
+ retrievalParams: credentialReference.retrievalParams || {},
162
+ };
163
+ // Use CredentialStuffer to build proper config with auth headers
164
+ if (!credentialStoreRegistry) {
165
+ throw new Error('CredentialStoreRegistry is required for authenticated tools');
166
+ }
167
+ const contextResolver = new ContextResolver(tool.tenantId, tool.projectId, dbClient, credentialStoreRegistry);
168
+ const credentialStuffer = new CredentialStuffer(credentialStoreRegistry, contextResolver);
169
+ serverConfig = (await credentialStuffer.buildMcpServerConfig({ tenantId: tool.tenantId, projectId: tool.projectId }, convertToMCPToolConfig(tool), storeReference));
170
+ }
171
+ else {
172
+ // No credentials - build basic config
173
+ const transportType = tool.config.mcp.transport?.type || 'streamable_http';
174
+ if (transportType === 'sse') {
175
+ serverConfig = {
176
+ type: 'sse',
177
+ url: tool.config.mcp.server.url,
178
+ activeTools: tool.config.mcp.activeTools,
179
+ eventSourceInit: tool.config.mcp.transport?.eventSourceInit,
180
+ };
181
+ }
182
+ else {
183
+ serverConfig = {
184
+ type: 'streamable_http',
185
+ url: tool.config.mcp.server.url,
186
+ activeTools: tool.config.mcp.activeTools,
187
+ requestInit: tool.config.mcp.transport?.requestInit,
188
+ eventSourceInit: tool.config.mcp.transport?.eventSourceInit,
189
+ reconnectionOptions: tool.config.mcp.transport?.reconnectionOptions,
190
+ sessionId: tool.config.mcp.transport?.sessionId,
191
+ };
192
+ }
193
+ }
194
+ const client = new McpClient({
195
+ name: tool.name,
196
+ server: serverConfig,
197
+ });
198
+ await client.connect();
199
+ // Get tools from the MCP client
200
+ const serverTools = await client.tools();
201
+ await client.disconnect();
202
+ // Convert to our format
203
+ const toolDefinitions = Object.entries(serverTools).map(([name, toolDef]) => ({
204
+ name,
205
+ description: toolDef.description || '',
206
+ inputSchema: extractInputSchema(toolDef),
207
+ }));
208
+ return toolDefinitions;
209
+ }
210
+ catch (error) {
211
+ logger.error({ toolId: tool.id, error }, 'Tool discovery failed');
212
+ throw error;
213
+ }
214
+ };
215
+ export const syncToolDefinitions = async ({ tenantId, projectId, toolId, credentialStoreRegistry, }) => {
216
+ const tool = await getToolById(dbClient)({ scopes: { tenantId, projectId }, toolId });
217
+ if (!tool) {
218
+ throw new Error(`Tool ${toolId} not found`);
219
+ }
220
+ const mcpTool = dbResultToMcpTool(tool);
221
+ try {
222
+ const availableTools = await discoverToolsFromServer(mcpTool, credentialStoreRegistry);
223
+ const updatedTool = await updateTool(dbClient)({
224
+ scopes: { tenantId, projectId },
225
+ toolId,
226
+ data: {
227
+ availableTools,
228
+ lastToolsSync: new Date().toISOString(),
229
+ status: 'healthy',
230
+ updatedAt: new Date().toISOString(),
231
+ },
232
+ });
233
+ return updatedTool;
234
+ }
235
+ catch (error) {
236
+ const toolNeedsAuth = error instanceof Error && (await detectAuthenticationRequired(mcpTool, error));
237
+ const now = new Date().toISOString();
238
+ const updatedTool = await updateTool(dbClient)({
239
+ scopes: { tenantId, projectId },
240
+ toolId,
241
+ data: {
242
+ availableTools: [],
243
+ lastToolsSync: new Date().toISOString(),
244
+ status: toolNeedsAuth ? 'needs_auth' : 'unhealthy',
245
+ lastError: toolNeedsAuth
246
+ ? 'Authentication required - OAuth login needed'
247
+ : error instanceof Error
248
+ ? error.message
249
+ : 'Tool sync failed',
250
+ lastHealthCheck: now,
251
+ updatedAt: now,
252
+ },
253
+ });
254
+ return updatedTool;
255
+ }
256
+ };
257
+ // Bulk health checking
258
+ export const checkAllToolsHealth = async (tenantId, projectId, credentialStoreRegistry) => {
259
+ const toolsList = await listTools(dbClient)({ scopes: { tenantId, projectId } });
260
+ const results = await Promise.allSettled(toolsList.data.map(async (tool) => {
261
+ const healthResult = await checkToolHealth(dbResultToMcpTool(tool), credentialStoreRegistry);
262
+ return await updateToolHealth({
263
+ tenantId,
264
+ projectId: tool.projectId,
265
+ toolId: tool.id,
266
+ status: healthResult.status,
267
+ error: healthResult.error,
268
+ });
269
+ }));
270
+ return results;
271
+ };
package/dist/env.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ declare const envSchema: z.ZodObject<{
3
+ NODE_ENV: z.ZodOptional<z.ZodEnum<{
4
+ development: "development";
5
+ production: "production";
6
+ test: "test";
7
+ }>>;
8
+ ENVIRONMENT: z.ZodOptional<z.ZodEnum<{
9
+ development: "development";
10
+ pentest: "pentest";
11
+ production: "production";
12
+ test: "test";
13
+ }>>;
14
+ DB_FILE_NAME: z.ZodDefault<z.ZodString>;
15
+ PORT: z.ZodDefault<z.ZodOptional<z.ZodCoercedNumber<unknown>>>;
16
+ MANAGEMENT_PORT: z.ZodDefault<z.ZodOptional<z.ZodCoercedNumber<unknown>>>;
17
+ AGENT_BASE_URL: z.ZodOptional<z.ZodString>;
18
+ LOG_LEVEL: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
19
+ error: "error";
20
+ debug: "debug";
21
+ info: "info";
22
+ trace: "trace";
23
+ warn: "warn";
24
+ }>>>;
25
+ NANGO_SECRET_KEY: z.ZodOptional<z.ZodString>;
26
+ INKEEP_AGENTS_MANAGE_API_SECRET: z.ZodOptional<z.ZodString>;
27
+ }, z.core.$strip>;
28
+ export declare const env: {
29
+ DB_FILE_NAME: string;
30
+ PORT: number;
31
+ MANAGEMENT_PORT: number;
32
+ LOG_LEVEL: "error" | "debug" | "info" | "trace" | "warn";
33
+ NODE_ENV?: "development" | "production" | "test" | undefined;
34
+ ENVIRONMENT?: "development" | "pentest" | "production" | "test" | undefined;
35
+ AGENT_BASE_URL?: string | undefined;
36
+ NANGO_SECRET_KEY?: string | undefined;
37
+ INKEEP_AGENTS_MANAGE_API_SECRET?: string | undefined;
38
+ };
39
+ export type Env = z.infer<typeof envSchema>;
40
+ export {};
41
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAkCxB,QAAA,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;iBAUb,CAAC;AAuBH,eAAO,MAAM,GAAG;;;;;;;;;;CAAa,CAAC;AAC9B,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,CAAC"}
package/dist/env.js ADDED
@@ -0,0 +1,59 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import * as dotenv from 'dotenv';
4
+ import { z } from 'zod';
5
+ dotenv.config({ quiet: true });
6
+ const _nodeEnvSchema = z.enum(['development', 'production']).default('development');
7
+ const environmentSchema = z.enum(['development', 'pentest', 'production', 'test']);
8
+ const criticalEnv = z
9
+ .object({
10
+ ENVIRONMENT: environmentSchema,
11
+ })
12
+ .parse(process.env);
13
+ const loadEnvFile = () => {
14
+ // Priority of environment variables:
15
+ // 1. Existing process.env variables (highest priority)
16
+ // 2. Values from .env.{nodeEnv}.nonsecret file (lower priority)
17
+ // 3. Default values defined in schema (lowest priority)
18
+ const envPath = path.resolve(process.cwd(), `.env.${criticalEnv.ENVIRONMENT}.nonsecret`);
19
+ if (fs.existsSync(envPath)) {
20
+ const envConfig = dotenv.parse(fs.readFileSync(envPath));
21
+ for (const k in envConfig) {
22
+ // Only set if the environment variable doesn't already exist
23
+ // This preserves any values that were already set in process.env
24
+ if (!(k in process.env)) {
25
+ process.env[k] = envConfig[k];
26
+ }
27
+ }
28
+ }
29
+ };
30
+ loadEnvFile();
31
+ const envSchema = z.object({
32
+ NODE_ENV: z.enum(['development', 'production', 'test']).optional(),
33
+ ENVIRONMENT: z.enum(['development', 'production', 'pentest', 'test']).optional(),
34
+ DB_FILE_NAME: z.string().default('file:../local.db'),
35
+ PORT: z.coerce.number().optional().default(3002),
36
+ MANAGEMENT_PORT: z.coerce.number().optional().default(3002),
37
+ AGENT_BASE_URL: z.string().optional(),
38
+ LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warn', 'error']).optional().default('debug'),
39
+ NANGO_SECRET_KEY: z.string().optional(),
40
+ INKEEP_AGENTS_MANAGE_API_SECRET: z.string().optional(),
41
+ });
42
+ const parseEnv = () => {
43
+ try {
44
+ const parsedEnv = envSchema.parse(process.env);
45
+ // Set default AGENT_BASE_URL if not provided
46
+ if (!parsedEnv.AGENT_BASE_URL) {
47
+ parsedEnv.AGENT_BASE_URL = `http://localhost:${parsedEnv.PORT}`;
48
+ }
49
+ return parsedEnv;
50
+ }
51
+ catch (error) {
52
+ if (error instanceof z.ZodError) {
53
+ const missingVars = error.issues.map((issue) => issue.path.join('.'));
54
+ throw new Error(`❌ Invalid environment variables: ${missingVars.join(', ')}\n${error.message}`);
55
+ }
56
+ throw error;
57
+ }
58
+ };
59
+ export const env = parseEnv();
@@ -0,0 +1,10 @@
1
+ import { type CredentialStore, type ServerConfig } from '@inkeep/agents-core';
2
+ import { createManagementHono } from './app';
3
+ declare const app: import("hono").Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
4
+ export default app;
5
+ export { createManagementHono };
6
+ export declare function createManagementApp(config?: {
7
+ serverConfig?: ServerConfig;
8
+ credentialStores?: CredentialStore[];
9
+ }): import("hono").Hono<import("hono/types").BlankEnv, import("hono/types").BlankSchema, "/">;
10
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,eAAe,EAGpB,KAAK,YAAY,EAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAiB7C,QAAA,MAAM,GAAG,2FAAuD,CAAC;AAGjE,eAAe,GAAG,CAAC;AAGnB,OAAO,EAAE,oBAAoB,EAAE,CAAC;AAGhC,wBAAgB,mBAAmB,CAAC,MAAM,CAAC,EAAE;IAC3C,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,gBAAgB,CAAC,EAAE,eAAe,EAAE,CAAC;CACtC,6FAMA"}