Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): run tools published over mcpChannel as a forwarded user (#4236)

Rui866cb415a5b3
diff --git a/.changeset/mcp-forwarded-principals.md b/.changeset/mcp-forwarded-principals.md
new file mode 100644
index 000000000..64891e70c
--- /dev/null
+++ b/.changeset/mcp-forwarded-principals.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Tools published with `mcpChannel({ tools: true })` can now run as the user a trusted caller forwards. Set `trustedForwarders` on the channel to accept the `eve-forwarded-principal` header, and `forwardPrincipal: true` on a `defineMcpClientConnection` to send the turn's user to another eve agent. A channel without `trustedForwarders` refuses requests carrying the header with `403`. `invokeTool` also accepts an `initiator` option.
diff --git a/docs/channels/mcp.mdx b/docs/channels/mcp.mdx
index de50aa268..c1128b114 100644
--- a/docs/channels/mcp.mdx
+++ b/docs/channels/mcp.mdx
@@ -227,7 +227,7 @@ export default mcpChannel({
`tools/list` returns the `agent_*` tools first, then the agent's tools in name order with their input and output JSON schemas. Framework tools, workflow and provider tools, tools without `execute`, and tools added by dynamic resolvers or subagents are not published. While `agent` is on, an agent tool named `agent_start`, `agent_get`, `agent_update`, or `agent_cancel` is not published, and eve logs a warning. With `agent: false`, the channel sends no `agent_*` instructions. Turning off both `agent` and `tools` throws.
-Each `tools/call` checks the arguments against the tool's input schema, then runs the tool as the route-authenticated caller, with no model, turn, or workflow run. Every caller the channel's `auth` admits can call these tools, outside the agent's instructions, so review what becomes callable before you turn this on. Each call gets its own session:
+Each `tools/call` checks the arguments against the tool's input schema, then runs the tool as the route-authenticated caller, or as a [forwarded user](#forwarded-principals), with no model, turn, or workflow run. Every caller the channel's `auth` admits can call these tools, outside the agent's instructions, so review what becomes callable before you turn this on. Each call gets its own session:
- Authored state starts from its initial value, and updates are not kept.
- A sandbox the tool opens is deleted when the call ends.
@@ -249,6 +249,34 @@ MCP clients send W3C trace context in each request's `params._meta`, not in HTTP
`_meta.baggage` is never read. A caller cannot choose the trace audience, session lineage, or content capture: those come from the channel and your `tracePolicy`, as they do for conversations. The `execute_tool` span records the call's arguments and result only when that content decision allows it, and never records exception text.
+### Forwarded principals
+
+A router that calls the channel on behalf of its own users, such as another eve agent's [`forwardPrincipal` connection](../connections/mcp#forward-the-caller-to-an-eve-agent), can name the user in the `eve-forwarded-principal` header: unpadded base64url of UTF-8 JSON `{ current, initiator? }`, at most 16 KiB. eve accepts the header only when `trustedForwarders` is set, and only from a route-authenticated forwarder the predicate accepts:
+
+```ts title="agent/channels/mcp.ts"
+import { vercelOidc, vercelSubject } from "eve/channels/auth";
+import { mcpChannel } from "eve/channels/mcp";
+
+export default mcpChannel({
+ auth: [vercelOidc()],
+ tools: true,
+ // Only the router deployment may name the user a tool runs as.
+ trustedForwarders: (forwarder) =>
+ forwarder.subject === vercelSubject({ teamSlug: "acme", projectName: "router" }),
+});
+```
+
+The predicate receives the verified forwarder and the principals it asserts, as the [eve channel](./eve)'s `trustedForwarders` does, so match the forwarder precisely; see [Accepting forwarded identity](../guides/auth-and-route-protection#accepting-forwarded-identity-from-another-deployment). A published tool called with an accepted header runs as the forwarded user: `ctx.session.auth.current` is that user, `ctx.session.auth.initiator` is the asserted initiator or that user, and both carry the forwarder's `principalId` in the `eve:forwarded-by` attribute. The `agent_*` tools still act as the route-authenticated caller.
+
+| Request | Response |
+| ------------------------------------------------------ | ------------------------ |
+| No header | Runs as the route caller |
+| Malformed or over 16 KiB | `400` |
+| The predicate refuses the forwarder or what it asserts | `403` |
+| The forwarder is anonymous (`none()`) | `403` |
+| The channel has no `trustedForwarders` | `403` |
+| The predicate throws | `500` |
+
## Invocation ownership
Every MCP operation reruns the configured auth policy. With authenticated policies, an invocation belongs to the principal that started it; knowing its ID is not sufficient. Bearer tokens are not stored with the invocation or forwarded to the agent's tools.
diff --git a/docs/connections/mcp.mdx b/docs/connections/mcp.mdx
index 1c6e40df0..4be2a65fb 100644
--- a/docs/connections/mcp.mdx
+++ b/docs/connections/mcp.mdx
@@ -159,6 +159,25 @@ Return `"user-approval"` (or `true`) to pause for a person and `"not-applicable"
[Human-in-the-loop](/docs/human-in-the-loop#approvals) covers the full set of statuses, how `approvedTools` and `session.auth` factor in, and how a gated call pauses and resumes durably.
+## Forward the caller to an eve agent
+
+When the server is another eve agent's [`mcpChannel`](../channels/mcp), set `forwardPrincipal: true` so its published tools run as the user of the current turn instead of as this deployment:
+
+```ts title="agent/connections/specialist.ts"
+import { defineMcpClientConnection } from "eve/connections";
+
+export default defineMcpClientConnection({
+ url: "https://specialist.example.com/eve/v1/mcp",
+ description: "The specialist agent's tools.",
+ headers: { authorization: `Bearer ${process.env.SPECIALIST_TOKEN}` },
+ forwardPrincipal: true,
+});
+```
+
+eve sends the turn's user, and its initiator when that differs, in the `eve-forwarded-principal` header on every request. A turn with no caller, or an anonymous one, sends no header. The server must trust this deployment's route-authenticated identity in `trustedForwarders`; otherwise it refuses the request with `403`. See [Forwarded principals](../channels/mcp#forwarded-principals). A request carrying the header fails rather than follow a redirect, so the header never reaches another host. A principal over 16 KiB encoded fails the call before it is sent; trim its attributes.
+
+Authenticate the connection as this deployment, with a stable service credential, like the token above, not with user-scoped `connect("...")` or a per-caller resolver. eve resolves `auth` and `headers` once when it opens the client, but one client can serve turns from different users in a shared session, so the header is what names the user on each request. The server trusts the forwarder by that service identity, and grants the user's own access to downstream services itself.
+
## Control result size
`connection_execute` returns an MCP tool's `structuredContent` when the server sends it. Otherwise it returns the result's text, parsed as JSON when the tool declares no output schema. Image, audio, and resource content reaches the model as file parts, and a result with `isError: true` fails the call with its text. MCP connections do not expose a per-result transform equivalent to an authored tool's [`toModelOutput`](/docs/tools#shape-what-the-model-sees-with-tomodeloutput).
diff --git a/e2e/fixtures/agent-mcp/agent/channels/eve.ts b/e2e/fixtures/agent-mcp/agent/channels/eve.ts
new file mode 100644
index 000000000..5d551d78a
--- /dev/null
+++ b/e2e/fixtures/agent-mcp/agent/channels/eve.ts
@@ -0,0 +1,18 @@
+import { eveChannel } from "eve/channels/eve";
+
+import { USER_HEADER } from "../../fixture";
+
+/** Fixture-only authentication: evals name the speaker, so turns have a user to forward. */
+export default eveChannel({
+ auth: (request) => {
+ const principalId = request.headers.get(USER_HEADER) ?? "e2e-eval";
+ return {
+ attributes: {},
+ authenticator: "e2e-fixture",
+ issuer: "e2e",
+ principalId,
+ principalType: "user",
+ subject: principalId,
+ };
+ },
+});
diff --git a/e2e/fixtures/agent-mcp/agent/channels/mcp.ts b/e2e/fixtures/agent-mcp/agent/channels/mcp.ts
index 398ad5379..ef8329e15 100644
--- a/e2e/fixtures/agent-mcp/agent/channels/mcp.ts
+++ b/e2e/fixtures/agent-mcp/agent/channels/mcp.ts
@@ -13,4 +13,7 @@ export default mcpChannel({
}
: null,
tools: true,
+ // The loopback connection forwards the turn's user; only this service may.
+ trustedForwarders: (forwarder) =>
+ forwarder.authenticator === "e2e-fixture" && forwarder.principalId === SERVICE_ID,
});
diff --git a/e2e/fixtures/agent-mcp/agent/connections/loopback.ts b/e2e/fixtures/agent-mcp/agent/connections/loopback.ts
index 4a4861eab..8fb59bf31 100644
--- a/e2e/fixtures/agent-mcp/agent/connections/loopback.ts
+++ b/e2e/fixtures/agent-mcp/agent/connections/loopback.ts
@@ -8,6 +8,7 @@ export default defineDynamic({
"session.started": () =>
defineMcpClientConnection({
description: "The Maple Street kennel agent's own tools, reached over its MCP channel.",
+ forwardPrincipal: true,
headers: { ...previewBypassHeaders(), authorization: `Bearer ${SERVICE_TOKEN}` },
url: selfMcpUrl(),
}),
diff --git a/e2e/fixtures/agent-mcp/agent/tools/whoami.ts b/e2e/fixtures/agent-mcp/agent/tools/whoami.ts
index 798093658..5a4d0f742 100644
--- a/e2e/fixtures/agent-mcp/agent/tools/whoami.ts
+++ b/e2e/fixtures/agent-mcp/agent/tools/whoami.ts
@@ -2,11 +2,12 @@ import { defineTool } from "eve/tools";
import { z } from "zod";
export default defineTool({
- description: "Report who this call runs as.",
+ description: "Report who this call runs as and which service forwarded it.",
inputSchema: z.object({}),
async execute(_input, ctx) {
const current = ctx.session.auth.current;
return {
+ forwardedBy: current?.attributes["eve:forwarded-by"] ?? null,
principalId: current?.principalId ?? null,
principalType: current?.principalType ?? null,
};
diff --git a/e2e/fixtures/agent-mcp/evals/call.eval.ts b/e2e/fixtures/agent-mcp/evals/call.eval.ts
index 076e0b801..6efefd944 100644
--- a/e2e/fixtures/agent-mcp/evals/call.eval.ts
+++ b/e2e/fixtures/agent-mcp/evals/call.eval.ts
@@ -2,24 +2,29 @@ import { isDeepStrictEqual } from "node:util";
import { defineEval } from "eve/evals";
-import { SERVICE_ID } from "../fixture";
+import { SERVICE_ID, USER_HEADER } from "../fixture";
import { requireMockModel } from "./mock-model";
export default defineEval({
description:
- "The agent calls one of its own tools through its MCP channel and gets the tool's exact structured output, run as the route-authenticated caller.",
+ "The agent calls one of its own tools through its MCP channel and gets the tool's exact structured output, run as the forwarded user rather than the forwarding service.",
async test(t) {
requireMockModel(t);
const turn = await t.send(
- "Alice starts her shift and checks which account the kennel tools run as. MCP_WHOAMI",
+ "Alice starts her shift and checks which account the kennel tools see her as. MCP_WHOAMI",
+ { headers: { [USER_HEADER]: "alice" } },
);
turn.expectOk();
turn.calledTool("loopback__whoami", {
count: 1,
output: (value) =>
- isDeepStrictEqual(value, { principalId: SERVICE_ID, principalType: "service" }),
+ isDeepStrictEqual(value, {
+ forwardedBy: SERVICE_ID,
+ principalId: "alice",
+ principalType: "user",
+ }),
});
},
});
diff --git a/e2e/fixtures/agent-mcp/fixture.ts b/e2e/fixtures/agent-mcp/fixture.ts
index 6c53d2f1b..6057cd5c3 100644
--- a/e2e/fixtures/agent-mcp/fixture.ts
+++ b/e2e/fixtures/agent-mcp/fixture.ts
@@ -4,6 +4,9 @@
* values exist so the fixture can call itself without injected env.
*/
+/** Header naming the person behind an eve-channel request. */
+export const USER_HEADER = "x-eve-fixture-user";
+
/** The service principal the loopback connection authenticates as. */
export const SERVICE_ID = "maple-router";
diff --git a/packages/eve/extension-contracts/compatibility/channel/v48.ts b/packages/eve/extension-contracts/compatibility/channel/v48.ts
new file mode 100644
index 000000000..637a2e510
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v48.ts
@@ -0,0 +1,20 @@
+import { defineChannel, POST } from "#public/channels/index.js";
+
+// Epoch 48 invokeTool options had no `initiator`; epoch 49 adds it.
+export default defineChannel({
+ routes: [
+ POST("/tools/:name", async (request, { describe, invokeTool, params }) => {
+ const { tools } = await describe();
+ if (!tools.some((tool) => tool.name === params.name)) {
+ return Response.json({ error: "unknown tool" }, { status: 404 });
+ }
+ const auth = {
+ attributes: {},
+ authenticator: "fixture",
+ principalId: "fixture",
+ principalType: "service",
+ };
+ return Response.json(await invokeTool(params.name!, await request.json(), { auth }));
+ }),
+ ],
+});
diff --git a/packages/eve/extension-contracts/compatibility/connection/v39.ts b/packages/eve/extension-contracts/compatibility/connection/v39.ts
new file mode 100644
index 000000000..9aaa22499
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/connection/v39.ts
@@ -0,0 +1,10 @@
+import { defineMcpClientConnection } from "#public/connections/index.js";
+
+// Epoch 39 MCP connections had no `forwardPrincipal`; epoch 40 adds it.
+// Connections that authenticate with their own headers keep working.
+export default defineMcpClientConnection({
+ description: "The specialist agent's tools.",
+ url: "https://specialist.example.com/eve/v1/mcp",
+ headers: { authorization: "Bearer specialist-token" },
+ protocolVersionDiscovery: false,
+});
diff --git a/packages/eve/extension-contracts/compatibility/tool/v76.ts b/packages/eve/extension-contracts/compatibility/tool/v76.ts
new file mode 100644
index 000000000..3011ab98e
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/tool/v76.ts
@@ -0,0 +1,11 @@
+import { z } from "zod";
+import { defineTool } from "#public/tools/index.js";
+
+// Epoch 76 MCP connection definitions had no `forwardPrincipal`; epoch 77 adds it.
+// Tools that read the session caller keep working.
+export default defineTool({
+ description: "Report which account a lookup runs as.",
+ inputSchema: z.object({}),
+ outputSchema: z.object({ principalId: z.string().nullable() }),
+ execute: (_input, ctx) => ({ principalId: ctx.session.auth.current?.principalId ?? null }),
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v49.json b/packages/eve/extension-contracts/reports/channel/v49.json
new file mode 100644
index 000000000..c782e90f9
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v49.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 49,
+ "sha256": "2c5c4029e74e4e0ca3fb22b6a0b19fc23c0c7e22302200a9785c02a54114a97c",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/connection/v40.json b/packages/eve/extension-contracts/reports/connection/v40.json
new file mode 100644
index 000000000..0e81cfc31
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/connection/v40.json
@@ -0,0 +1,16 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "connection",
+ "epoch": 40,
+ "sha256": "6d6d491da78ba356b846284c922d09727aa6e9bbea8412e77369735a297557dc",
+ "exports": [
+ "ConnectionAuthorizationFailedError",
+ "ConnectionAuthorizationRequiredError",
+ "defineDynamic",
+ "defineInteractiveAuthorization",
+ "defineMcpClientConnection",
+ "defineOpenAPIConnection",
+ "isConnectionAuthorizationFailedError",
+ "isConnectionAuthorizationRequiredError"
+ ]
+}
diff --git a/packages/eve/extension-contracts/reports/tool/v77.json b/packages/eve/extension-contracts/reports/tool/v77.json
new file mode 100644
index 000000000..05451c1c1
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/tool/v77.json
@@ -0,0 +1,29 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "tool",
+ "epoch": 77,
+ "sha256": "0c250214f3ad511996c2984131f19be3b14454a8aa0cb0bff8c7e41e91ceaecf",
+ "exports": [
+ "AgentRouterInput",
+ "AgentRouterTool",
+ "WorkflowStepToolContext",
+ "WorkflowTool",
+ "WorkflowToolDefinition",
+ "WorkflowToolInput",
+ "WorkflowToolOptions",
+ "agentRouter",
+ "decide",
+ "defaultWebSearch",
+ "defineTool",
+ "defineWorkflowTool",
+ "disableTool",
+ "isDisabledToolSentinel",
+ "isWebSearchToolDefinition",
+ "serializeModelInputSchema",
+ "toolOutput",
+ "toolOutputPart",
+ "toolResultFrom",
+ "webSearch",
+ "workflow"
+ ]
+}
diff --git a/packages/eve/src/channel/invoke-tool.ts b/packages/eve/src/channel/invoke-tool.ts
index 54115daed..3bf9e0728 100644
--- a/packages/eve/src/channel/invoke-tool.ts
+++ b/packages/eve/src/channel/invoke-tool.ts
@@ -5,6 +5,8 @@ import type { ToolModelOutput } from "#tools/model-output.js";
export interface InvokeToolOptions {
/** The caller this request authenticated. Becomes `ctx.session.auth.current`. */
readonly auth: SessionAuthContext;
+ /** Becomes `ctx.session.auth.initiator`. Defaults to `auth`. */
+ readonly initiator?: SessionAuthContext;
readonly signal?: AbortSignal;
}
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 1e63f8908..6726adcbc 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -22,8 +22,8 @@ interface ExtensionCapabilityContract {
const EXTENSION_CAPABILITY_CONTRACTS = {
extension: { current: 1, supported: [1], dropped: {} },
tool: {
- current: 76,
- supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76],
+ current: 77,
+ supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77],
dropped: {
14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",
15: "TaskExec replaces stageEffect with send",
@@ -127,10 +127,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 48,
+ current: 49,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, 47, 48,
+ 43, 44, 45, 46, 47, 48, 49,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
@@ -177,10 +177,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
connection: {
- current: 39,
+ current: 40,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 32, 33, 34,
- 35, 36, 37, 38, 39,
+ 35, 36, 37, 38, 39, 40,
],
dropped: {
9: "Dynamic connection resolvers no longer receive conversation or channel continuation data",
diff --git a/packages/eve/src/context/turn-principals.ts b/packages/eve/src/context/turn-principals.ts
new file mode 100644
index 000000000..793b24b07
--- /dev/null
+++ b/packages/eve/src/context/turn-principals.ts
@@ -0,0 +1,27 @@
+import type { SessionAuthContext } from "#channel/types.js";
+import { contextStorage } from "#context/container.js";
+import { AuthKey, InitiatorAuthKey, SessionKey } from "#context/keys.js";
+
+/**
+ * The active turn's caller and, when it differs, its initiator, read the same
+ * way for every consumer that attributes work to a person. `undefined` when
+ * the turn has no authenticated caller. Anonymous principals read as absent:
+ * every anonymous caller shares one synthetic identity, so one cannot be told
+ * apart from another, or vouched for.
+ */
+export function readTurnPrincipals():
+ | { readonly current: SessionAuthContext; readonly initiator?: SessionAuthContext }
+ | undefined {
+ const context = contextStorage.getStore();
+ const session = context?.get(SessionKey)?.auth;
+ const current = identified(context?.get(AuthKey) ?? session?.current);
+ if (current === undefined) return undefined;
+ const initiator = identified(context?.get(InitiatorAuthKey) ?? session?.initiator);
+ return initiator === undefined || initiator === current ? { current } : { current, initiator };
+}
+
+function identified(auth: SessionAuthContext | null | undefined): SessionAuthContext | undefined {
+ return auth === null || auth === undefined || auth.principalType === "anonymous"
+ ? undefined
+ : auth;
+}
diff --git a/packages/eve/src/execution/invoke-tool.test.ts b/packages/eve/src/execution/invoke-tool.test.ts
index f85bf645b..0e8c45300 100644
--- a/packages/eve/src/execution/invoke-tool.test.ts
+++ b/packages/eve/src/execution/invoke-tool.test.ts
@@ -117,6 +117,23 @@ function runtimeWith(
}
describe("invokeTool", () => {
+ it("runs as auth, with initiator defaulting to auth", async () => {
+ const bob: SessionAuthContext = { ...alice, principalId: "bob" };
+ const seen: unknown[] = [];
+ const runtime = runtimeWith([
+ tool("whoami", (_input, ctx) => {
+ seen.push({ ...ctx.session.auth });
+ return "ok";
+ }),
+ ]);
+ await invokeTool(runtime, "whoami", {}, { auth: alice });
+ await invokeTool(runtime, "whoami", {}, { auth: alice, initiator: bob });
+ expect(seen).toEqual([
+ { current: alice, initiator: alice },
+ { current: alice, initiator: bob },
+ ]);
+ });
+
it("evaluates the approval policy and never asks anyone", async () => {
const policies: Array<[ApprovalPolicy, object, boolean]> = [
[() => "user-approval", { status: "approval-required" }, false],
diff --git a/packages/eve/src/execution/invoke-tool.ts b/packages/eve/src/execution/invoke-tool.ts
index 2fa0a0613..3ec3b1517 100644
--- a/packages/eve/src/execution/invoke-tool.ts
+++ b/packages/eve/src/execution/invoke-tool.ts
@@ -147,6 +147,7 @@ async function runInvocation(input: {
const sandbox = await callSandbox(runtime, sessionId);
const context = createCallContext({
auth: options.auth,
+ initiator: options.initiator ?? options.auth,
callId,
callbackBaseUrl: runtime.callbackBaseUrl,
sessionId,
@@ -208,17 +209,18 @@ async function callSandbox(
function createCallContext(input: {
readonly auth: SessionAuthContext;
+ readonly initiator: SessionAuthContext;
readonly callId: string;
readonly callbackBaseUrl: string;
readonly sessionId: string;
}): ContextContainer {
const context = new ContextContainer();
context.set(AuthKey, input.auth);
- context.set(InitiatorAuthKey, input.auth);
+ context.set(InitiatorAuthKey, input.initiator);
context.set(SessionIdKey, input.sessionId);
// No turn exists; the stand-in names the call, as sandbox setup outside a turn does.
context.setVirtualContext(SessionKey, {
- auth: { current: input.auth, initiator: input.auth },
+ auth: { current: input.auth, initiator: input.initiator },
sessionId: input.sessionId,
turn: { id: input.callId, sequence: 0 },
});
diff --git a/packages/eve/src/internal/authored-definition/connection.ts b/packages/eve/src/internal/authored-definition/connection.ts
index fdf075006..8d3e96836 100644
--- a/packages/eve/src/internal/authored-definition/connection.ts
+++ b/packages/eve/src/internal/authored-definition/connection.ts
@@ -18,6 +18,7 @@ const KNOWN_TOP_LEVEL_KEYS = [
"approval",
"auth",
"description",
+ "forwardPrincipal",
"headers",
"instanceKey",
"protocolVersionDiscovery",
@@ -102,6 +103,13 @@ export function normalizeMcpClientConnectionDefinition(
result.protocolVersionDiscovery = record.protocolVersionDiscovery;
}
+ if (record.forwardPrincipal !== undefined) {
+ if (typeof record.forwardPrincipal !== "boolean") {
+ throw new Error(`${message} "forwardPrincipal" must be a boolean.`);
+ }
+ result.forwardPrincipal = record.forwardPrincipal;
+ }
+
if (record.instanceKey !== undefined) {
result.instanceKey = record.instanceKey as string;
}
diff --git a/packages/eve/src/internal/mcp/forwarded-principal-header.ts b/packages/eve/src/internal/mcp/forwarded-principal-header.ts
new file mode 100644
index 000000000..a77025f49
--- /dev/null
+++ b/packages/eve/src/internal/mcp/forwarded-principal-header.ts
@@ -0,0 +1,98 @@
+import {
+ resolveForwardedPrincipal,
+ type ForwardedPrincipal,
+ type TrustedForwarders,
+} from "#channel/forwarded-principal.js";
+import type { SessionAuthContext } from "#channel/types.js";
+
+/** Request header carrying a forwarded principal on MCP requests. */
+export const FORWARDED_PRINCIPAL_HEADER = "eve-forwarded-principal";
+
+/** Largest accepted encoded header value. */
+export const FORWARDED_PRINCIPAL_HEADER_MAX_BYTES = 16 * 1024;
+
+const BASE64URL_UNPADDED = /^[A-Za-z0-9_-]+$/;
+
+/** The principals one MCP request's published tools run as. */
+export interface McpRequestPrincipals {
+ /** The route-auth principal, or the accepted forwarded `current`. */
+ readonly current: SessionAuthContext;
+ /** The accepted forwarded initiator, or `current` when none was forwarded. */
+ readonly initiator: SessionAuthContext;
+}
+
+/**
+ * Resolves the `eve-forwarded-principal` header against the channel's
+ * `trustedForwarders`, sharing parsing, stamping, and the predicate with
+ * eveChannel's `forwardedPrincipal` body field.
+ *
+ * A header the channel cannot accept is a 403 rather than ignored: running the
+ * call as the forwarder instead would silently widen it to the forwarder's
+ * access. An anonymous route principal cannot forward, since no one is
+ * accountable for the assertion. A malformed or oversized header is a 400.
+ */
+export async function resolveMcpRequestPrincipals(
+ request: Request,
+ routePrincipal: SessionAuthContext,
+ trustedForwarders: TrustedForwarders | undefined,
+): Promise<McpRequestPrincipals | Response> {
+ const header = request.headers.get(FORWARDED_PRINCIPAL_HEADER);
+ if (header === null) return { current: routePrincipal, initiator: routePrincipal };
+ if (trustedForwarders === undefined) {
+ return failure(403, "This deployment does not accept a forwarded principal.");
+ }
+ if (routePrincipal.principalType === "anonymous") {
+ return failure(403, "An anonymous caller cannot forward a principal. Authenticate it.");
+ }
+ const decoded = decodeHeader(header);
+ if (typeof decoded === "string") return failure(400, decoded);
+
+ const resolved = await resolveForwardedPrincipal({
+ forwarder: routePrincipal,
+ payload: { forwardedPrincipal: decoded.value },
+ trustedForwarders,
+ });
+ if (resolved instanceof Response) return resolved;
+ if (!resolved.accepted) return { current: routePrincipal, initiator: routePrincipal };
+ // resolveForwardedPrincipal already stamped both with `eve:forwarded-by`.
+ return { current: resolved.auth, initiator: resolved.initiatorAuth };
+}
+
+/**
+ * Encodes a principal for the header, failing before the request when the
+ * receiving channel would refuse it as oversized.
+ */
+export function encodeForwardedPrincipalHeader(
+ principal: ForwardedPrincipal,
+ connectionName: string,
+): string {
+ const encoded = Buffer.from(JSON.stringify(principal), "utf8").toString("base64url");
+ if (encoded.length > FORWARDED_PRINCIPAL_HEADER_MAX_BYTES) {
+ throw new Error(
+ `Connection "${connectionName}" cannot forward the caller's principal: the ` +
+ `${FORWARDED_PRINCIPAL_HEADER} header would be ${encoded.length} bytes, over the ` +
+ `${FORWARDED_PRINCIPAL_HEADER_MAX_BYTES}-byte limit. Trim the principal's attributes.`,
+ );
+ }
+ return encoded;
+}
+
+/** Unpadded base64url of UTF-8 JSON, at most 16 KiB encoded; a string is the failure. */
+function decodeHeader(value: string): { readonly value: unknown } | string {
+ if (value.length > FORWARDED_PRINCIPAL_HEADER_MAX_BYTES) {
+ return `The ${FORWARDED_PRINCIPAL_HEADER} header must be at most ${FORWARDED_PRINCIPAL_HEADER_MAX_BYTES} bytes.`;
+ }
+ if (!BASE64URL_UNPADDED.test(value) || value.length % 4 === 1) {
+ return `The ${FORWARDED_PRINCIPAL_HEADER} header must be unpadded base64url.`;
+ }
+ try {
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(value, "base64url"));
+ return { value: JSON.parse(text) as unknown };
+ } catch {
+ return `The ${FORWARDED_PRINCIPAL_HEADER} header must encode UTF-8 JSON.`;
+ }
+}
+
+function failure(status: 400 | 403, error: string): Response {
+ return Response.json({ error, ok: false }, { status });
+}
diff --git a/packages/eve/src/internal/mcp/published-tools.ts b/packages/eve/src/internal/mcp/published-tools.ts
index ec939afa8..f19e4f763 100644
--- a/packages/eve/src/internal/mcp/published-tools.ts
+++ b/packages/eve/src/internal/mcp/published-tools.ts
@@ -3,6 +3,7 @@ import { fromJsonSchema } from "#compiled/@modelcontextprotocol/server/index.js"
import type { AgentToolDescription } from "#channel/agent-description.js";
import type { InvokeToolFn, InvokeToolResult } from "#channel/invoke-tool.js";
import { createLogger } from "#internal/logging.js";
+import type { McpRequestPrincipals } from "#internal/mcp/forwarded-principal-header.js";
import {
defineMcpTool,
McpToolOperationError,
@@ -16,11 +17,13 @@ const warnedReserved = new Set<string>();
/**
* The agent's invocable tools as MCP tools. Each `tools/call` runs the tool
- * through `invokeTool` as the route-authenticated caller. Tools named like
- * one in `reserved` are skipped, since the channel serves that name itself.
+ * through `invokeTool` as `principals`: the route-authenticated caller, or the
+ * user a trusted forwarder named. Tools named like one in `reserved` are
+ * skipped, since the channel serves that name itself.
*/
export function createPublishedTools(input: {
readonly invokeTool: InvokeToolFn;
+ readonly principals: McpRequestPrincipals;
readonly reserved: ReadonlySet<string>;
readonly tools: readonly AgentToolDescription[];
}): McpServerTool[] {
@@ -44,11 +47,13 @@ export function createPublishedTools(input: {
outputSchema:
tool.outputSchema === undefined ? undefined : fromJsonSchema(tool.outputSchema),
},
- async call(value, { auth, signal }) {
- if (auth === null) {
- throw new McpToolOperationError("denied", "The channel authenticated no caller.");
- }
- const result = await input.invokeTool(tool.name, value, { auth, signal });
+ async call(value, { signal }) {
+ const { current, initiator } = input.principals;
+ const result = await input.invokeTool(tool.name, value, {
+ auth: current,
+ initiator,
+ signal,
+ });
return toCallToolResult(tool.name, result, tool.outputSchema !== undefined);
},
}),
diff --git a/packages/eve/src/public/channels/mcp.test.ts b/packages/eve/src/public/channels/mcp.test.ts
index e1a9c39fd..bbad7b8bd 100644
--- a/packages/eve/src/public/channels/mcp.test.ts
+++ b/packages/eve/src/public/channels/mcp.test.ts
@@ -11,7 +11,7 @@ import {
} from "#internal/nitro/routes/channel-route-context.js";
import { MCP_PROTOCOL_VERSION } from "#internal/mcp/streamable-http-server.js";
import { ForbiddenError, none, oauthResource, withAuthChallenges } from "#public/channels/auth.js";
-import { mcpChannel } from "#public/channels/mcp.js";
+import { mcpChannel, type McpChannelInput } from "#public/channels/mcp.js";
import { mockAgentRouteArgs } from "#internal/testing/mocks/mock-route-args.js";
const MCP_LEGACY_PROTOCOL_VERSION = "2025-11-25";
@@ -627,11 +627,108 @@ describe("mcpChannel tools", () => {
}
expect(invokeTool).toHaveBeenCalledWith(name, args, {
auth: principal,
+ initiator: principal,
signal: expect.any(AbortSignal),
});
}
});
+ it("runs published tools as the user a trusted forwarder names, and agent_* as the forwarder", async () => {
+ const alice: SessionAuthContext = {
+ attributes: { team: "équipe" },
+ authenticator: "oidc",
+ principalId: "alice",
+ principalType: "user",
+ };
+ const encode = (text: string) => Buffer.from(text).toString("base64url");
+ const bob: SessionAuthContext = { ...alice, attributes: {}, principalId: "bob" };
+ const json = JSON.stringify({ current: alice });
+ const valid = encode(json);
+ const withInitiator = encode(JSON.stringify({ current: alice, initiator: bob }));
+ // Unpadded base64url of 12,288 bytes is exactly the 16 KiB cap; JSON whitespace pads it.
+ const sized = (bytes: number) => encode(json + " ".repeat(bytes - Buffer.byteLength(json)));
+ const trusted = {
+ trustedForwarders: (forwarder: SessionAuthContext) => forwarder === principal,
+ };
+ const forwardedAlice = {
+ ...alice,
+ attributes: { ...alice.attributes, "eve:forwarded-by": "user-1" },
+ };
+ const forwardedBob = { ...bob, attributes: { "eve:forwarded-by": "user-1" } };
+ function post(
+ options: Partial<McpChannelInput>,
+ header: string | undefined,
+ tool: string,
+ overrides: { createSession?: () => Promise<never>; invokeTool?: InvokeToolFn },
+ ) {
+ const args = routeArgs(overrides.createSession, {
+ describe: async () => ({ name: "compiled-agent", tools: [note] }),
+ invokeTool: overrides.invokeTool,
+ });
+ const route = mcpChannel({ auth: () => principal, tools: true, ...options }).routes[1]!;
+ if (route.transport === "websocket") throw new Error("expected HTTP route");
+ const params = { arguments: tool === "agent_start" ? { message: "hi" } : {}, name: tool };
+ const body = { id: 1, jsonrpc: "2.0", method: "tools/call", params };
+ return route.handler(
+ mcpRequest(body, header ? { "eve-forwarded-principal": header } : {}),
+ args,
+ );
+ }
+ // [label, header, channel options, expected status or the [current, initiator] the tool runs as, error]
+ type Ran = readonly [object, object];
+ const rows: Array<[string, string?, Partial<McpChannelInput>?, (number | Ran)?, string?]> = [
+ ["no header", undefined, trusted, [principal, principal]],
+ ["a valid header", valid, trusted, [forwardedAlice, forwardedAlice]],
+ ["a header naming an initiator", withInitiator, trusted, [forwardedAlice, forwardedBob]],
+ ["a header at the 16 KiB cap", sized(12_288), trusted, [forwardedAlice, forwardedAlice]],
+ ["a padded header", `${valid}=`, trusted, 400, "unpadded base64url"],
+ ["not a principal", encode('{"current":{}}'), trusted, 400, "Invalid forwardedPrincipal"],
+ ["a header over 16 KiB", sized(12_289), trusted, 400, "at most 16384 bytes"],
+ ["an untrusted forwarder", valid, { trustedForwarders: () => false }, 403, "not authorized"],
+ [
+ "an anonymous forwarder",
+ valid,
+ { auth: none(), trustedForwarders: () => true },
+ 403,
+ "anonymous",
+ ],
+ [
+ "no trustedForwarders",
+ valid,
+ {},
+ 403,
+ "This deployment does not accept a forwarded principal.",
+ ],
+ ];
+ for (const [label, header, options, expected, error] of rows) {
+ const invokeTool = vi.fn<InvokeToolFn>(async () => ({
+ modelOutput: { type: "text", value: "ok" },
+ output: "ok",
+ status: "completed",
+ }));
+ const response = await post(options!, header, "note", { invokeTool });
+ if (typeof expected === "number") {
+ expect(response.status, label).toBe(expected);
+ expect(((await response.json()) as { error: string }).error, label).toContain(error);
+ expect(invokeTool, label).not.toHaveBeenCalled();
+ continue;
+ }
+ expect(response.status, label).toBe(200);
+ const [auth, initiator] = expected as Ran;
+ expect(invokeTool.mock.calls[0]![2], label).toEqual({
+ auth,
+ initiator,
+ signal: expect.any(AbortSignal),
+ });
+ }
+
+ const createSession = vi.fn(async (_input: unknown) => {
+ throw new Error("stop after createSession");
+ });
+ await post(trusted, valid, "agent_start", { createSession: createSession as never });
+ expect(createSession.mock.calls[0]![0]).toMatchObject({ auth: principal });
+ });
+
it("checks arguments against the tool's JSON schema before invoking it", async () => {
const invokeTool = vi.fn<InvokeToolFn>();
const rpc = serve({ tools: true }, invokeTool);
diff --git a/packages/eve/src/public/channels/mcp.ts b/packages/eve/src/public/channels/mcp.ts
index deb0067e7..ad015356c 100644
--- a/packages/eve/src/public/channels/mcp.ts
+++ b/packages/eve/src/public/channels/mcp.ts
@@ -17,6 +17,12 @@ import type {
import { WorkflowAgentInvocationExecution } from "#internal/invocation/workflow-execution.js";
import { resolveInstalledPackageInfo } from "#internal/application/package.js";
import { createPublishedTools } from "#internal/mcp/published-tools.js";
+import {
+ resolveMcpRequestPrincipals,
+ type McpRequestPrincipals,
+} from "#internal/mcp/forwarded-principal-header.js";
+import type { TrustedForwarders } from "#channel/forwarded-principal.js";
+import type { SessionAuthContext } from "#channel/types.js";
import { validateMcpHttpRequest, validateMcpMetadataRequest } from "#internal/mcp/http-security.js";
import {
createMcpStreamableHttpServer,
@@ -60,6 +66,16 @@ export interface McpChannelInput {
* @default false
*/
readonly tools?: boolean;
+ /**
+ * Lets a route-authenticated forwarder, such as another eve agent's
+ * `forwardPrincipal` connection, run the published tools as a user it names
+ * in the `eve-forwarded-principal` header. Receives the verified forwarder
+ * and what it asserts, as eveChannel's `trustedForwarders` does; match the
+ * forwarder precisely. Accepted principals carry the forwarder's id as the
+ * `eve:forwarded-by` attribute. `agent_*` tools still act as the route
+ * caller. Omit to refuse any request carrying the header with 403.
+ */
+ readonly trustedForwarders?: TrustedForwarders;
}
/** Public MCP channel publishing this agent's `agent_*` tools and, optionally, its own tools. */
@@ -85,23 +101,9 @@ export function mcpChannel(input: McpChannelInput): McpChannel {
}
const path = input.route ?? "/eve/v1/mcp";
const oauth = readOAuthResourceOptions(input.auth);
- const routes = [
- GET(
- path,
- async (request, args) =>
- await authenticateMcpRequest(request, args, input.auth, oauth, publish),
- ),
- POST(
- path,
- async (request, args) =>
- await authenticateMcpRequest(request, args, input.auth, oauth, publish),
- ),
- DELETE(
- path,
- async (request, args) =>
- await authenticateMcpRequest(request, args, input.auth, oauth, publish),
- ),
- ];
+ const handle = async (request: Request, args: RouteHandlerArgs) =>
+ await authenticateMcpRequest(request, args, input, oauth, publish);
+ const routes = [GET(path, handle), POST(path, handle), DELETE(path, handle)];
if (oauth !== undefined) {
routes.unshift(...protectedResourceMetadataRoutes(oauth, path));
}
@@ -347,17 +349,19 @@ function readChallengeScheme(value: string): string | undefined {
async function authenticateMcpRequest(
request: Request,
args: RouteHandlerArgs,
- policy: AuthFn<Request> | readonly AuthFn<Request>[],
+ input: McpChannelInput,
oauth: OAuthResourceOptions | undefined,
publish: McpPublishOptions,
): Promise<Response> {
const securityFailure = validateMcpHttpRequest(request);
if (securityFailure !== undefined) return securityFailure;
- const auth = await routeAuth(request, policy);
+ const auth = await routeAuth(request, input.auth);
if (auth instanceof Response) {
return oauth === undefined ? auth : addResourceChallenge(auth, request, oauth);
}
- return await handleMcpRequest(request, args, auth, publish);
+ const principals = await resolveMcpRequestPrincipals(request, auth, input.trustedForwarders);
+ if (principals instanceof Response) return principals;
+ return await handleMcpRequest(request, args, auth, principals, publish);
}
interface McpPublishOptions {
@@ -368,7 +372,8 @@ interface McpPublishOptions {
async function handleMcpRequest(
request: Request,
args: RouteHandlerArgs,
- auth: import("#channel/types.js").SessionAuthContext,
+ auth: SessionAuthContext,
+ principals: McpRequestPrincipals,
publish: McpPublishOptions,
): Promise<Response> {
const createSession = readRouteSessionCreator(args);
@@ -405,6 +410,7 @@ async function handleMcpRequest(
const publishedTools = publish.tools
? createPublishedTools({
invokeTool: args.invokeTool,
+ principals,
reserved: new Set(agentTools.map((tool) => tool.name)),
tools: (await args.describe()).tools,
})
diff --git a/packages/eve/src/public/definitions/connections/mcp.ts b/packages/eve/src/public/definitions/connections/mcp.ts
index e9c714d10..f70ce5e3e 100644
--- a/packages/eve/src/public/definitions/connections/mcp.ts
+++ b/packages/eve/src/public/definitions/connections/mcp.ts
@@ -34,6 +34,17 @@ export interface McpClientConnectionDefinition {
* initialize handshake; that handshake still negotiates a supported version.
*/
readonly protocolVersionDiscovery?: boolean;
+ /**
+ * Whether to forward the calling turn's user and initiator to the server in
+ * the `eve-forwarded-principal` header, so an eve agent's `mcpChannel` can
+ * run its published tools as that user. The server must set
+ * `trustedForwarders` and trust this connection's route-authenticated
+ * identity; otherwise it refuses the request with 403. Anonymous callers
+ * are not forwarded. Requests carrying the header fail rather than follow
+ * a redirect.
+ * @default false
+ */
+ readonly forwardPrincipal?: boolean;
/**
* Human-readable summary of the connection and its tools.
*
diff --git a/packages/eve/src/runtime/connections/mcp-client.test.ts b/packages/eve/src/runtime/connections/mcp-client.test.ts
index 9703439ac..acd052fc1 100644
--- a/packages/eve/src/runtime/connections/mcp-client.test.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.test.ts
@@ -1,7 +1,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 { AuthKey, InitiatorAuthKey, SessionKey, type SessionAuthContext } from "#context/keys.js";
import {
ConnectionAuthorizationRequiredError,
isConnectionAuthorizationFailedError,
@@ -181,6 +181,43 @@ describe("McpConnectionClient", () => {
);
});
+ it("with forwardPrincipal, sends the turn's user in a header that refuses redirects", async () => {
+ createMCPClient.mockResolvedValue({ close: vi.fn() });
+ await new McpConnectionClient(makeConnection({ forwardPrincipal: true })).connect();
+ const fetch: typeof globalThis.fetch = createMCPClient.mock.calls[0]![0].transport.fetch;
+ const sent = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response(null));
+ const send = (auth: SessionAuthContext | null) =>
+ contextStorage.run(ctxWithAuth(auth), () => fetch("https://mcp.example.com", {}));
+ try {
+ await send(userAuth("alice"));
+ const init = sent.mock.calls[0]![1]!;
+ const header = new Headers(init.headers).get("eve-forwarded-principal")!;
+ expect(JSON.parse(Buffer.from(header, "base64url").toString())).toEqual({
+ current: userAuth("alice"),
+ });
+ expect(init.redirect).toBe("error");
+
+ await send({ ...userAuth("anon"), principalType: "anonymous" });
+ expect(sent.mock.calls[1]![1]).toEqual({});
+
+ const delegated = ctxWithAuth(userAuth("alice"));
+ delegated.set(InitiatorAuthKey, userAuth("bob"));
+ await contextStorage.run(delegated, () => fetch("https://mcp.example.com", {}));
+ const delegatedHeader = new Headers(sent.mock.calls[2]![1]!.headers).get(
+ "eve-forwarded-principal",
+ )!;
+ expect(JSON.parse(Buffer.from(delegatedHeader, "base64url").toString())).toEqual({
+ current: userAuth("alice"),
+ initiator: userAuth("bob"),
+ });
+
+ const large = { ...userAuth("alice"), attributes: { blob: "a".repeat(16 * 1024) } };
+ await expect(send(large)).rejects.toThrow(/Connection "test" cannot forward.*16384-byte/u);
+ } finally {
+ sent.mockRestore();
+ }
+ });
+
it("creates an HTTP MCP client with resolved connection headers", async () => {
const client = {
close: vi.fn(),
diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.ts
index 73c3b7195..5bc2240c1 100644
--- a/packages/eve/src/runtime/connections/mcp-client.ts
+++ b/packages/eve/src/runtime/connections/mcp-client.ts
@@ -11,6 +11,11 @@ import type { ResolvedConnectionDefinition } from "#runtime/types.js";
import { evictScopedToken, resolveScopedToken } from "#runtime/connections/scoped-authorization.js";
import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";
import { isObject } from "#shared/guards.js";
+import { readTurnPrincipals } from "#context/turn-principals.js";
+import {
+ encodeForwardedPrincipalHeader,
+ FORWARDED_PRINCIPAL_HEADER,
+} from "#internal/mcp/forwarded-principal-header.js";
import {
omitProvidedArgumentsFromSchema,
resolveProvidedArguments,
@@ -94,6 +99,7 @@ export class McpConnectionClient implements ConnectionClient {
const url = this.#connection.url;
const fetch = createMcpTraceFetch({
connectionName: this.#connection.connectionName,
+ fetcher: this.#forwardingFetch(),
getProtocolVersion: () => this.#client?.initializeResult?.protocolVersion,
});
@@ -113,6 +119,29 @@ export class McpConnectionClient implements ConnectionClient {
}
}
+ /**
+ * With `forwardPrincipal`, adds `eve-forwarded-principal` to every request,
+ * read per request: one client can serve turns from different people in a
+ * shared session.
+ */
+ #forwardingFetch(): typeof fetch | undefined {
+ if (this.#connection.forwardPrincipal !== true) return undefined;
+ const connectionName = this.#connection.connectionName;
+ return async (request, init) => {
+ const principals = readTurnPrincipals();
+ if (principals === undefined) return await globalThis.fetch(request, init);
+ const headers = new Headers(init?.headers);
+ headers.set(
+ FORWARDED_PRINCIPAL_HEADER,
+ encodeForwardedPrincipalHeader(principals, connectionName),
+ );
+ // Fetch keeps custom headers across a cross-origin redirect, unlike
+ // `Authorization`, so following one would hand the user's identity to
+ // another host.
+ return await globalThis.fetch(request, { ...init, headers, redirect: "error" });
+ };
+ }
+
/**
* Returns cached tool metadata for all tools this connection exposes,
* after applying any configured tool filter.
diff --git a/packages/eve/src/runtime/resolve-connection.ts b/packages/eve/src/runtime/resolve-connection.ts
index e3ec6a937..772b1fa8e 100644
--- a/packages/eve/src/runtime/resolve-connection.ts
+++ b/packages/eve/src/runtime/resolve-connection.ts
@@ -76,6 +76,7 @@ export async function resolveConnectionDefinition(
logicalPath: string;
protocol: ResolvedConnectionDefinition["protocol"];
protocolVersionDiscovery?: boolean;
+ forwardPrincipal?: boolean;
sourceId: string;
sourceKind: "module";
spec?: ResolvedConnectionDefinition["spec"];
@@ -126,6 +127,13 @@ export async function resolveConnectionDefinition(
result.protocolVersionDiscovery = resolvedRecord.protocolVersionDiscovery;
}
+ if (definition.protocol === "mcp" && resolvedRecord.forwardPrincipal !== undefined) {
+ if (typeof resolvedRecord.forwardPrincipal !== "boolean") {
+ throw new Error('"forwardPrincipal" must be a boolean.');
+ }
+ result.forwardPrincipal = resolvedRecord.forwardPrincipal;
+ }
+
if (hasHeaders) {
result.headers = resolvedRecord.headers as Readonly<HeadersDefinition>;
}
@@ -230,6 +238,7 @@ export function resolveDynamicConnectionValue(
sourceKind: "module" as const,
toolCall: normalized.toolCall,
protocolVersionDiscovery: normalized.protocolVersionDiscovery,
+ forwardPrincipal: normalized.forwardPrincipal,
tools: normalized.tools,
url: normalized.url,
});
diff --git a/packages/eve/src/runtime/types.ts b/packages/eve/src/runtime/types.ts
index 840987a1c..25ae1b2bc 100644
--- a/packages/eve/src/runtime/types.ts
+++ b/packages/eve/src/runtime/types.ts
@@ -101,6 +101,8 @@ export type ResolvedScheduleDefinition = Readonly<
*/
export interface ResolvedConnectionDefinition extends ResolvedModuleSourceRef {
readonly protocolVersionDiscovery?: boolean;
+ /** MCP only: send the turn's principals in `eve-forwarded-principal`. */
+ readonly forwardPrincipal?: boolean;
readonly approval?: Approval;
readonly authorization?: Readonly<AuthorizationDefinition> | ConnectionAuthResolver;
readonly connectionName: string;