The Open Framework for Building Agents
Fail connection search when connections cannot load (#1066)
John Phamous49f2f1392ee3
diff --git a/.changeset/clear-connection-search-errors.md b/.changeset/clear-connection-search-errors.mdnew file mode 100644index 000000000..b36e74f52--- /dev/null+++ b/.changeset/clear-connection-search-errors.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Report `connection_search` as failed when every targeted connection fails to load, including authorization startup failures, so tool-call observability preserves the underlying error. Requests for unregistered connections now fail instead of returning an empty result.diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.tsindex 29dcb3c3f..80feaa0a9 100644--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.test.ts@@ -1,10 +1,258 @@import { describe, expect, it } from "vitest";-import { extractDiscoveredTools } from "#runtime/framework-tools/connection-search-dynamic.js";+import { ConnectionRegistryKey } from "#context/providers/connection-key.js";+import { ContextContainer, contextStorage } from "#context/container.js";+import { AuthKey, SessionIdKey } from "#context/keys.js";+import { CallbackBaseUrlKey, isAuthorizationSignal } from "#harness/authorization.js";+import { ConnectionAuthorizationRequiredError } from "#public/connections/errors.js";+import type { ToolContext } from "#public/definitions/tool.js";+import type { ConnectionRegistry, ConnectionToolMetadata } from "#runtime/connections/types.js";+import {+ createConnectionSearchEvents,+ extractDiscoveredTools,+} from "#runtime/framework-tools/connection-search-dynamic.js";+import type { ResolvedConnectionDefinition } from "#runtime/types.js";+import type { DynamicResolveContext, DynamicToolSet } from "#shared/dynamic-tool-definition.js";// eslint-disable-next-line @typescript-eslint/no-explicit-anytype Msg = any;+function connection(name: string): ResolvedConnectionDefinition {+ return {+ connectionName: name,+ description: `${name} connection`,+ logicalPath: `agent/connections/${name}.ts`,+ protocol: "mcp",+ sourceId: `connections/${name}`,+ sourceKind: "module",+ url: `https://${name}.example.com/mcp`,+ };+}++async function executeConnectionSearch(+ registry: ConnectionRegistry,+ input: { readonly connection?: string; readonly keywords: string; readonly limit?: number },+ setupContext?: (ctx: ContextContainer) => void,+): Promise<unknown> {+ const ctx = new ContextContainer();+ ctx.set(ConnectionRegistryKey, registry);+ setupContext?.(ctx);++ return contextStorage.run(ctx, async () => {+ const resolve = createConnectionSearchEvents()["step.started"]!;+ const resolved = (await resolve({}, {+ channel: {},+ messages: [],+ session: { auth: { current: null, initiator: null }, id: "test-session" },+ } satisfies DynamicResolveContext)) as DynamicToolSet;++ return resolved["connection_search"]!.execute(input, {} as ToolContext);+ });+}++function registry(input: {+ readonly connections: readonly ResolvedConnectionDefinition[];+ readonly loadTools: Readonly<Record<string, () => Promise<readonly ConnectionToolMetadata[]>>>;+}): ConnectionRegistry {+ return {+ dispose: async () => {},+ getClient: (name) => ({+ close: async () => {},+ connect: async () => {},+ executeTool: async () => {},+ getToolMetadata: input.loadTools[name]!,+ getTools: async () => ({}),+ }),+ getConnectionApproval: () => undefined,+ getConnectionNames: () => input.connections.map((item) => item.connectionName),+ getConnections: () => input.connections,+ };+}++describe("connection_search", () => {+ it("fails when every targeted connection fails to load", async () => {+ const incident = connection("incident");+ const connectionRegistry = registry({+ connections: [incident],+ loadTools: {+ incident: async () => {+ throw new Error("MCP SSE Transport Error: 400 Bad Request");+ },+ },+ });++ await expect(+ executeConnectionSearch(connectionRegistry, {+ connection: "incident",+ keywords: "list incidents",+ }),+ ).rejects.toThrow(+ 'Failed to load tools for "incident": MCP SSE Transport Error: 400 Bad Request',+ );+ });++ it("fails when the requested connection is not registered", async () => {+ const incident = connection("incident");+ const connectionRegistry = registry({+ connections: [incident],+ loadTools: { incident: async () => [] },+ });++ await expect(+ executeConnectionSearch(connectionRegistry, {+ connection: "incidents",+ keywords: "list incidents",+ }),+ ).rejects.toThrow('Connection "incidents" is not registered. Available connections: incident.');+ });++ it("fails when authorization cannot be started", async () => {+ const salesforce: ResolvedConnectionDefinition = {+ ...connection("salesforce"),+ authorization: {+ completeAuthorization: async () => ({ token: "unused" }),+ getToken: async () => {+ throw new ConnectionAuthorizationRequiredError("salesforce");+ },+ principalType: "user",+ startAuthorization: async () => {+ throw new Error("OAuth provider unavailable");+ },+ },+ };+ const connectionRegistry = registry({+ connections: [salesforce],+ loadTools: {+ salesforce: async () => {+ throw new ConnectionAuthorizationRequiredError("salesforce");+ },+ },+ });++ await expect(+ executeConnectionSearch(+ connectionRegistry,+ { connection: "salesforce", keywords: "accounts" },+ (ctx) => {+ ctx.set(SessionIdKey, "session-auth");+ ctx.set(CallbackBaseUrlKey, "https://agent.example.com");+ ctx.set(AuthKey, {+ attributes: {},+ authenticator: "test-idp",+ issuer: "test-idp",+ principalId: "user-1",+ principalType: "user",+ });+ },+ ),+ ).rejects.toThrow('Failed to start authorization for "salesforce": OAuth provider unavailable');+ });++ it("returns connection summaries when loading succeeds without a keyword match", async () => {+ const incident = connection("incident");+ const connectionRegistry = registry({+ connections: [incident],+ loadTools: { incident: async () => [] },+ });++ await expect(+ executeConnectionSearch(connectionRegistry, { keywords: "list incidents" }),+ ).resolves.toEqual([+ {+ connection: "incident",+ description: "incident connection",+ },+ ]);+ });++ it("returns matches and errors when at least one connection loads", async () => {+ const incident = connection("incident");+ const linear = connection("linear");+ const connectionRegistry = registry({+ connections: [incident, linear],+ loadTools: {+ incident: async () => {+ throw new Error("MCP SSE Transport Error: 400 Bad Request");+ },+ linear: async () => [+ {+ description: "List issues",+ inputSchema: { type: "object" },+ name: "list_issues",+ },+ ],+ },+ });++ await expect(+ executeConnectionSearch(connectionRegistry, { keywords: "list issues" }),+ ).resolves.toEqual([+ {+ connection: "linear",+ description: "List issues",+ inputSchema: { type: "object" },+ outputSchema: undefined,+ qualifiedName: "linear__list_issues",+ tool: "list_issues",+ },+ {+ connection: "incident",+ description: "incident connection",+ error: 'Failed to load tools for "incident": MCP SSE Transport Error: 400 Bad Request',+ },+ ]);+ });++ it("returns an authorization signal when sign-in can be started", async () => {+ const salesforce: ResolvedConnectionDefinition = {+ ...connection("salesforce"),+ authorization: {+ completeAuthorization: async () => ({ token: "unused" }),+ getToken: async () => {+ throw new ConnectionAuthorizationRequiredError("salesforce");+ },+ principalType: "user",+ startAuthorization: async () => ({+ challenge: { url: "https://idp.example.com/authorize" },+ }),+ },+ };+ const connectionRegistry = registry({+ connections: [salesforce],+ loadTools: {+ salesforce: async () => {+ throw new ConnectionAuthorizationRequiredError("salesforce");+ },+ },+ });++ const result = await executeConnectionSearch(+ connectionRegistry,+ { connection: "salesforce", keywords: "accounts" },+ (ctx) => {+ ctx.set(SessionIdKey, "session-auth");+ ctx.set(CallbackBaseUrlKey, "https://agent.example.com");+ ctx.set(AuthKey, {+ attributes: {},+ authenticator: "test-idp",+ issuer: "test-idp",+ principalId: "user-1",+ principalType: "user",+ });+ },+ );++ expect(isAuthorizationSignal(result)).toBe(true);+ if (!isAuthorizationSignal(result)) throw new Error("expected authorization signal");+ expect(result.challenges).toMatchObject([+ {+ name: "salesforce",+ challenge: { url: "https://idp.example.com/authorize" },+ },+ ]);+ });+});+describe("extractDiscoveredTools", () => {it("extracts tools from raw array output", () => {const messages: Msg[] = [diff --git a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.tsindex 682f12f71..bec57afdb 100644--- a/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts+++ b/packages/eve/src/runtime/framework-tools/connection-search-dynamic.ts@@ -32,6 +32,7 @@ import {import type { ResolvedDynamicToolResolver } from "#runtime/types.js";import { createLogger } from "#internal/logging.js";import type { DynamicToolEvents, DynamicToolEntry } from "#shared/dynamic-tool-definition.js";+import { toError } from "#shared/errors.js";import type { ModelMessage } from "ai";import { ConnectionRegistryKey } from "#context/providers/connection-key.js";@@ -191,6 +192,12 @@ async function executeConnectionSearch(? registry.getConnections().filter((c) => c.connectionName === input.connection): registry.getConnections();+ if (input.connection && targetConnections.length === 0) {+ throw new Error(+ `Connection "${input.connection}" is not registered. Available connections: ${registry.getConnectionNames().join(", ")}.`,+ );+ }+const authChallenges: AuthorizationChallenge[] = [];for (const conn of targetConnections) {@@ -238,10 +245,17 @@ async function executeConnectionSearch(resume,});} catch (startErr) {+ const error = toError(startErr);logger.warn("startAuthorization failed", {connection: conn.connectionName,- error: startErr instanceof Error ? startErr : new Error(String(startErr)),+ error,+ });+ failedConnections.push({+ connection: conn.connectionName,+ description: conn.description,+ error: `Failed to start authorization for "${conn.connectionName}": ${error.message}`,});+ continue;}}}@@ -268,15 +282,15 @@ async function executeConnectionSearch(continue;}- const message = err instanceof Error ? err.message : "unknown error";+ const error = toError(err);logger.warn("failed to load connection tools", {connection: conn.connectionName,- error: err instanceof Error ? err : new Error(message),+ error,});failedConnections.push({connection: conn.connectionName,description: conn.description,- error: `Failed to load tools for "${conn.connectionName}": ${message}`,+ error: `Failed to load tools for "${conn.connectionName}": ${error.message}`,});continue;}@@ -303,6 +317,14 @@ async function executeConnectionSearch(return requestAuthorization(authChallenges);}+ const terminalFailures = failedConnections.filter((failure) => failure.error !== undefined);+ if (targetConnections.length > 0 && terminalFailures.length === targetConnections.length) {+ // When every targeted connection reaches a terminal error, connection_search itself fails.+ // AI SDK catches this rejection, emits a tool-error result, and preserves the failed call in+ // agent-run observability. Partial failures stay in the successful result so usable tools remain discoverable.+ throw new Error(terminalFailures.map((failure) => failure.error).join("\n"));+ }+results.sort((a, b) => b.score - a.score);const matched = results.slice(0, limit).map((r) => r.item);