Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

fix(eve): refresh MCP credentials before transport requests (#4922)

Murat Sutunc86b9c4264f11
diff --git a/.changeset/fresh-mcp-bearers.md b/.changeset/fresh-mcp-bearers.md
new file mode 100644
index 000000000..9a60059fd
--- /dev/null
+++ b/.changeset/fresh-mcp-bearers.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Resolve MCP credentials before each request so live clients use refreshed tokens after expiry. Retry a rejected bearer once through the token provider before requesting sign-in, while preserving existing permission errors.
diff --git a/docs/connections/mcp.mdx b/docs/connections/mcp.mdx
index 698e75d0f..5ba507744 100644
--- a/docs/connections/mcp.mdx
+++ b/docs/connections/mcp.mdx
@@ -53,6 +53,10 @@ eve asks the user to sign in only when the MCP server asks for it. When a connec
After the user signs in, the turn resumes and the model makes the call 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.
+eve resolves credentials before each MCP HTTP request, including requests on an existing client. When the cached token's `expiresAt` has passed, eve calls the token provider again. If the server rejects a bearer with HTTP `401`, eve evicts the cached token, asks the provider for another token, and retries the request once before asking for sign-in.
+
+Eviction clears eve's cached access token and calls the provider's optional `evict` hook. The provider controls whether it retains a refresh grant for silent renewal. Missing grants and rejected replacement tokens still use the normal authorization flow; HTTP `403` permission failures do not trigger token refresh or retries.
+
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
diff --git a/docs/connections/overview.mdx b/docs/connections/overview.mdx
index 0e54392fd..1e452a26d 100644
--- a/docs/connections/overview.mdx
+++ b/docs/connections/overview.mdx
@@ -99,7 +99,7 @@ export default defineMcpClientConnection({
});
```
-If the token has a known TTL, set `expiresAt` (milliseconds since epoch) and eve refreshes ahead of time rather than waiting for a `401`.
+If the token has a known TTL, set `expiresAt` (milliseconds since epoch). Once it expires, eve calls `getToken` again before the next request, including requests on an existing MCP client.
When `getToken` is the only auth, `credentialOwner` defaults to `"app"`: one shared credential keyed across all sessions. Set `credentialOwner: "user"` when each end-user carries their own token.
diff --git a/packages/eve/src/runtime/connections/mcp-client.integration.test.ts b/packages/eve/src/runtime/connections/mcp-client.integration.test.ts
index fe955a27e..e8b46b527 100644
--- a/packages/eve/src/runtime/connections/mcp-client.integration.test.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.integration.test.ts
@@ -11,6 +11,9 @@ import {
resolveDynamicConnectionValue,
} from "#runtime/resolve-connection.js";
import { McpConnectionClient } from "#runtime/connections/mcp-client.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { AuthKey, InitiatorAuthKey } from "#context/keys.js";
+import { ConnectionAuthorizationRequiredError } from "#connections/errors.js";
describe.each(["static", "dynamic"] as const)(
"%s MCP protocol configuration with the bundled client",
@@ -198,3 +201,202 @@ describe.each(["static", "dynamic"] as const)(
});
},
);
+
+describe("MCP bearer refresh with the bundled client", () => {
+ let client: McpConnectionClient;
+ let token: string;
+ let acceptedToken: string;
+ let status: number;
+ const requests: { method: string; bearer: string | null }[] = [];
+ const getToken = vi.fn();
+ const evict = vi.fn();
+ const ctx = new ContextContainer();
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-10-15T12:00:00Z"));
+ ctx.clearVirtualContext();
+ ctx.set(AuthKey, {
+ attributes: {},
+ authenticator: "test",
+ issuer: "test",
+ principalId: "alice",
+ principalType: "user",
+ });
+ ctx.set(InitiatorAuthKey, {
+ attributes: {},
+ authenticator: "test",
+ issuer: "test",
+ principalId: "bob",
+ principalType: "user",
+ });
+ token = "first-token";
+ acceptedToken = token;
+ status = 200;
+ requests.length = 0;
+ getToken
+ .mockReset()
+ .mockImplementation(async () => ({ token, expiresAt: Date.now() + 60_000 }));
+ evict.mockReset();
+ client = new McpConnectionClient({
+ authorization: { getToken, evict, principalType: "user" },
+ connectionName: "test",
+ description: "Read the current user",
+ forwardPrincipal: true,
+ logicalPath: "connections/test.ts",
+ protocol: "mcp",
+ protocolVersionDiscovery: false,
+ sourceId: "connections/test",
+ sourceKind: "module",
+ url: "https://mcp.example.com/mcp",
+ });
+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const message = (await request.json()) as { id?: number; method: string };
+ const bearer = request.headers.get("authorization");
+ const forwarded = request.headers.get("eve-forwarded-principal");
+ expect(forwarded).not.toBeNull();
+ expect(JSON.parse(Buffer.from(forwarded!, "base64url").toString())).toEqual({
+ current: ctx.get(AuthKey),
+ initiator: ctx.get(InitiatorAuthKey),
+ });
+ expect(request.redirect).toBe("error");
+ requests.push({ method: message.method, bearer });
+ if (status !== 200 || bearer !== `Bearer ${acceptedToken}`) {
+ return new Response("Access denied", { status: status === 200 ? 401 : status });
+ }
+ let result: Record<string, unknown>;
+ switch (message.method) {
+ case "initialize":
+ result = {
+ capabilities: { tools: {} },
+ protocolVersion: "2025-11-25",
+ serverInfo: { name: "refresh-fixture", version: "1.0.0" },
+ };
+ break;
+ case "notifications/initialized":
+ return new Response(null, { status: 202 });
+ case "tools/list":
+ result = { tools: [{ name: "whoami", inputSchema: { type: "object", properties: {} } }] };
+ break;
+ case "tools/call":
+ result = { content: [{ type: "text", text: "alice" }] };
+ break;
+ default:
+ throw new Error(`Unexpected MCP method: ${message.method}`);
+ }
+ return Response.json({ jsonrpc: "2.0", id: message.id, result });
+ });
+ });
+
+ afterEach(async () => {
+ await client.close();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ const call = () =>
+ contextStorage.run(ctx, () => client.executeTool("whoami", {}, { callId: "read" }));
+
+ it("refreshes an expired bearer on a live MCP client without consent or another handshake", async () => {
+ await call();
+ token = acceptedToken = "refreshed-token";
+ vi.setSystemTime(Date.now() + 60_001);
+ await expect(call()).resolves.toMatchObject({ content: [{ text: "alice" }] });
+ expect(
+ requests
+ .filter((request) => request.method === "tools/call")
+ .map((request) => request.bearer),
+ ).toEqual(["Bearer first-token", "Bearer refreshed-token"]);
+ expect(requests.filter((request) => request.method === "initialize")).toHaveLength(1);
+ expect(evict).not.toHaveBeenCalled();
+ });
+
+ it("silently reacquires a rejected bearer and retries the request once", async () => {
+ await call();
+ token = acceptedToken = "replacement-token";
+ await expect(call()).resolves.toMatchObject({ content: [{ text: "alice" }] });
+ expect(
+ requests
+ .filter((request) => request.method === "tools/call")
+ .map((request) => request.bearer),
+ ).toEqual(["Bearer first-token", "Bearer first-token", "Bearer replacement-token"]);
+ expect(evict).toHaveBeenCalledOnce();
+ });
+
+ it("resolves credentials in the current execution context rather than the connect context", async () => {
+ await call();
+ token = acceptedToken = "next-execution-token";
+ const nextExecution = new ContextContainer();
+ nextExecution.set(AuthKey, ctx.get(AuthKey)!);
+ nextExecution.set(InitiatorAuthKey, ctx.get(InitiatorAuthKey)!);
+
+ await expect(
+ contextStorage.run(nextExecution, () =>
+ client.executeTool("whoami", {}, { callId: "next-execution" }),
+ ),
+ ).resolves.toMatchObject({ content: [{ text: "alice" }] });
+ expect(getToken).toHaveBeenCalledTimes(2);
+ expect(requests.filter((request) => request.method === "initialize")).toHaveLength(1);
+ expect(requests.at(-1)?.bearer).toBe("Bearer next-execution-token");
+ expect(evict).not.toHaveBeenCalled();
+ });
+
+ it("requires consent when the refreshed bearer is also rejected, without looping", async () => {
+ await call();
+ token = "replacement-token";
+ acceptedToken = "unavailable-token";
+ await expect(call()).rejects.toMatchObject({ name: "ConnectionAuthorizationRequiredError" });
+ expect(requests.filter((request) => request.method === "tools/call")).toHaveLength(3);
+ });
+
+ it("keeps missing grants in the existing consent flow", async () => {
+ await call();
+ getToken.mockRejectedValue(new ConnectionAuthorizationRequiredError("test"));
+ vi.setSystemTime(Date.now() + 60_001);
+ await expect(call()).rejects.toMatchObject({ name: "ConnectionAuthorizationRequiredError" });
+ expect(requests.filter((request) => request.method === "tools/call").at(-1)?.bearer).toBeNull();
+ });
+
+ it("evicts a rejected replacement bearer even when another user makes an anonymous request", async () => {
+ await call();
+ token = "replacement-token";
+ acceptedToken = "unavailable-token";
+ getToken.mockImplementation(async ({ principal }) => {
+ if (principal.id === "bob") throw new ConnectionAuthorizationRequiredError("test");
+ return { token, expiresAt: Date.now() + 60_000 };
+ });
+ const bob = new ContextContainer();
+ bob.set(AuthKey, { ...ctx.get(AuthKey)!, principalId: "bob" });
+ const fetch = globalThis.fetch;
+ vi.stubGlobal("fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ const request = new Request(input, init);
+ const message = (await request.json()) as { id?: number; method: string };
+ if (request.headers.get("authorization") === null) {
+ return Response.json({
+ jsonrpc: "2.0",
+ id: message.id,
+ result: { content: [{ type: "text", text: "anonymous" }] },
+ });
+ }
+ if (request.headers.get("authorization") === "Bearer replacement-token") {
+ await expect(
+ contextStorage.run(bob, () => client.executeTool("whoami", {}, { callId: "bob" })),
+ ).resolves.toMatchObject({ content: [{ text: "anonymous" }] });
+ }
+ return await fetch(input, init);
+ });
+
+ await expect(call()).rejects.toMatchObject({ name: "ConnectionAuthorizationRequiredError" });
+ expect(evict).toHaveBeenCalledTimes(2);
+ expect(evict.mock.calls.map(([options]) => options.principal.id)).toEqual(["alice", "alice"]);
+ });
+
+ it("does not refresh or retry a team permission failure", async () => {
+ await call();
+ status = 403;
+ await expect(call()).rejects.toThrow();
+ expect(requests.filter((request) => request.method === "tools/call")).toHaveLength(2);
+ expect(evict).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/eve/src/runtime/connections/mcp-client.test.ts b/packages/eve/src/runtime/connections/mcp-client.test.ts
index acd052fc1..62ab37981 100644
--- a/packages/eve/src/runtime/connections/mcp-client.test.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.test.ts
@@ -198,7 +198,9 @@ describe("McpConnectionClient", () => {
expect(init.redirect).toBe("error");
await send({ ...userAuth("anon"), principalType: "anonymous" });
- expect(sent.mock.calls[1]![1]).toEqual({});
+ expect(new Headers(sent.mock.calls[1]![1]?.headers).has("eve-forwarded-principal")).toBe(
+ false,
+ );
const delegated = ctxWithAuth(userAuth("alice"));
delegated.set(InitiatorAuthKey, userAuth("bob"));
diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.ts
index 4110820af..69115642e 100644
--- a/packages/eve/src/runtime/connections/mcp-client.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.ts
@@ -41,6 +41,28 @@ interface McpToolCache {
readonly tools: ToolSet;
}
+/** Carries the failing request's auth state through SDK error wrappers. */
+class McpUnauthorizedError extends Error {
+ readonly statusCode = 401;
+ readonly anonymous: boolean;
+
+ constructor(anonymous: boolean) {
+ super("MCP HTTP request failed (HTTP 401).");
+ this.anonymous = anonymous;
+ }
+}
+
+async function checkAuthorizationResponse(
+ response: Response,
+ anonymous: boolean,
+): Promise<Response> {
+ if (response.status === 401) {
+ await response.body?.cancel();
+ throw new McpUnauthorizedError(anonymous);
+ }
+ return response;
+}
+
/**
* Wraps one `MCPClient` from `@ai-sdk/mcp` for a single connection.
*
@@ -59,8 +81,6 @@ 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;
readonly eventActions: ConnectionClient["eventActions"];
constructor(connection: ResolvedConnectionDefinition) {
@@ -120,14 +140,13 @@ export class McpConnectionClient implements ConnectionClient {
}
async #createClient(): Promise<MCPClient> {
- const { anonymous, headers } = await resolveConnectionHeaders(this.#connection, {
+ const { headers } = await resolveConnectionHeaders(this.#connection, {
anonymousWhenAuthorizationRequired: true,
});
- this.#anonymous = anonymous;
const url = this.#connection.url;
const fetch = createMcpTraceFetch({
connectionName: this.#connection.connectionName,
- fetcher: this.#forwardingFetch(),
+ fetcher: this.#authorizedFetch(Object.keys(headers)),
getProtocolVersion: () => this.#client?.initializeResult?.protocolVersion,
});
@@ -147,6 +166,41 @@ export class McpConnectionClient implements ConnectionClient {
}
}
+ /** Keep eve's token provider on the request path instead of capturing one bearer forever. */
+ #authorizedFetch(connectionHeaderNames: readonly string[]): typeof fetch {
+ const fetcher = this.#forwardingFetch() ?? globalThis.fetch;
+ return async (request, init) => {
+ const resolve = () =>
+ resolveConnectionHeaders(this.#connection, { anonymousWhenAuthorizationRequired: true });
+ const send = async (resolved: ResolvedConnectionHeaders) => {
+ const headers = new Headers(init?.headers);
+ for (const name of connectionHeaderNames) headers.delete(name);
+ for (const [name, value] of Object.entries(resolved.headers)) headers.set(name, value);
+ return await fetcher(request, { ...init, headers });
+ };
+
+ const resolved = await resolve();
+ const response = await send(resolved);
+ if (
+ response.status !== 401 ||
+ resolved.anonymous ||
+ this.#connection.authorization === undefined ||
+ init?.signal?.aborted
+ ) {
+ return await checkAuthorizationResponse(response, resolved.anonymous);
+ }
+
+ // A rejected access token need not mean the refresh grant needs consent.
+ await this.#evictCachedToken();
+ const refreshed = await resolve();
+ if (refreshed.anonymous) {
+ return await checkAuthorizationResponse(response, true);
+ }
+ await response.body?.cancel();
+ return await checkAuthorizationResponse(await send(refreshed), refreshed.anonymous);
+ };
+ }
+
/**
* With `forwardPrincipal`, adds `eve-forwarded-principal` to every request,
* read per request: one client can serve turns from different people in a
@@ -303,7 +357,6 @@ export class McpConnectionClient implements ConnectionClient {
this.#clientPromise = undefined;
this.#toolsPromise = undefined;
this.#tools = undefined;
- this.#anonymous = false;
}
/**
@@ -316,8 +369,19 @@ export class McpConnectionClient implements ConnectionClient {
if (!isMcpAuthRequiredError(error)) {
throw error;
}
+ const requestError = [...walkErrorChain(error)].find(
+ (candidate) => candidate instanceof McpUnauthorizedError,
+ );
+ const anonymous =
+ requestError?.anonymous ??
+ (
+ await resolveConnectionHeaders(this.#connection, {
+ anonymousWhenAuthorizationRequired: true,
+ })
+ ).anonymous;
return await this.#requireAuthorization(
- this.#anonymous ? "the server requires sign-in" : "the server rejected the token",
+ anonymous ? "the server requires sign-in" : "the server rejected the token",
+ anonymous,
);
}
@@ -328,8 +392,11 @@ export class McpConnectionClient implements ConnectionClient {
* {@link ConnectionAuthorizationRequiredError} so the authorization flow
* takes over.
*/
- async #requireAuthorization(reason: string): Promise<never> {
- if (!this.#anonymous) {
+ async #requireAuthorization(reason: string, anonymous?: boolean): Promise<never> {
+ anonymous ??= (
+ await resolveConnectionHeaders(this.#connection, { anonymousWhenAuthorizationRequired: true })
+ ).anonymous;
+ if (!anonymous) {
await this.#evictCachedToken();
}
await this.close();