Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .changeset/expose-request-headers-dynamic-agents.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
---
"@voltagent/core": patch
"@voltagent/server-core": patch
"@voltagent/server-hono": patch
"@voltagent/server-elysia": patch
"@voltagent/serverless-hono": patch
---

feat(agent): expose request headers to dynamic agent configuration

Dynamic `instructions`, `model`, and `tools` functions now receive a `headers` map in
`DynamicValueOptions` when an agent is called through the built-in HTTP endpoints. This makes it
possible to configure tenant-aware models and request-scoped tools from headers such as
`authorization`, `x-tenant-id`, or `x-user-id` without manually copying them into
`options.context`.

Header names are normalized to lowercase:

```ts
const agent = new Agent({
name: "Tenant Agent",
instructions: "You are a tenant-aware assistant.",
model: ({ headers }) => {
return headers?.["x-tenant-id"] === "enterprise" ? "openai/gpt-4o" : "openai/gpt-4o-mini";
},
tools: ({ headers }) => {
return headers?.authorization ? [createTenantTool(headers.authorization)] : [];
},
});
```

For direct in-process calls, pass `requestHeaders`:

```ts
await agent.generateText("Hello", {
requestHeaders: {
authorization: "Bearer token",
"x-tenant-id": "tenant-1",
},
});
```

Fixes #1201
8 changes: 8 additions & 0 deletions packages/core/src/agent/agent.spec-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ describe("Agent Type System", () => {
// Dynamic model function
const dynamicModelFn: DynamicValue<AgentModelReference> = async (options) => {
expectTypeOf(options.context).toMatchTypeOf<Map<string | symbol, unknown>>();
expectTypeOf(options.headers).toMatchTypeOf<Record<string, string> | undefined>();
return mockModel;
};

Expand Down Expand Up @@ -257,6 +258,7 @@ describe("Agent Type System", () => {
// Dynamic value function
const dynamicInstructions: InstructionsDynamicValue = async (options) => {
expectTypeOf(options).toMatchTypeOf<{ context?: UserContext }>();
expectTypeOf(options.headers).toMatchTypeOf<Record<string, string> | undefined>();
return "Dynamic instructions";
};
expectTypeOf(dynamicInstructions).toMatchTypeOf<InstructionsDynamicValue>();
Expand All @@ -277,6 +279,7 @@ describe("Agent Type System", () => {
// Dynamic model
const dynamicModel: ModelDynamicValue<ModelRouterModelId> = async (options) => {
expectTypeOf(options).toMatchTypeOf<{ context?: UserContext }>();
expectTypeOf(options.headers).toMatchTypeOf<Record<string, string> | undefined>();
return "openai/gpt-4o-mini";
};
expectTypeOf(dynamicModel).toMatchTypeOf<ModelDynamicValue<ModelRouterModelId>>();
Expand Down Expand Up @@ -311,6 +314,7 @@ describe("Agent Type System", () => {
// Dynamic tools
const dynamicTools: ToolsDynamicValue = async (options) => {
expectTypeOf(options).toMatchTypeOf<{ context?: UserContext }>();
expectTypeOf(options.headers).toMatchTypeOf<Record<string, string> | undefined>();
return [tool];
};
expectTypeOf(dynamicTools).toMatchTypeOf<ToolsDynamicValue>();
Expand Down Expand Up @@ -430,6 +434,10 @@ describe("Agent Type System", () => {
maxSteps: 5,
signal: new AbortSignal(),
context: new Map(),
requestHeaders: {
authorization: "Bearer token",
"x-tenant-id": "tenant-1",
},
};

const legacyOptions: PublicGenerateOptions = {
Expand Down
49 changes: 49 additions & 0 deletions packages/core/src/agent/agent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4672,6 +4672,55 @@ Use pandas and summarize findings.`.split("\n"),
expect(systemMessage.content).toContain("Use markdown to format your answers");
});

it("should expose request headers to dynamic model, tools, and instructions", async () => {
const requestHeaders = {
authorization: "Bearer test-token",
"x-tenant-id": "tenant-1",
};
const dynamicInstructions = vi.fn().mockResolvedValue("Dynamic content");
const dynamicModel = vi.fn().mockResolvedValue(mockModel as any);
const dynamicTools = vi.fn().mockResolvedValue([]);

const agent = new Agent({
name: "TestAgent",
instructions: dynamicInstructions,
model: dynamicModel,
tools: dynamicTools,
});

vi.mocked(ai.generateText).mockResolvedValue({
text: "Response",
content: [{ type: "text", text: "Response" }],
reasoning: [],
files: [],
sources: [],
toolCalls: [],
toolResults: [],
finishReason: "stop",
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
warnings: [],
request: {},
response: {
id: "test",
modelId: "test-model",
timestamp: new Date(),
messages: [],
},
steps: [],
} as any);

await agent.generateText("Hello", {
requestHeaders,
});

expect(dynamicInstructions.mock.calls[0][0].headers).toEqual(requestHeaders);
expect(dynamicModel.mock.calls[0][0].headers).toEqual(requestHeaders);
expect(dynamicTools.mock.calls[0][0].headers).toEqual(requestHeaders);

const callArgs = vi.mocked(ai.generateText).mock.calls[0][0] as Record<string, unknown>;
expect(callArgs.requestHeaders).toBeUndefined();
});

it("should add retriever context correctly through enrichInstructions", async () => {
// Create mock retriever
const mockRetriever = {
Expand Down
16 changes: 16 additions & 0 deletions packages/core/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,14 @@ export interface BaseGenerationOptions<TProviderOptions extends ProviderOptions
*/
conversationId?: string;
context?: ContextInput;
/**
* HTTP request headers associated with this call.
*
* Server adapters populate this from the incoming request and expose it to
* dynamic `model`, `instructions`, and `tools` callbacks as `headers`.
* This is separate from AI SDK/provider `headers`.
*/
requestHeaders?: Record<string, string>;
elicitation?: (request: unknown) => Promise<unknown>;

// Parent tracking
Expand Down Expand Up @@ -1259,6 +1267,7 @@ export class Agent {
conversationId,
memory: _memory,
context, // Explicitly exclude to prevent collision with AI SDK's future 'context' field
requestHeaders: _requestHeaders,
parentAgentId,
parentOperationContext,
hooks,
Expand Down Expand Up @@ -1877,6 +1886,7 @@ export class Agent {
conversationId,
memory: _memory,
context, // Explicitly exclude to prevent collision with AI SDK's future 'context' field
requestHeaders: _requestHeaders,
parentAgentId,
parentOperationContext,
hooks,
Expand Down Expand Up @@ -2780,6 +2790,7 @@ export class Agent {
conversationId,
memory: _memory,
context, // Explicitly exclude to prevent collision with AI SDK's future 'context' field
requestHeaders: _requestHeaders,
parentAgentId,
parentOperationContext,
hooks,
Expand Down Expand Up @@ -3153,6 +3164,7 @@ export class Agent {
conversationId,
memory: _memory,
context, // Explicitly exclude to prevent collision with AI SDK's future 'context' field
requestHeaders: _requestHeaders,
parentAgentId,
parentOperationContext,
hooks,
Expand Down Expand Up @@ -4058,6 +4070,7 @@ export class Agent {
return {
operationId,
context,
requestHeaders: options?.requestHeaders ?? options?.parentOperationContext?.requestHeaders,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Normalize direct-call requestHeaders before storing them.

Server adapters may already lowercase names, but direct in-process calls can pass mixed-case keys. Store normalized keys here so headers["x-tenant-id"] behaves consistently across all entrypoints.

🐛 Proposed fix
-      requestHeaders: options?.requestHeaders ?? options?.parentOperationContext?.requestHeaders,
+      requestHeaders:
+        options?.requestHeaders !== undefined
+          ? Object.fromEntries(
+              Object.entries(options.requestHeaders).map(([name, value]) => [
+                name.toLowerCase(),
+                value,
+              ]),
+            )
+          : options?.parentOperationContext?.requestHeaders,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
requestHeaders: options?.requestHeaders ?? options?.parentOperationContext?.requestHeaders,
requestHeaders:
options?.requestHeaders !== undefined
? Object.fromEntries(
Object.entries(options.requestHeaders).map(([name, value]) => [
name.toLowerCase(),
value,
]),
)
: options?.parentOperationContext?.requestHeaders,
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/agent/agent.ts` at line 4073, Normalize any direct-call
request headers before storing: where the code currently assigns requestHeaders:
options?.requestHeaders ?? options?.parentOperationContext?.requestHeaders,
transform the chosen headers object so all header keys are lowercased (e.g., map
keys to key.toLowerCase()) and use that normalized object instead. Update the
assignment logic (referencing requestHeaders, options, and
parentOperationContext) to call the normalizer so downstream access like
headers["x-tenant-id"] is consistent across entrypoints.

systemContext,
isActive: true,
logger,
Expand Down Expand Up @@ -5080,6 +5093,7 @@ export class Agent {

const dynamicValueOptions: DynamicValueOptions = {
context: oc.context,
headers: oc.requestHeaders,
prompts: promptHelper,
};

Expand Down Expand Up @@ -5541,10 +5555,12 @@ export class Agent {
(this.prompts
? {
context: oc.context,
headers: oc.requestHeaders,
prompts: this.prompts,
}
: {
context: oc.context,
headers: oc.requestHeaders,
prompts: {
getPrompt: async () => ({ type: "text" as const, text: "" }),
},
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/agent/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,9 @@ export interface CommonGenerateOptions {
// Optional user-defined context to be passed from a parent operation
context?: UserContext;

// HTTP request headers associated with this generation call, when available.
requestHeaders?: Record<string, string>;
Comment on lines +1081 to +1082

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Normalize direct-call requestHeaders before storing them on OperationContext.

Server adapters normalize through server-core, but direct agent.generateText(..., { requestHeaders }) can pass mixed-case keys. Since agent.ts stores options?.requestHeaders directly before exposing it as DynamicValueOptions.headers, dynamic resolvers can see inconsistent casing across HTTP vs in-process calls.

🐛 Proposed implementation shape
+function normalizeRequestHeaders(
+  headers?: Record<string, string>,
+): Record<string, string> | undefined {
+  if (!headers) {
+    return undefined;
+  }
+
+  return Object.fromEntries(
+    Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]),
+  );
+}
+
 // In createOperationContext / operation context construction:
-      requestHeaders: options?.requestHeaders ?? options?.parentOperationContext?.requestHeaders,
+      requestHeaders: normalizeRequestHeaders(
+        options?.requestHeaders ?? options?.parentOperationContext?.requestHeaders,
+      ),

Also applies to: 1312-1313

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/agent/types.ts` around lines 1081 - 1082, OperationContext
currently stores options?.requestHeaders verbatim which allows mixed-case keys
from direct agent.generateText calls; normalize header names to a canonical form
(e.g., lower-case keys) before assigning to OperationContext so
DynamicValueOptions.headers always sees consistent casing. Update the code paths
that set OperationContext.requestHeaders (references: OperationContext,
agent.generateText, and where DynamicValueOptions.headers is read) to run a
small normalization helper that iterates options.requestHeaders and produces a
new Record<string,string> with normalized header keys, and apply the same
normalization in the other location mentioned (lines referencing the other
assignment around 1312-1313) so both HTTP/server-core flows and direct
in-process calls present headers with consistent casing.


// Optional hooks to be included only during the operation call and not persisted in the agent
hooks?: AgentHooks;
}
Expand Down Expand Up @@ -1306,6 +1309,9 @@ export type OperationContext = {
/** User-managed context map for this operation */
readonly context: Map<string | symbol, unknown>;

/** HTTP request headers associated with this operation, when available */
readonly requestHeaders?: Record<string, string>;

/** System-managed context map for internal operation tracking */
readonly systemContext: Map<string | symbol, unknown>;

Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/voltops/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export type PromptHelper = {
export interface DynamicValueOptions {
/** User context map */
context: Map<string | symbol, unknown>;
/** HTTP request headers for server-triggered agent calls, when available */
headers?: Record<string, string>;
/** Prompt helper (available when VoltOpsClient is configured) */
prompts: PromptHelper;
}
Expand Down
66 changes: 66 additions & 0 deletions packages/server-core/src/handlers/agent.handlers.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ToolDeniedError } from "@voltagent/core";
import { describe, expect, it, vi } from "vitest";
import { processAgentOptions } from "../utils/options";
import { handleChatStream, handleGenerateText } from "./agent.handlers";

describe("server-core: agent.handlers ClientHTTPError mapping", () => {
Expand Down Expand Up @@ -56,6 +57,71 @@ describe("server-core: agent.handlers ClientHTTPError mapping", () => {
error: "Model timeout",
});
});

it("handleGenerateText should pass request headers into agent options", async () => {
const logger = { error: vi.fn() } as any;

const mockAgent = {
generateText: vi.fn(async () => ({
text: "ok",
usage: undefined,
finishReason: "stop",
toolCalls: [],
toolResults: [],
feedback: null,
})),
} as any;

const deps = {
agentRegistry: {
getAgent: vi.fn(() => mockAgent),
},
} as any;

const headers = new Headers({
Authorization: "Bearer test-token",
"X-Tenant-ID": "tenant-1",
});

const res = await handleGenerateText(
"agent-1",
{ input: "hi" },
deps,
logger,
undefined,
headers,
);

expect(res.success).toBe(true);
expect(mockAgent.generateText).toHaveBeenCalledWith(
"hi",
expect.objectContaining({
requestHeaders: {
authorization: "Bearer test-token",
"x-tenant-id": "tenant-1",
},
}),
);
});
});

describe("server-core: processAgentOptions", () => {
it("processAgentOptions should lowercase Headers entries", () => {
const headers = new Headers();
vi.spyOn(headers, "entries").mockReturnValue(
[
["Authorization", "Bearer test-token"],
["X-Tenant-ID", "tenant-1"],
][Symbol.iterator]() as HeadersIterator<[string, string]>,
);

const options = processAgentOptions({ options: {} }, undefined, headers);

expect(options.requestHeaders).toEqual({
authorization: "Bearer test-token",
"x-tenant-id": "tenant-1",
});
});
});

describe("server-core: agent.handlers resumable memory envelope", () => {
Expand Down
Loading
Loading