Typescript sdk

Request Context

Copy page

Pass dynamic context to your agents via HTTP headers for personalized interactions

Overview

Request context allows you to pass request-specific values (like user IDs, authentication tokens, or organization metadata) to your agent graph at runtime via HTTP headers. These values are validated, cached per conversation, and made available throughout your agent system for:

  • Context Fetchers: Dynamic data retrieval based on request values
  • External Tools: Authentication and personalization for API calls
  • Agent Prompts: Personalized responses using context variables

Passing request context via headers

Include context values as HTTP headers when calling your agent API. These headers are validated against your configured schema and cached for the conversation.

curl -N \
  -X POST "http://localhost:3003/api/chat" \
  -H "Authorization: Bearer $INKEEP_API_KEY" \
  -H "user_id: u_123" \
  -H "auth_token: t_abc" \
  -H "org_name: Acme Corp" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [ { "role": "user", "content": "What can you help me with?" } ],
    "conversationId": "conv-123"
  }'
Note
Note

Header keys are normalized to lowercase. Define them as lowercase in your schema and reference them as lowercase in templates.

Configuring request context

Define a schema for your request context and configure how it's used in your agent graph.

import { z } from "zod";
import { agent, agentGraph, contextConfig, fetchDefinition } from "@inkeep/agents-manage-api/builders";

// Define schema for expected headers (use lowercase keys)
const requestSchema = z.object({
  user_id: z.string(),
  auth_token: z.string(),
  org_name: z.string().optional()
});

// Create a context fetcher that uses request values
const userFetcher = fetchDefinition({
  id: "user-info",
  name: "User Information",
  trigger: "initialization",
  fetchConfig: {
    url: "https://api.example.com/users/{{requestContext.user_id}}",
    method: "GET",
    headers: {
      Authorization: "Bearer {{requestContext.auth_token}}",
    },
    transform: "name"  // Extract the 'name' field from response
  },
  responseSchema: z.string(),
  defaultValue: "Guest User"
});

// Configure context for your graph
const userContext = contextConfig({
  id: "user-context",
  name: "User Context",
  description: "User personalization context",
  requestContextSchema: requestSchema,
  contextVariables: {
    userName: userFetcher,
  },
});

// Create an agent that uses context variables
const personalAssistant = agent({
  id: "personal-assistant",
  name: "Personal Assistant",
  description: "Personalized AI assistant",
  prompt: `You are a helpful assistant for {{userName}} from {{requestContext.org_name}}.
  
  User ID: {{requestContext.user_id}}
  
  Provide personalized assistance based on their context.`,
});

// Attach context to your graph
const graph = agentGraph({
  id: "personal-graph",
  name: "Personal Assistant Graph",
  defaultAgent: personalAssistant,
  agents: () => [personalAssistant],
  contextConfig: userContext,
});

How it works

Validation: Headers are validated against your configured schema when a request arrives

Caching: Validated context is cached per conversation for reuse across multiple interactions

Reuse: Subsequent requests with the same conversationId automatically use cached context values

Updates: Provide new header values to update the context for an ongoing conversation

Tip
Tip

Context values persist across conversation turns. To update them, send new header values with the same conversation ID.

Using request context in your agents

Request context values are available throughout your agent system using template syntax {{requestContext.field_name}}:

In Context Fetchers

Use request values to fetch dynamic data from external APIs:

const userDataFetcher = fetchDefinition({
  id: "user-data",
  name: "User Data",
  fetchConfig: {
    url: "https://api.example.com/users/{{requestContext.user_id}}/profile",
    headers: {
      Authorization: "Bearer {{requestContext.auth_token}}",
      "X-Organization": "{{requestContext.org_name}}"
    },
    body: {
      includePreferences: true,
      userId: "{{requestContext.user_id}}"
    }
  }
});

In Agent Prompts

Reference context directly in agent prompts for personalization:

const agent = agent({
  prompt: `You are an assistant for {{userName}} from {{requestContext.org_name}}.
  
  User context:
  - ID: {{requestContext.user_id}}
  - Organization: {{requestContext.org_name}}
  
  Provide help tailored to their organization's needs.`
});

In External Tools

Configure external agents or MCP servers with dynamic headers:

const externalAgent = externalAgent({
  id: "external-service",
  baseUrl: "https://external.api.com",
  headers: {
    Authorization: "Bearer {{requestContext.auth_token}}",
    "X-User-Context": "{{requestContext.user_id}}",
    "X-Org": "{{requestContext.org_name}}"
  }
});

Best practices

  • Use lowercase keys: Always define schema properties in lowercase and reference them as lowercase in templates
  • Validate early: Test your schema configuration with sample headers before deploying
  • Cache wisely: Remember that context persists per conversation - design accordingly
  • Secure sensitive data: For long-lived secrets, use the Credentials system instead of request context
  • Keep it minimal: Only include context values that are actually needed by your agents

Common use cases

Multi-tenant applications

Pass tenant-specific configuration to customize agent behavior per customer:

// Headers
"tenant_id: acme-corp"
"tenant_plan: enterprise"
"tenant_features: advanced-analytics,custom-branding"

User authentication

Provide user identity and session information for personalized interactions:

// Headers
"user_id: user_123"
"user_role: admin"
"session_token: sk_live_..."

API gateway integration

Forward headers from your API gateway for consistent authentication:

// Headers
"x-api-key: your-api-key"
"x-request-id: req_abc123"
"x-client-version: 2.0.0"

Troubleshooting

Invalid request context errors

If you receive a 400 error about invalid request context:

  1. Verify your schema matches the headers you're sending
  2. Ensure all header keys are lowercase
  3. Check that required fields are present
  4. Validate the data types match your schema

Context not persisting

If context values aren't available in subsequent requests:

  1. Ensure you're using the same conversationId across requests
  2. Verify headers are being sent correctly
  3. Check that your context config is properly attached to the graph