Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): ask for MCP sign-in only when the server requires it (#4415)

Ruic230e94e54d6
diff --git a/.changeset/mcp-sign-in-when-asked.md b/.changeset/mcp-sign-in-when-asked.md
new file mode 100644
index 000000000..9191873f0
--- /dev/null
+++ b/.changeset/mcp-sign-in-when-asked.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+MCP connections now ask the user to sign in only when the server asks for it. When a connection has `auth` but no token yet, eve connects without an `Authorization` header, so servers that allow anonymous `initialize` and `tools/list` have their tools listed by `connection_search` and run by `connection_execute` with no prompt. Sign-in starts when a call returns HTTP `401` or an error result with a `_meta["mcp/www_authenticate"]` challenge, and the call runs again with the token once the user signs in. Servers that reject every request without a token behave as before, and connections that already have a token are unchanged.
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index dc1c5cd22..6c467ba25 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -298,9 +298,9 @@ export default disableTool();
`connection_search` and `connection_execute` give the model every tool from the agent's [connections](../connections) without adding each tool to the model's tool list. eve adds both when the agent has a static connection or a dynamic connection resolver, even when `defaultTools` is `false`, so there is no add command.
-- `connection_search({ query?, connection?, signIn?, limit?, offset? })` returns matching tools with their connection, name, description, and a TypeScript signature rendered from the tool's schemas. Omit `query` to list every tool, or pair it with `connection` to list one connection's tools. A plain search never asks the user to sign in. For a connection the user has not signed in to, the result tells the model that sign-in is needed before its tools can be listed: the connection appears under `unavailable` with `requiresSignIn: true` and an error that points to `signIn: true`. Tools from the other connections are still returned.
+- `connection_search({ query?, connection?, signIn?, limit?, offset? })` returns matching tools with their connection, name, description, and a TypeScript signature rendered from the tool's schemas. Omit `query` to list every tool, or pair it with `connection` to list one connection's tools. A plain search never asks the user to sign in. For a connection whose server will not list its tools until the user signs in, the result tells the model that sign-in is needed: the connection appears under `unavailable` with `requiresSignIn: true` and an error that points to `signIn: true`. Tools from the other connections are still returned.
- `connection_search({ connection, signIn: true, query? })` asks the user to sign in to that one connection when they have not yet, then returns its matching tools. Without `connection` it fails, so the user is asked about one service at a time.
-- `connection_execute({ connection, tool, input })` checks `input` against the tool's input schema, calls the tool, and returns its result. When the connection needs the user's authorization, it also asks the user to sign in and the call parks until sign-in completes. The stream reports the call as a nested action named `<connection>__<tool>`, such as `linear__list_issues`, whose `parentCallId` is the `connection_execute` call id.
+- `connection_execute({ connection, tool, input })` checks `input` against the tool's input schema, calls the tool, and returns its result. When the server asks for the user's authorization, it also asks the user to sign in and the call parks until sign-in completes. The stream reports the call as a nested action named `<connection>__<tool>`, such as `linear__list_issues`, whose `parentCallId` is the `connection_execute` call id.
The definitions of both tools never change during a session. eve lists connection names and descriptions in append-only context messages rather than in the system prompt, so finding a tool, signing in, or resolving a dynamic connection keeps the cached prompt prefix.
diff --git a/docs/connections/mcp.mdx b/docs/connections/mcp.mdx
index 6d4420ad0..1c6e40df0 100644
--- a/docs/connections/mcp.mdx
+++ b/docs/connections/mcp.mdx
@@ -44,6 +44,17 @@ For OAuth-backed MCP servers, use the shared [Vercel Connect flow](../connection
`connect("...")` is user-scoped by default and requires an authenticated user on the active eve session. Use `connect({ connector, principalType: "app" })` when the server should act as the agent instead. The connections overview covers connector setup, session requirements, app and user scope, callback behavior, and troubleshooting.
+## When eve asks for sign-in
+
+eve asks the user to sign in only when the MCP server asks for it. When a connection has `auth` but no token yet, because its `getToken` throws `ConnectionAuthorizationRequiredError`, eve connects without an `Authorization` header and lists the server's tools. Any other error from `getToken` still fails the connection.
+
+- **The server rejects every request without a token.** Most hosted OAuth servers, such as Linear, GitHub, and Notion, answer `initialize` or `tools/list` with HTTP `401`. A plain `connection_search` lists the connection under `unavailable` with `requiresSignIn: true`. Calling `connection_search({ connection, signIn: true })` or any of its tools with `connection_execute` asks the user to sign in.
+- **The server lists tools without a token.** `connection_search` returns its tools with no prompt, and `connection_execute` runs tools the server answers anonymously. Sign-in starts only when a tool call comes back with HTTP `401`, or with an error result that carries a `WWW-Authenticate` challenge in `_meta["mcp/www_authenticate"]`.
+
+After the user signs in, the call that asked for it runs again. eve reconnects with the token and reloads the tool list, which may now include tools the server hides from anonymous callers. A connection that already has a token sends it on every request, as before.
+
+A server that leaves protected tools out of its anonymous `tools/list` never triggers sign-in, because the model cannot find those tools. Servers that support anonymous use should list every tool and refuse the protected calls.
+
## Static tokens and headers
MCP connections accept the shared connection `auth` and `headers` options. Use `auth.getToken` for a bearer token, `headers` for another scheme, and resolver functions when credentials or routing depend on the caller. See [Static-token auth](../connections#static-token-auth), [Headers](../connections#headers), and [Per-caller auth and headers](../connections#per-caller-auth-and-headers) for the canonical examples and token-lifecycle behavior.
diff --git a/docs/connections/overview.mdx b/docs/connections/overview.mdx
index 6e55fe896..bf792213c 100644
--- a/docs/connections/overview.mdx
+++ b/docs/connections/overview.mdx
@@ -227,7 +227,7 @@ export default defineMcpClientConnection({
Use the connector UID returned by `vercel connect create`; the display name passed to `--name` is not the UID. `connect("linear/myagent")` is shorthand for a user-scoped interactive OAuth connection: eve resolves a token for the active user before each tool call, emits `authorization.required` when that user has not authorized yet, and resumes the parked turn after the callback completes.
-Discovering tools never posts a sign-in prompt for a service the answer does not need. A plain `connection_search` lists connections the user has not authorized yet under `unavailable` with `requiresSignIn: true`. Most OAuth MCP servers reject even tool listing without the user's token, so the model asks for sign-in explicitly, one connection at a time, with `connection_search({ connection, signIn: true })`, which returns that connection's tools once the user signs in. Calling a tool with `connection_execute` on a connection the user has not authorized also asks for sign-in.
+Discovering tools never posts a sign-in prompt for a service the answer does not need. Before the user signs in, eve connects to an MCP server without a token, so a server that lists its tools anonymously is searched like any other connection, and sign-in starts only when one of its tools asks for it (see [When eve asks for sign-in](/docs/connections/mcp#when-eve-asks-for-sign-in)). Most OAuth MCP servers reject even tool listing without the user's token. A plain `connection_search` lists those connections under `unavailable` with `requiresSignIn: true`, and the model asks for sign-in explicitly, one connection at a time, with `connection_search({ connection, signIn: true })`, which returns that connection's tools once the user signs in. Calling a tool with `connection_execute` on such a connection also asks for sign-in.
A sign-in holds the turn open until the user connects, the turn is cancelled, or the user sends another message. That message steers the turn: eve cancels the sign-in, reports `authorization.completed` with `outcome: "declined"`, and the model reads the message next. Messages from other people in a shared thread wait until the turn ends, and the completed sign-in resumes the turn as the person who started it.
diff --git a/e2e/fixtures/agent-workflow-tools/agent/agent.ts b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
index 3eb04f559..06ac109e6 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/agent.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/agent.ts
@@ -17,6 +17,27 @@ const HOOK_SCENARIO_CALLS = {
waiting: { name: "blocking_agent", input: { service: "hook-audit" } },
} as const;
+/**
+ * public-catalog lists its tools without sign-in: run its public tool, then its
+ * protected one, which asks the user to sign in and resumes once they have.
+ */
+function respondToPublicCatalog(request: MockModelRequest): MockModelResponse | string {
+ const call = (id: string, tool: string) => ({
+ id,
+ name: "connection_execute",
+ input: { connection: "public-catalog", tool, input: {} },
+ });
+ const byId = new Map(request.toolResults.map((entry) => [entry.id, entry]));
+ if (!byId.has("public-catalog-items")) {
+ return { toolCalls: [call("public-catalog-items", "list_items")] };
+ }
+ const orders = byId.get("public-catalog-orders");
+ if (orders === undefined) {
+ return { toolCalls: [call("public-catalog-orders", "list_orders")] };
+ }
+ return `PUBLIC_CATALOG_DONE ${JSON.stringify(orders.output)}`;
+}
+
/**
* Deterministic script: each directive names the workflow tool to call with
* service "api"; once the turn holds a tool result the reply echoes it.
@@ -62,6 +83,9 @@ async function respond(request: MockModelRequest): Promise<MockModelResponse | s
return typeof call.output === "string" ? call.output : JSON.stringify(call.output);
}
+ if (request.userMessages.some((entry) => entry.startsWith("PUBLIC-CATALOG-E2E"))) {
+ return respondToPublicCatalog(request);
+ }
const message =
[...request.userMessages]
.reverse()
diff --git a/e2e/fixtures/agent-workflow-tools/agent/channels/catalog.ts b/e2e/fixtures/agent-workflow-tools/agent/channels/catalog.ts
index cc0635f8f..9de1b8997 100644
--- a/e2e/fixtures/agent-workflow-tools/agent/channels/catalog.ts
+++ b/e2e/fixtures/agent-workflow-tools/agent/channels/catalog.ts
@@ -6,9 +6,68 @@ const rpcRequest = z.object({
method: z.string(),
});
+const rpcCall = rpcRequest.extend({
+ params: z.object({ name: z.string().optional() }).optional(),
+});
+
+const rpcReply = (id: string | number, result: unknown) =>
+ Response.json({ jsonrpc: "2.0", id, result });
+
+const textResult = (value: unknown) => ({
+ content: [{ type: "text", text: JSON.stringify(value) }],
+});
+
+/**
+ * A server that, like a catalog with a public storefront, answers `initialize`,
+ * `tools/list`, and `list_items` without a token. Only `list_orders` needs
+ * sign-in, and it answers `401` until the request carries the bearer.
+ */
+async function publicCatalog(request: Request): Promise<Response> {
+ const signedIn = request.headers.get("authorization") === "Bearer authorized-fixture-token";
+ const { id, method, params } = rpcCall.parse(await request.json());
+ if (id === undefined) return new Response(null, { status: 202 });
+ switch (method) {
+ case "initialize":
+ return rpcReply(id, {
+ protocolVersion: "2025-03-26",
+ capabilities: { tools: {} },
+ serverInfo: { name: "fixture-public-catalog", version: "1.0.0" },
+ });
+ case "tools/list":
+ return rpcReply(id, {
+ tools: [
+ {
+ name: "list_items",
+ description: "List catalog items. Public.",
+ inputSchema: { type: "object", properties: {} },
+ },
+ {
+ name: "list_orders",
+ description: "List the signed-in user's orders.",
+ inputSchema: { type: "object", properties: {} },
+ },
+ ],
+ });
+ case "tools/call":
+ if (params?.name === "list_items") return rpcReply(id, textResult({ items: ["Lamp"] }));
+ if (params?.name === "list_orders") {
+ if (!signedIn) return new Response("Unauthorized", { status: 401 });
+ return rpcReply(id, textResult({ orders: ["Alice's lamp"], signedIn }));
+ }
+ break;
+ }
+ return Response.json({
+ jsonrpc: "2.0",
+ id,
+ error: { code: -32601, message: "Method not found" },
+ });
+}
+
// A fixture-owned MCP server: eve still resolves auth and performs real HTTP discovery.
export default defineChannel({
routes: [
+ GET("/fixture-public-catalog/mcp", async () => new Response(null, { status: 405 })),
+ POST("/fixture-public-catalog/mcp", publicCatalog),
GET("/fixture-catalog/mcp", async () => new Response(null, { status: 405 })),
POST("/fixture-catalog/mcp", async (request) => {
if (request.headers.get("authorization") !== "Bearer authorized-fixture-token") {
diff --git a/e2e/fixtures/agent-workflow-tools/agent/connections/public-catalog.ts b/e2e/fixtures/agent-workflow-tools/agent/connections/public-catalog.ts
new file mode 100644
index 000000000..863e1ac3c
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/agent/connections/public-catalog.ts
@@ -0,0 +1,16 @@
+import { defineDynamic, defineMcpClientConnection } from "eve/connections";
+
+import { createFakeAuthProvider } from "../lib/fake-auth-provider.ts";
+import { fixtureUrl } from "../lib/fake-service.ts";
+
+export default defineDynamic({
+ events: {
+ "session.started": () =>
+ defineMcpClientConnection({
+ description: "Public catalog: lists items without sign-in; orders need sign-in.",
+ url: fixtureUrl("/fixture-public-catalog/mcp").href,
+ instanceKey: "fixture-public-catalog",
+ auth: createFakeAuthProvider({ expiredToken: false, rememberSignIns: true }),
+ }),
+ },
+});
diff --git a/e2e/fixtures/agent-workflow-tools/evals/connection-tools.lazy-authorization.eval.ts b/e2e/fixtures/agent-workflow-tools/evals/connection-tools.lazy-authorization.eval.ts
new file mode 100644
index 000000000..75ab0ccf3
--- /dev/null
+++ b/e2e/fixtures/agent-workflow-tools/evals/connection-tools.lazy-authorization.eval.ts
@@ -0,0 +1,75 @@
+import { defineEval } from "eve/evals";
+
+import { fixtureAuthorizationCallback } from "../agent/lib/fake-service.ts";
+
+const mentions = (text: string) => (value: unknown) => JSON.stringify(value).includes(text);
+
+export default defineEval({
+ description:
+ "An MCP server that lists its tools without a token runs its public tool with no sign-in; its protected tool asks the user to sign in, then resumes over authenticated HTTP.",
+ timeoutMs: 90_000,
+
+ async test(t) {
+ if (process.env.EVE_E2E_MODEL !== "mock") {
+ t.skip("Requires the deterministic mock model to issue the exact calls.");
+ }
+
+ // A fresh principal per run: the fixture provider remembers each user's token.
+ const alice = { "x-eve-forwarded-principal-id": `public-catalog-alice-${crypto.randomUUID()}` };
+ const started = await t.send(
+ "PUBLIC-CATALOG-E2E Alice wants her public-catalog items and orders.",
+ {
+ headers: alice,
+ },
+ );
+ const session = started.session;
+ started.expectOk();
+ // The public tool runs before anyone signs in.
+ started.calledTool("connection_execute", {
+ count: 1,
+ status: "completed",
+ input: { connection: "public-catalog", tool: "list_items" },
+ output: mentions("Lamp"),
+ });
+ // Only the protected tool asks for sign-in, and the turn holds on it.
+ started.event("authorization.required", { count: 1 });
+ started.notEvent("authorization.completed");
+ started.event("turn.waiting", { count: 1 });
+ started.notEvent("session.waiting");
+
+ const required = started.events.find((event) => event.type === "authorization.required");
+ if (required?.type !== "authorization.required") {
+ throw new Error("The protected tool did not produce an authorization challenge.");
+ }
+ const callback = fixtureAuthorizationCallback(t.target.url, required.data.authorization?.url);
+ if (session.sessionId === undefined || session.state === undefined) {
+ throw new Error("The turn did not create a session.");
+ }
+
+ const resumed = t.target.watchTurn(session.sessionId, {
+ startIndex: session.state.streamIndex,
+ });
+ const response = await fetch(callback);
+ if (!response.ok) {
+ throw new Error(`Authorization callback failed (${response.status}).`);
+ }
+
+ const completed = await resumed.result();
+ completed.expectOk();
+ completed.notEvent("turn.started");
+ completed.noFailedActions();
+ completed.notEvent("authorization.required");
+ completed.event("authorization.completed", {
+ count: 1,
+ data: { candidateId: required.data.candidateId, outcome: "authorized" },
+ });
+ // The server answers list_orders only when the request carries the bearer.
+ completed.calledTool("connection_execute", {
+ count: 1,
+ input: { connection: "public-catalog", tool: "list_orders" },
+ output: mentions('"signedIn":true'),
+ });
+ completed.messageIncludes("PUBLIC_CATALOG_DONE");
+ completed.messageIncludes("Alice's lamp");
+ },
+});
diff --git a/packages/eve/src/execution/tools/connection-tools.lazy-auth.test.ts b/packages/eve/src/execution/tools/connection-tools.lazy-auth.test.ts
new file mode 100644
index 000000000..54ddaf4ec
--- /dev/null
+++ b/packages/eve/src/execution/tools/connection-tools.lazy-auth.test.ts
@@ -0,0 +1,241 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { AuthKey, SessionIdKey } from "#context/keys.js";
+import { ConnectionRegistryKey } from "#context/providers/connection-key.js";
+import {
+ CallbackBaseUrlKey,
+ isAuthorizationSignal,
+ PendingAuthorizationResultKey,
+} from "#harness/authorization.js";
+import { McpConnectionClient } from "#runtime/connections/mcp-client.js";
+import type { ConnectionRegistry } from "#runtime/connections/registry-types.js";
+import type { ResolvedConnectionDefinition } from "#runtime/types.js";
+import { type ConnectionClient, defineInteractiveAuthorization } from "#shared/connection-types.js";
+
+import { CONNECTION_EXECUTE_TOOL_NAME } from "./connection-target.js";
+import { CONNECTION_SEARCH_TOOL_NAME, resolveConnectionTools } from "./connection-tools.js";
+
+const URL = "https://kennel.example.com/mcp";
+const TOKEN = "signed-in-token";
+
+/** How the fake server treats requests that carry no bearer. */
+type ServerMode =
+ /** `initialize`/`tools/list` are public; a protected `tools/call` answers HTTP 401. */
+ | "public-list-401"
+ /** `initialize`/`tools/list` are public; a protected `tools/call` returns an `mcp/www_authenticate` error. */
+ | "public-list-meta"
+ /** Every request without a bearer answers HTTP 401. */
+ | "token-everywhere";
+
+interface SeenRequest {
+ readonly authorization: string | null;
+ readonly method: string;
+ readonly tool?: string;
+}
+
+function setup(mode: ServerMode) {
+ const seen: SeenRequest[] = [];
+ vi.stubGlobal("fetch", async (input: string | globalThis.URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ if (request.method !== "POST") return new Response(null, { status: 405 });
+ const authorization = request.headers.get("authorization");
+ const message = (await request.json()) as {
+ id?: number;
+ method: string;
+ params?: { name?: string };
+ };
+ seen.push({ authorization, method: message.method, tool: message.params?.name });
+ const signedIn = authorization === `Bearer ${TOKEN}`;
+ if (!signedIn && mode === "token-everywhere") {
+ return new Response("Unauthorized", { status: 401 });
+ }
+ if (message.id === undefined) return new Response(null, { status: 202 });
+ const reply = (result: unknown) => Response.json({ jsonrpc: "2.0", id: message.id, result });
+ switch (message.method) {
+ case "initialize":
+ return reply({
+ capabilities: { tools: {} },
+ protocolVersion: "2025-06-18",
+ serverInfo: { name: "kennel", version: "1.0.0" },
+ });
+ case "tools/list":
+ return reply({
+ tools: [
+ { name: "find_pet", description: "Find a pet.", inputSchema: { type: "object" } },
+ { name: "pet_invoice", description: "A pet's bill.", inputSchema: { type: "object" } },
+ ],
+ });
+ case "tools/call": {
+ if (message.params?.name === "pet_invoice" && !signedIn) {
+ if (mode === "public-list-401") return new Response("Unauthorized", { status: 401 });
+ return reply({
+ _meta: { "mcp/www_authenticate": [`Bearer resource_metadata="${URL}/.well-known"`] },
+ content: [{ type: "text", text: "Sign in to see invoices." }],
+ isError: true,
+ });
+ }
+ return reply({ content: [{ type: "text", text: `${message.params?.name} ok` }] });
+ }
+ default:
+ return Response.json({
+ jsonrpc: "2.0",
+ id: message.id,
+ error: { code: -32601, message: "Method not found" },
+ });
+ }
+ });
+
+ let token: string | undefined;
+ const startAuthorization = vi.fn(async ({ callbackUrl }: { callbackUrl: string }) => ({
+ challenge: { url: `https://idp.example.com/authorize?redirect=${callbackUrl}` },
+ }));
+ const authorization = defineInteractiveAuthorization({
+ getToken: async () => {
+ if (token === undefined) throw new ConnectionAuthorizationRequiredError("kennel");
+ return { token };
+ },
+ startAuthorization,
+ completeAuthorization: async () => {
+ token = TOKEN;
+ return { token };
+ },
+ });
+ const connection = {
+ authorization,
+ connectionName: "kennel",
+ description: "Kennel",
+ protocol: "mcp",
+ protocolVersionDiscovery: false,
+ url: URL,
+ } as ResolvedConnectionDefinition;
+
+ const clients = new Map<string, ConnectionClient>();
+ const registry: ConnectionRegistry = {
+ dispose: async () => {
+ await Promise.all([...clients.values()].map((client) => client.close()));
+ },
+ getClient: (name) => {
+ let client = clients.get(name);
+ if (client === undefined) {
+ client = new McpConnectionClient(connection);
+ clients.set(name, client);
+ }
+ return client;
+ },
+ getConnectionApproval: () => undefined,
+ getConnectionNames: () => ["kennel"],
+ getConnections: () => [connection],
+ };
+
+ const ctx = new ContextContainer();
+ ctx.set(AuthKey, {
+ attributes: {},
+ authenticator: "test",
+ principalId: "alice",
+ principalType: "user",
+ });
+ ctx.set(SessionIdKey, "lazy-auth");
+ ctx.set(CallbackBaseUrlKey, "https://agent.example.com");
+ ctx.set(ConnectionRegistryKey, registry);
+
+ async function call(toolName: string, input: unknown): Promise<unknown> {
+ return await contextStorage.run(ctx, async () => {
+ const execute = resolveConnectionTools()?.[toolName]?.execute;
+ if (execute === undefined) throw new Error(`${toolName} is not defined.`);
+ return await execute(input, { callId: "call-1", messages: [] } as never);
+ });
+ }
+
+ /** Simulates the user finishing sign-in: the callback result arrives for the next step. */
+ function completeSignIn() {
+ ctx.set(PendingAuthorizationResultKey, [
+ {
+ callback: { method: "GET", params: { code: "ok" } },
+ hookUrl: "https://agent.example.com/callback",
+ name: "kennel",
+ },
+ ]);
+ }
+
+ return { call, completeSignIn, registry, seen, startAuthorization };
+}
+
+describe("MCP connections sign in only when the server asks", () => {
+ let registry: ConnectionRegistry | undefined;
+
+ beforeEach(() => {
+ registry = undefined;
+ });
+
+ afterEach(async () => {
+ await registry?.dispose();
+ vi.unstubAllGlobals();
+ });
+
+ it("lists a public server's tools without a token or a sign-in prompt", async () => {
+ const env = setup("public-list-401");
+ registry = env.registry;
+
+ const result = await env.call(CONNECTION_SEARCH_TOOL_NAME, { connection: "kennel" });
+
+ expect(result).toMatchObject({
+ tools: [{ tool: "find_pet" }, { tool: "pet_invoice" }],
+ total: 2,
+ });
+ expect(result).not.toHaveProperty("unavailable");
+ expect(env.startAuthorization).not.toHaveBeenCalled();
+ expect(env.seen.every((request) => request.authorization === null)).toBe(true);
+ });
+
+ it.each(["public-list-401", "public-list-meta"] as const)(
+ "%s: runs a public tool anonymously, then prompts on a protected tool and resumes with the token",
+ async (mode) => {
+ const env = setup(mode);
+ registry = env.registry;
+
+ await expect(
+ env.call(CONNECTION_EXECUTE_TOOL_NAME, { connection: "kennel", tool: "find_pet" }),
+ ).resolves.toBe("find_pet ok");
+ expect(env.startAuthorization).not.toHaveBeenCalled();
+
+ const signal = await env.call(CONNECTION_EXECUTE_TOOL_NAME, {
+ connection: "kennel",
+ tool: "pet_invoice",
+ });
+ expect(isAuthorizationSignal(signal)).toBe(true);
+ expect(signal).toMatchObject({ challenges: [{ name: "kennel" }] });
+ expect(env.startAuthorization).toHaveBeenCalledOnce();
+
+ env.completeSignIn();
+ const seenBefore = env.seen.length;
+ await expect(
+ env.call(CONNECTION_EXECUTE_TOOL_NAME, { connection: "kennel", tool: "pet_invoice" }),
+ ).resolves.toBe("pet_invoice ok");
+ const resumed = env.seen.slice(seenBefore);
+ expect(resumed.map((request) => request.method)).toContain("initialize");
+ expect(resumed.every((request) => request.authorization === `Bearer ${TOKEN}`)).toBe(true);
+ expect(env.startAuthorization).toHaveBeenCalledOnce();
+ },
+ );
+
+ it("keeps reporting requiresSignIn for servers that reject every anonymous request", async () => {
+ const env = setup("token-everywhere");
+ registry = env.registry;
+
+ const result = await env.call(CONNECTION_SEARCH_TOOL_NAME, { connection: "kennel" });
+
+ expect(result).toMatchObject({
+ tools: [],
+ unavailable: [{ connection: "kennel", requiresSignIn: true }],
+ });
+ expect(env.startAuthorization).not.toHaveBeenCalled();
+
+ const signal = await env.call(CONNECTION_EXECUTE_TOOL_NAME, {
+ connection: "kennel",
+ tool: "find_pet",
+ });
+ expect(signal).toMatchObject({ challenges: [{ name: "kennel" }] });
+ });
+});
diff --git a/packages/eve/src/execution/tools/connection-tools.ts b/packages/eve/src/execution/tools/connection-tools.ts
index 9ccea013a..041f72cd5 100644
--- a/packages/eve/src/execution/tools/connection-tools.ts
+++ b/packages/eve/src/execution/tools/connection-tools.ts
@@ -354,6 +354,8 @@ async function executeConnectionTool(
const auth = createAuthorizationExecution();
if (scoped !== undefined) await auth.complete(scoped);
const client = registry.getClient(connection.connectionName);
+ // A client that connected anonymously before sign-in must reconnect with the new token.
+ if (scoped !== undefined && auth.isJustAuthorized(scoped)) await client.close();
let tools: readonly ConnectionToolMetadata[];
try {
@@ -467,7 +469,10 @@ async function completePendingAuthorizations(
for (const connection of connections) {
if (!results.some((result) => result.name === connection.connectionName)) continue;
const scoped = await resolveInteractiveAuthorization(registry, connection.connectionName);
- if (scoped !== undefined) await auth.complete(scoped);
+ if (scoped === undefined) continue;
+ await auth.complete(scoped);
+ // A client that connected anonymously before sign-in must reconnect with the new token.
+ if (auth.isJustAuthorized(scoped)) await registry.getClient(connection.connectionName).close();
}
}
diff --git a/packages/eve/src/runtime/connections/mcp-client.test.ts b/packages/eve/src/runtime/connections/mcp-client.test.ts
index 2a597329d..9703439ac 100644
--- a/packages/eve/src/runtime/connections/mcp-client.test.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { contextStorage, ContextContainer } from "#context/container.js";
import { AuthKey, SessionKey, type SessionAuthContext } from "#context/keys.js";
import {
+ ConnectionAuthorizationRequiredError,
isConnectionAuthorizationFailedError,
isConnectionAuthorizationRequiredError,
} from "#connections/errors.js";
@@ -10,6 +11,7 @@ import type { SessionContext } from "#context/session-context.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { ConnectionAuthorizationTokensKey } from "#runtime/connections/authorization-tokens.js";
import {
+ isMcpAuthChallengeResult,
isMcpAuthRequiredError,
McpConnectionClient,
passesToolFilter,
@@ -463,6 +465,206 @@ describe("McpConnectionClient authorization recovery", () => {
});
});
+describe("McpConnectionClient without a token yet", () => {
+ beforeEach(() => {
+ createMCPClient.mockReset();
+ });
+
+ function unauthorized() {
+ return Object.assign(new Error("MCP HTTP Transport Error: POSTing to endpoint (HTTP 401)"), {
+ statusCode: 401,
+ });
+ }
+
+ /** An authorization that has no token until `signIn()` is called. */
+ function pendingSignIn() {
+ let token: string | undefined;
+ const evict = vi.fn();
+ const getToken = vi.fn(async () => {
+ if (token === undefined) throw new ConnectionAuthorizationRequiredError("test");
+ return { token };
+ });
+ return {
+ authorization: { evict, getToken, principalType: "app" as const },
+ evict,
+ getToken,
+ signIn: (value: string) => {
+ token = value;
+ },
+ };
+ }
+
+ function fakeServer(callTool: (name: string) => unknown) {
+ const close = vi.fn();
+ createMCPClient.mockImplementation(async () => ({
+ close,
+ listTools: vi.fn().mockResolvedValue({
+ tools: [
+ { name: "public_tool", description: "", inputSchema: {} },
+ { name: "protected_tool", description: "", inputSchema: {} },
+ ],
+ }),
+ toolsFromDefinitions: vi.fn(({ tools }: { tools: { name: string }[] }) =>
+ Object.fromEntries(
+ tools.map((tool) => [tool.name, { execute: vi.fn(async () => callTool(tool.name)) }]),
+ ),
+ ),
+ }));
+ return { close };
+ }
+
+ function sentHeaders(call: number): Record<string, string> {
+ return createMCPClient.mock.calls[call]?.[0].transport.headers;
+ }
+
+ it("connects without an Authorization header and lists tools", async () => {
+ const auth = pendingSignIn();
+ fakeServer(() => ({ content: [] }));
+ const client = new McpConnectionClient(
+ makeConnection({ authorization: auth.authorization, headers: { "X-Workspace": "w" } }),
+ );
+
+ const tools = await client.getToolMetadata();
+
+ expect(tools.map((tool) => tool.name)).toEqual(["public_tool", "protected_tool"]);
+ expect(sentHeaders(0)).toEqual({ "X-Workspace": "w" });
+ expect(auth.getToken).toHaveBeenCalledOnce();
+ });
+
+ it("propagates getToken errors other than authorization-required", async () => {
+ const boom = new Error("boom");
+ const client = new McpConnectionClient(
+ makeConnection({
+ authorization: { getToken: vi.fn().mockRejectedValue(boom), principalType: "app" },
+ }),
+ );
+
+ await expect(client.getToolMetadata()).rejects.toBe(boom);
+ expect(createMCPClient).not.toHaveBeenCalled();
+ });
+
+ it("asks for authorization when the server rejects the anonymous connection", async () => {
+ const auth = pendingSignIn();
+ createMCPClient.mockRejectedValue(unauthorized());
+ const client = new McpConnectionClient(makeConnection({ authorization: auth.authorization }));
+
+ const err = await client.getToolMetadata().catch((e) => e);
+
+ expect(isConnectionAuthorizationRequiredError(err)).toBe(true);
+ expect(err.message).toBe(
+ 'Connection "test" requires authorization (the server requires sign-in).',
+ );
+ // There was no bearer to evict.
+ expect(auth.evict).not.toHaveBeenCalled();
+ });
+
+ it("asks for authorization when an anonymous tools/list returns 401", async () => {
+ const auth = pendingSignIn();
+ createMCPClient.mockResolvedValue({
+ close: vi.fn(),
+ listTools: vi.fn().mockRejectedValue(unauthorized()),
+ toolsFromDefinitions: vi.fn(),
+ });
+ const client = new McpConnectionClient(makeConnection({ authorization: auth.authorization }));
+
+ const err = await client.getToolMetadata().catch((e) => e);
+
+ expect(isConnectionAuthorizationRequiredError(err)).toBe(true);
+ });
+
+ it.each([
+ ["an HTTP 401", () => Promise.reject(unauthorized())],
+ [
+ "an mcp/www_authenticate tool result",
+ () => ({
+ _meta: { "mcp/www_authenticate": ['Bearer error="invalid_token"'] },
+ content: [{ type: "text", text: "Sign in to continue." }],
+ isError: true,
+ }),
+ ],
+ ])(
+ "runs public tools anonymously, asks for sign-in on %s, then reconnects with the token",
+ async (_label, challenge) => {
+ const auth = pendingSignIn();
+ const { close } = fakeServer((name) =>
+ name === "protected_tool" && auth.getToken.mock.calls.length === 1
+ ? challenge()
+ : { content: [{ type: "text", text: name }] },
+ );
+ const client = new McpConnectionClient(makeConnection({ authorization: auth.authorization }));
+
+ await expect(client.executeTool("public_tool", {}, { callId: "c1" })).resolves.toEqual({
+ content: [{ type: "text", text: "public_tool" }],
+ });
+ const err = await client.executeTool("protected_tool", {}, { callId: "c2" }).catch((e) => e);
+ expect(isConnectionAuthorizationRequiredError(err)).toBe(true);
+ expect(close).toHaveBeenCalledOnce();
+ expect(auth.evict).not.toHaveBeenCalled();
+
+ auth.signIn("fresh-token");
+ await expect(client.executeTool("protected_tool", {}, { callId: "c3" })).resolves.toEqual({
+ content: [{ type: "text", text: "protected_tool" }],
+ });
+ expect(createMCPClient).toHaveBeenCalledTimes(2);
+ expect(sentHeaders(0)).toEqual({});
+ expect(sentHeaders(1)).toEqual({ Authorization: "Bearer fresh-token" });
+ },
+ );
+
+ it("evicts the bearer when a signed-in call returns an mcp/www_authenticate challenge", async () => {
+ const evict = vi.fn();
+ fakeServer(() => ({
+ _meta: { "mcp/www_authenticate": 'Bearer error="insufficient_scope"' },
+ content: [],
+ isError: true,
+ }));
+ const client = new McpConnectionClient(
+ makeConnection({
+ authorization: { evict, getToken: async () => ({ token: "t" }), principalType: "app" },
+ }),
+ );
+
+ // Eviction needs a runtime scope.
+ const err = await contextStorage.run(ctxWithAuth(null), () =>
+ client.executeTool("protected_tool", {}, { callId: "c1" }).catch((e) => e),
+ );
+
+ expect(isConnectionAuthorizationRequiredError(err)).toBe(true);
+ expect(evict).toHaveBeenCalledOnce();
+ });
+
+ it("keeps resolveHeaders strict for callers that require a token", async () => {
+ const auth = pendingSignIn();
+ const err = await resolveHeaders(makeConnection({ authorization: auth.authorization })).catch(
+ (e) => e,
+ );
+ expect(isConnectionAuthorizationRequiredError(err)).toBe(true);
+ });
+});
+
+describe("isMcpAuthChallengeResult", () => {
+ it("detects error results carrying a WWW-Authenticate challenge", () => {
+ const challenge = 'Bearer resource_metadata="https://mcp.example.com/.well-known/x"';
+ expect(
+ isMcpAuthChallengeResult({ isError: true, _meta: { "mcp/www_authenticate": [challenge] } }),
+ ).toBe(true);
+ expect(
+ isMcpAuthChallengeResult({ isError: true, _meta: { "mcp/www_authenticate": challenge } }),
+ ).toBe(true);
+ });
+
+ it("ignores successful results, empty challenges, and plain errors", () => {
+ expect(
+ isMcpAuthChallengeResult({ _meta: { "mcp/www_authenticate": ["Bearer"] }, content: [] }),
+ ).toBe(false);
+ expect(isMcpAuthChallengeResult({ isError: true, _meta: { "mcp/www_authenticate": [] } })).toBe(
+ false,
+ );
+ expect(isMcpAuthChallengeResult({ isError: true, content: [] })).toBe(false);
+ expect(isMcpAuthChallengeResult(undefined)).toBe(false);
+ });
+});
+
describe("passesToolFilter", () => {
it("passes all tools when filter is undefined", () => {
expect(passesToolFilter("any_tool", undefined)).toBe(true);
diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.ts
index e26b27942..73c3b7195 100644
--- a/packages/eve/src/runtime/connections/mcp-client.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.ts
@@ -2,7 +2,10 @@ import { createMCPClient, type MCPClient } from "#compiled/@ai-sdk/mcp/index.js"
import type { ToolSet } from "ai";
import { buildCallbackContext } from "#context/build-callback-context.js";
-import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";
+import {
+ ConnectionAuthorizationRequiredError,
+ isConnectionAuthorizationRequiredError,
+} from "#connections/errors.js";
import type { SessionContext } from "#context/session-context.js";
import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";
@@ -37,6 +40,12 @@ interface McpToolCache {
*
* Created lazily per-connection per-session. Caches tool metadata after
* the first `getToolMetadata()` call.
+ *
+ * When the connection declares `authorization` but no token is available
+ * yet (`getToken` throws {@link ConnectionAuthorizationRequiredError}), the
+ * client connects anonymously instead of failing. Sign-in is only requested
+ * once the server asks for it: an HTTP `401` on any request, or a tool
+ * result that carries an `mcp/www_authenticate` challenge.
*/
export class McpConnectionClient implements ConnectionClient {
#clientPromise: Promise<MCPClient> | undefined;
@@ -44,6 +53,8 @@ export class McpConnectionClient implements ConnectionClient {
#toolsPromise: Promise<McpToolCache> | undefined;
#tools: McpToolCache | undefined;
#connection: ResolvedConnectionDefinition;
+ /** Whether the current transport connected without a bearer because none was available yet. */
+ #anonymous = false;
constructor(connection: ResolvedConnectionDefinition) {
this.#connection = connection;
@@ -76,7 +87,10 @@ export class McpConnectionClient implements ConnectionClient {
}
async #createClient(): Promise<MCPClient> {
- const headers = await resolveHeaders(this.#connection);
+ const { anonymous, headers } = await resolveConnectionHeaders(this.#connection, {
+ anonymousWhenAuthorizationRequired: true,
+ });
+ this.#anonymous = anonymous;
const url = this.#connection.url;
const fetch = createMcpTraceFetch({
connectionName: this.#connection.connectionName,
@@ -120,13 +134,15 @@ export class McpConnectionClient implements ConnectionClient {
* A `401`/`invalid_token` from the remote server is translated into
* {@link ConnectionAuthorizationRequiredError} via {@link #rethrowClassified}
* so callers re-enter the authorization flow instead of surfacing an
- * opaque transport error.
+ * opaque transport error. A tool error result carrying an
+ * `_meta["mcp/www_authenticate"]` challenge is treated the same way.
*/
async executeTool(
toolName: string,
args: unknown,
options: ConnectionToolExecuteOptions,
): Promise<unknown> {
+ let result: unknown;
try {
const { tools } = await this.#ensureTools();
@@ -145,7 +161,7 @@ export class McpConnectionClient implements ConnectionClient {
toolName,
});
- return await withMcpToolCallSpan({
+ result = await withMcpToolCallSpan({
arguments: args,
connectionName: this.#connection.connectionName,
execute: async () =>
@@ -156,6 +172,10 @@ export class McpConnectionClient implements ConnectionClient {
} catch (error) {
return await this.#rethrowClassified(error);
}
+ if (isMcpAuthChallengeResult(result)) {
+ return await this.#requireAuthorization(`the server asked for sign-in to call "${toolName}"`);
+ }
+ return result;
}
async #ensureTools(): Promise<McpToolCache> {
@@ -233,27 +253,38 @@ export class McpConnectionClient implements ConnectionClient {
this.#clientPromise = undefined;
this.#toolsPromise = undefined;
this.#tools = undefined;
+ this.#anonymous = false;
}
/**
* Always rethrows — this only classifies the error first. A non-auth
* error (timeout, `5xx`, `403`, "tool not found", network failure) is
- * rethrown unchanged. Only a server rejection of the bearer
- * (`401`/`invalid_token`) is translated: evict the stale cached token,
- * tear down the connection so the retry reconnects with a fresh bearer,
- * and rethrow as {@link ConnectionAuthorizationRequiredError} so the
- * re-authorization flow takes over.
+ * rethrown unchanged. Only a `401` is translated, via
+ * {@link #requireAuthorization}.
*/
async #rethrowClassified(error: unknown): Promise<never> {
if (!isMcpAuthRequiredError(error)) {
throw error;
}
- await this.#evictCachedToken();
+ return await this.#requireAuthorization(
+ this.#anonymous ? "the server requires sign-in" : "the server rejected the token",
+ );
+ }
+
+ /**
+ * Evicts the stale cached token (when the request carried one), tears
+ * down the connection so the retry reconnects with a fresh bearer and
+ * reloads the tool list, and throws
+ * {@link ConnectionAuthorizationRequiredError} so the authorization flow
+ * takes over.
+ */
+ async #requireAuthorization(reason: string): Promise<never> {
+ if (!this.#anonymous) {
+ await this.#evictCachedToken();
+ }
await this.close();
throw new ConnectionAuthorizationRequiredError(this.#connection.connectionName, {
- message:
- `Connection "${this.#connection.connectionName}" requires authorization ` +
- `(the server rejected the token).`,
+ message: `Connection "${this.#connection.connectionName}" requires authorization (${reason}).`,
});
}
@@ -289,6 +320,25 @@ export function isMcpAuthRequiredError(error: unknown): boolean {
return readHttpStatus(error) === 401;
}
+/** `_meta` key a tool result uses to ask for sign-in (OpenAI Apps SDK convention). */
+export const MCP_WWW_AUTHENTICATE_META_KEY = "mcp/www_authenticate";
+
+/**
+ * Returns `true` for a `tools/call` error result that asks the client to
+ * sign in: `isError: true` plus a non-empty `_meta["mcp/www_authenticate"]`
+ * (a `WWW-Authenticate` challenge string or list of them). Servers that
+ * accept anonymous `initialize`/`tools/list` use this to protect individual
+ * tools without failing the whole HTTP request.
+ */
+export function isMcpAuthChallengeResult(result: unknown): boolean {
+ if (!isObject(result) || result.isError !== true || !isObject(result._meta)) {
+ return false;
+ }
+ const challenge = result._meta[MCP_WWW_AUTHENTICATE_META_KEY];
+ if (typeof challenge === "string") return challenge.length > 0;
+ return Array.isArray(challenge) && challenge.length > 0;
+}
+
/**
* Decides whether an error thrown while creating a streamable HTTP MCP
* client should trigger a fallback attempt against the legacy SSE
@@ -391,7 +441,30 @@ export function passesToolFilter(
export async function resolveHeaders(
connection: ResolvedConnectionDefinition,
): Promise<Record<string, string>> {
+ const { headers } = await resolveConnectionHeaders(connection, {
+ anonymousWhenAuthorizationRequired: false,
+ });
+ return headers;
+}
+
+interface ResolvedConnectionHeaders {
+ /** `true` when `authorization` is declared but no token was available, so no bearer was set. */
+ readonly anonymous: boolean;
+ readonly headers: Record<string, string>;
+}
+
+/**
+ * {@link resolveHeaders}, optionally tolerating a missing token: with
+ * `anonymousWhenAuthorizationRequired`, a {@link ConnectionAuthorizationRequiredError}
+ * from `getToken` leaves the `Authorization` header unset and reports
+ * `anonymous: true` instead of throwing. Every other error still propagates.
+ */
+async function resolveConnectionHeaders(
+ connection: ResolvedConnectionDefinition,
+ options: { readonly anonymousWhenAuthorizationRequired: boolean },
+): Promise<ResolvedConnectionHeaders> {
const merged: Record<string, string> = {};
+ let anonymous = false;
let callbackContext: SessionContext | undefined;
const getCallbackContext = (): SessionContext => (callbackContext ??= buildCallbackContext());
@@ -401,8 +474,18 @@ export async function resolveHeaders(
);
if (authorization !== undefined) {
- const result = await resolveToken(connection, authorization);
- merged.Authorization = `Bearer ${result.token}`;
+ try {
+ const result = await resolveToken(connection, authorization);
+ merged.Authorization = `Bearer ${result.token}`;
+ } catch (error) {
+ if (
+ !options.anonymousWhenAuthorizationRequired ||
+ !isConnectionAuthorizationRequiredError(error)
+ ) {
+ throw error;
+ }
+ anonymous = true;
+ }
}
if (connection.headers !== undefined) {
@@ -417,7 +500,7 @@ export async function resolveHeaders(
}
}
- return merged;
+ return { anonymous, headers: merged };
}
/**