@inkeep/agents-run-api 0.14.2 → 0.14.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.
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
- import { defaultBatchProcessor } from './chunk-Z76LOSTO.js';
1
+ import { flushBatchProcessor } from './chunk-XO4RG36I.js';
2
2
  import { getLogger } from './chunk-A2S7GSHL.js';
3
- import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-F46V23RK.js';
4
- import { dbClient_default, env } from './chunk-TWVQBIUL.js';
3
+ import { getFormattedConversationHistory, createDefaultConversationHistoryConfig, saveA2AMessageResponse } from './chunk-5GUNCN5X.js';
4
+ import { dbClient_default } from './chunk-7IMXW4RD.js';
5
+ import { env } from './chunk-NZHNG4A3.js';
5
6
  import { __publicField } from './chunk-PKBMQBKP.js';
6
7
  import { getLogger as getLogger$1, getTracer, HeadersScopeSchema, getRequestExecutionContext, createApiError, getAgentGraphWithDefaultAgent, contextValidationMiddleware, getFullGraph, createOrGetConversation, getActiveAgentForConversation, setActiveAgentForConversation, getAgentById, handleContextResolution, createMessage, commonGetErrorResponses, loggerFactory, createDefaultCredentialStores, CredentialStoreRegistry, listTaskIdsByContextId, getTask, getLedgerArtifacts, upsertLedgerArtifact, getAgentGraphById, createTask, updateTask, setSpanWithError, updateConversation, handleApiError, TaskState, setActiveAgentForThread, getConversation, getRelatedAgentsForGraph, getToolsForAgent, getDataComponentsForAgent, getArtifactComponentsForAgent, dbResultToMcpTool, validateAndGetApiKey, getProject, ContextResolver, CredentialStuffer, MCPServerType, getCredentialReference, McpClient, getContextConfigById, getFullGraphDefinition, TemplateEngine, graphHasArtifactComponents, MCPTransportType, getExternalAgent } from '@inkeep/agents-core';
7
8
  import { otel } from '@hono/otel';
@@ -2709,7 +2710,6 @@ ${this.statusUpdateState?.config.prompt?.trim() || ""}`;
2709
2710
  return { summaries: [] };
2710
2711
  } finally {
2711
2712
  span.end();
2712
- await defaultBatchProcessor.forceFlush();
2713
2713
  }
2714
2714
  }
2715
2715
  );
@@ -3128,7 +3128,6 @@ Make it specific and relevant.`;
3128
3128
  );
3129
3129
  } finally {
3130
3130
  span.end();
3131
- await defaultBatchProcessor.forceFlush();
3132
3131
  }
3133
3132
  }
3134
3133
  );
@@ -3684,7 +3683,6 @@ var ResponseFormatter = class {
3684
3683
  };
3685
3684
  } finally {
3686
3685
  span.end();
3687
- await defaultBatchProcessor.forceFlush();
3688
3686
  }
3689
3687
  });
3690
3688
  }
@@ -3735,7 +3733,6 @@ var ResponseFormatter = class {
3735
3733
  return { text: responseText };
3736
3734
  } finally {
3737
3735
  span.end();
3738
- await defaultBatchProcessor.forceFlush();
3739
3736
  }
3740
3737
  });
3741
3738
  }
@@ -6166,6 +6163,8 @@ var Agent = class {
6166
6163
  __publicField(this, "isDelegatedAgent", false);
6167
6164
  __publicField(this, "contextResolver");
6168
6165
  __publicField(this, "credentialStoreRegistry");
6166
+ __publicField(this, "mcpClientCache", /* @__PURE__ */ new Map());
6167
+ __publicField(this, "mcpConnectionLocks", /* @__PURE__ */ new Map());
6169
6168
  this.artifactComponents = config.artifactComponents || [];
6170
6169
  let processedDataComponents = config.dataComponents || [];
6171
6170
  if (processedDataComponents.length > 0) {
@@ -6488,6 +6487,7 @@ var Agent = class {
6488
6487
  };
6489
6488
  }
6490
6489
  async getMcpTool(tool3) {
6490
+ const cacheKey = `${this.config.tenantId}-${this.config.projectId}-${tool3.id}-${tool3.credentialReferenceId || "no-cred"}`;
6491
6491
  const credentialReferenceId = tool3.credentialReferenceId;
6492
6492
  const toolsForAgent = await getToolsForAgent(dbClient_default)({
6493
6493
  scopes: {
@@ -6556,12 +6556,56 @@ var Agent = class {
6556
6556
  },
6557
6557
  "Built MCP server config with credentials"
6558
6558
  );
6559
+ let client = this.mcpClientCache.get(cacheKey);
6560
+ if (client && !client.isConnected()) {
6561
+ this.mcpClientCache.delete(cacheKey);
6562
+ client = void 0;
6563
+ }
6564
+ if (!client) {
6565
+ let connectionPromise = this.mcpConnectionLocks.get(cacheKey);
6566
+ if (!connectionPromise) {
6567
+ connectionPromise = this.createMcpConnection(tool3, serverConfig);
6568
+ this.mcpConnectionLocks.set(cacheKey, connectionPromise);
6569
+ }
6570
+ try {
6571
+ client = await connectionPromise;
6572
+ this.mcpClientCache.set(cacheKey, client);
6573
+ } catch (error) {
6574
+ this.mcpConnectionLocks.delete(cacheKey);
6575
+ logger16.error(
6576
+ {
6577
+ toolName: tool3.name,
6578
+ agentId: this.config.id,
6579
+ cacheKey,
6580
+ error: error instanceof Error ? error.message : String(error)
6581
+ },
6582
+ "MCP connection failed"
6583
+ );
6584
+ throw error;
6585
+ }
6586
+ }
6587
+ const tools = await client.tools();
6588
+ return tools;
6589
+ }
6590
+ async createMcpConnection(tool3, serverConfig) {
6559
6591
  const client = new McpClient({
6560
6592
  name: tool3.name,
6561
6593
  server: serverConfig
6562
6594
  });
6563
- await client.connect();
6564
- return client.tools();
6595
+ try {
6596
+ await client.connect();
6597
+ return client;
6598
+ } catch (error) {
6599
+ logger16.error(
6600
+ {
6601
+ toolName: tool3.name,
6602
+ agentId: this.config.id,
6603
+ error: error instanceof Error ? error.message : String(error)
6604
+ },
6605
+ "Agent failed to connect to MCP server"
6606
+ );
6607
+ throw error;
6608
+ }
6565
6609
  }
6566
6610
  getFunctionTools(streamRequestId) {
6567
6611
  if (!this.config.functionTools) return {};
@@ -6607,7 +6651,6 @@ var Agent = class {
6607
6651
  requestContext: requestContext || {},
6608
6652
  tenantId: this.config.tenantId
6609
6653
  });
6610
- await defaultBatchProcessor.forceFlush();
6611
6654
  const contextWithBuiltins = {
6612
6655
  ...result.resolvedContext,
6613
6656
  $now: (/* @__PURE__ */ new Date()).toISOString(),
@@ -6777,7 +6820,7 @@ var Agent = class {
6777
6820
  inputSchema: tool3.inputSchema || tool3.parameters || {},
6778
6821
  usageGuidelines: name.startsWith("transfer_to_") || name.startsWith("delegate_to_") ? `Use this tool to ${name.startsWith("transfer_to_") ? "transfer" : "delegate"} to another agent when appropriate.` : "Use this tool when appropriate for the task at hand."
6779
6822
  }));
6780
- const { getConversationScopedArtifacts } = await import('./conversations-AP5WZGWA.js');
6823
+ const { getConversationScopedArtifacts } = await import('./conversations-6HJ4FX5F.js');
6781
6824
  const historyConfig = this.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
6782
6825
  const referenceArtifacts = await getConversationScopedArtifacts({
6783
6826
  tenantId: this.config.tenantId,
@@ -7146,7 +7189,6 @@ var Agent = class {
7146
7189
  throw err;
7147
7190
  } finally {
7148
7191
  childSpan.end();
7149
- await defaultBatchProcessor.forceFlush();
7150
7192
  }
7151
7193
  }
7152
7194
  );
@@ -7577,7 +7619,6 @@ ${output}${structureHintsFormatted}`;
7577
7619
  }
7578
7620
  span.setStatus({ code: SpanStatusCode.OK });
7579
7621
  span.end();
7580
- await defaultBatchProcessor.forceFlush();
7581
7622
  let formattedContent = response.formattedContent || null;
7582
7623
  if (!formattedContent) {
7583
7624
  const session = toolSessionManager.getSession(sessionId);
@@ -9129,7 +9170,6 @@ var ExecutionHandler = class {
9129
9170
  throw error;
9130
9171
  } finally {
9131
9172
  span.end();
9132
- await defaultBatchProcessor.forceFlush();
9133
9173
  }
9134
9174
  });
9135
9175
  }
@@ -9651,7 +9691,6 @@ app3.openapi(chatDataStreamRoute, async (c) => {
9651
9691
  dbClient: dbClient_default,
9652
9692
  credentialStores
9653
9693
  });
9654
- await defaultBatchProcessor.forceFlush();
9655
9694
  const lastUserMessage = body.messages.filter((m) => m.role === "user").slice(-1)[0];
9656
9695
  const userText = typeof lastUserMessage?.content === "string" ? lastUserMessage.content : lastUserMessage?.parts?.map((p) => p.text).join("") || "";
9657
9696
  logger22.info({ userText, lastUserMessage }, "userText");
@@ -10455,19 +10494,19 @@ function createExecutionHono(serverConfig, credentialStores) {
10455
10494
  setupOpenAPIRoutes(app6);
10456
10495
  app6.use("/tenants/*", async (_c, next) => {
10457
10496
  await next();
10458
- await defaultBatchProcessor.forceFlush();
10497
+ await flushBatchProcessor();
10459
10498
  });
10460
10499
  app6.use("/agents/*", async (_c, next) => {
10461
10500
  await next();
10462
- await defaultBatchProcessor.forceFlush();
10501
+ await flushBatchProcessor();
10463
10502
  });
10464
10503
  app6.use("/v1/*", async (_c, next) => {
10465
10504
  await next();
10466
- await defaultBatchProcessor.forceFlush();
10505
+ await flushBatchProcessor();
10467
10506
  });
10468
10507
  app6.use("/api/*", async (_c, next) => {
10469
10508
  await next();
10470
- await defaultBatchProcessor.forceFlush();
10509
+ await flushBatchProcessor();
10471
10510
  });
10472
10511
  const baseApp = new Hono();
10473
10512
  baseApp.route("/", app6);
@@ -9,12 +9,58 @@ var resources = require('@opentelemetry/resources');
9
9
  var sdkNode = require('@opentelemetry/sdk-node');
10
10
  var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
11
11
  var semanticConventions = require('@opentelemetry/semantic-conventions');
12
+ var agentsCore = require('@inkeep/agents-core');
13
+ var zod = require('zod');
12
14
 
13
15
  // src/instrumentation.ts
14
- var otlpExporter = new exporterTraceOtlpHttp.OTLPTraceExporter();
15
- var defaultBatchProcessor = new sdkTraceBase.BatchSpanProcessor(otlpExporter, {
16
- scheduledDelayMillis: 1e3
16
+ agentsCore.loadEnvironmentFiles();
17
+ var envSchema = zod.z.object({
18
+ NODE_ENV: zod.z.enum(["development", "production", "test"]).optional(),
19
+ ENVIRONMENT: zod.z.enum(["development", "production", "pentest", "test"]).optional().default("development"),
20
+ DB_FILE_NAME: zod.z.string().optional(),
21
+ TURSO_DATABASE_URL: zod.z.string().optional(),
22
+ TURSO_AUTH_TOKEN: zod.z.string().optional(),
23
+ AGENTS_RUN_API_URL: zod.z.string().optional().default("http://localhost:3003"),
24
+ LOG_LEVEL: zod.z.enum(["trace", "debug", "info", "warn", "error"]).optional().default("debug"),
25
+ NANGO_SECRET_KEY: zod.z.string().optional(),
26
+ OPENAI_API_KEY: zod.z.string().optional(),
27
+ ANTHROPIC_API_KEY: zod.z.string(),
28
+ INKEEP_AGENTS_RUN_API_BYPASS_SECRET: zod.z.string().optional(),
29
+ OTEL_BSP_SCHEDULE_DELAY: zod.z.coerce.number().optional().default(500),
30
+ OTEL_BSP_MAX_EXPORT_BATCH_SIZE: zod.z.coerce.number().optional().default(64)
17
31
  });
32
+ var parseEnv = () => {
33
+ try {
34
+ const parsedEnv = envSchema.parse(process.env);
35
+ return parsedEnv;
36
+ } catch (error) {
37
+ if (error instanceof zod.z.ZodError) {
38
+ const missingVars = error.issues.map((issue) => issue.path.join("."));
39
+ throw new Error(
40
+ `\u274C Invalid environment variables: ${missingVars.join(", ")}
41
+ ${error.message}`
42
+ );
43
+ }
44
+ throw error;
45
+ }
46
+ };
47
+ var env = parseEnv();
48
+
49
+ // src/instrumentation.ts
50
+ var otlpExporter = new exporterTraceOtlpHttp.OTLPTraceExporter();
51
+ var logger = agentsCore.getLogger("instrumentation");
52
+ function createSafeBatchProcessor() {
53
+ try {
54
+ return new sdkTraceBase.BatchSpanProcessor(otlpExporter, {
55
+ scheduledDelayMillis: env.OTEL_BSP_SCHEDULE_DELAY,
56
+ maxExportBatchSize: env.OTEL_BSP_MAX_EXPORT_BATCH_SIZE
57
+ });
58
+ } catch (error) {
59
+ logger.warn({ error }, "Failed to create batch processor");
60
+ return new sdkTraceBase.NoopSpanProcessor();
61
+ }
62
+ }
63
+ var defaultBatchProcessor = createSafeBatchProcessor();
18
64
  var defaultResource = resources.resourceFromAttributes({
19
65
  [semanticConventions.ATTR_SERVICE_NAME]: "inkeep-agents-run-api"
20
66
  });
@@ -55,6 +101,13 @@ var defaultSDK = new sdkNode.NodeSDK({
55
101
  spanProcessors: defaultSpanProcessors,
56
102
  instrumentations: defaultInstrumentations
57
103
  });
104
+ async function flushBatchProcessor() {
105
+ try {
106
+ await defaultBatchProcessor.forceFlush();
107
+ } catch (error) {
108
+ logger.warn({ error }, "Failed to flush batch processor");
109
+ }
110
+ }
58
111
 
59
112
  exports.defaultBatchProcessor = defaultBatchProcessor;
60
113
  exports.defaultContextManager = defaultContextManager;
@@ -63,3 +116,4 @@ exports.defaultResource = defaultResource;
63
116
  exports.defaultSDK = defaultSDK;
64
117
  exports.defaultSpanProcessors = defaultSpanProcessors;
65
118
  exports.defaultTextMapPropagator = defaultTextMapPropagator;
119
+ exports.flushBatchProcessor = flushBatchProcessor;
@@ -2,14 +2,15 @@ import * as _opentelemetry_resources from '@opentelemetry/resources';
2
2
  import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
3
3
  import { CompositePropagator } from '@opentelemetry/core';
4
4
  import { NodeSDKConfiguration, NodeSDK } from '@opentelemetry/sdk-node';
5
- import { BatchSpanProcessor, SpanProcessor } from '@opentelemetry/sdk-trace-base';
5
+ import { SpanProcessor } from '@opentelemetry/sdk-trace-base';
6
6
 
7
- declare const defaultBatchProcessor: BatchSpanProcessor;
7
+ declare const defaultBatchProcessor: SpanProcessor;
8
8
  declare const defaultResource: _opentelemetry_resources.Resource;
9
9
  declare const defaultInstrumentations: NonNullable<NodeSDKConfiguration['instrumentations']>;
10
10
  declare const defaultSpanProcessors: SpanProcessor[];
11
11
  declare const defaultContextManager: AsyncLocalStorageContextManager;
12
12
  declare const defaultTextMapPropagator: CompositePropagator;
13
13
  declare const defaultSDK: NodeSDK;
14
+ declare function flushBatchProcessor(): Promise<void>;
14
15
 
15
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator };
16
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor };
@@ -2,14 +2,15 @@ import * as _opentelemetry_resources from '@opentelemetry/resources';
2
2
  import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
3
3
  import { CompositePropagator } from '@opentelemetry/core';
4
4
  import { NodeSDKConfiguration, NodeSDK } from '@opentelemetry/sdk-node';
5
- import { BatchSpanProcessor, SpanProcessor } from '@opentelemetry/sdk-trace-base';
5
+ import { SpanProcessor } from '@opentelemetry/sdk-trace-base';
6
6
 
7
- declare const defaultBatchProcessor: BatchSpanProcessor;
7
+ declare const defaultBatchProcessor: SpanProcessor;
8
8
  declare const defaultResource: _opentelemetry_resources.Resource;
9
9
  declare const defaultInstrumentations: NonNullable<NodeSDKConfiguration['instrumentations']>;
10
10
  declare const defaultSpanProcessors: SpanProcessor[];
11
11
  declare const defaultContextManager: AsyncLocalStorageContextManager;
12
12
  declare const defaultTextMapPropagator: CompositePropagator;
13
13
  declare const defaultSDK: NodeSDK;
14
+ declare function flushBatchProcessor(): Promise<void>;
14
15
 
15
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator };
16
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor };
@@ -1 +1 @@
1
- export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator } from './chunk-Z76LOSTO.js';
1
+ export { defaultBatchProcessor, defaultContextManager, defaultInstrumentations, defaultResource, defaultSDK, defaultSpanProcessors, defaultTextMapPropagator, flushBatchProcessor } from './chunk-XO4RG36I.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inkeep/agents-run-api",
3
- "version": "0.14.2",
3
+ "version": "0.14.5",
4
4
  "description": "Agents Run API for Inkeep Agent Framework - handles chat, agent execution, and streaming",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -51,7 +51,7 @@
51
51
  "traverse": "^0.6.11",
52
52
  "ts-pattern": "^5.7.1",
53
53
  "zod": "^4.1.11",
54
- "@inkeep/agents-core": "^0.14.2"
54
+ "@inkeep/agents-core": "^0.14.5"
55
55
  },
56
56
  "optionalDependencies": {
57
57
  "keytar": "^7.9.0"
@@ -1 +0,0 @@
1
- export { dbClient_default as default } from './chunk-TWVQBIUL.js';