AutoGen Tutorial (TypeScript): adding authentication for intermediate developers

By Cyprian AaronsUpdated 2026-04-21
autogenadding-authentication-for-intermediate-developerstypescript

This tutorial shows how to add authentication to an AutoGen TypeScript agent setup so your agents can call protected APIs without hardcoding secrets or shipping unauthenticated requests. You need this when your agent has to access internal services, user-scoped endpoints, or anything that requires bearer tokens, API keys, or signed headers.

What You'll Need

  • Node.js 18+
  • TypeScript 5+
  • An AutoGen TypeScript project installed with:
    • @autogenai/autogen
    • zod
  • An OpenAI API key for the LLM client
  • An auth token for the protected API you want the agent to call
  • A working TypeScript build setup with tsconfig.json
  • Basic familiarity with AutoGen agents, tools, and async/await

Step-by-Step

  1. Start by installing the packages and setting your environment variables. Keep secrets out of source code; use process.env for both model access and downstream API authentication.
npm install @autogenai/autogen zod
npm install -D typescript tsx @types/node
export OPENAI_API_KEY="your-openai-key"
export PROTECTED_API_TOKEN="your-api-token"
  1. Create a small authenticated HTTP client that injects the bearer token on every request. This is the part most teams get wrong: authentication should live in one place, not inside every tool function.
// auth-client.ts
export class AuthClient {
  constructor(private readonly token: string) {}

  async getJson<T>(url: string): Promise<T> {
    const response = await fetch(url, {
      headers: {
        Authorization: `Bearer ${this.token}`,
        Accept: "application/json",
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${await response.text()}`);
    }

    return (await response.json()) as T;
  }
}
  1. Define a tool that uses the authenticated client. The agent will call this tool instead of reaching out directly, which gives you one control point for authorization, logging, and error handling.
// tools.ts
import { z } from "zod";
import { AuthClient } from "./auth-client";

const authClient = new AuthClient(process.env.PROTECTED_API_TOKEN ?? "");

export const getAccountSummary = {
  name: "get_account_summary",
  description: "Fetch the current account summary from a protected API.",
  parameters: z.object({
    accountId: z.string().min(1),
  }),
  execute: async ({ accountId }: { accountId: string }) => {
    return authClient.getJson<{ accountId: string; balance: number }>(
      `https://api.example.com/accounts/${encodeURIComponent(accountId)}`
    );
  },
};
  1. Wire the tool into an AutoGen assistant and let the model decide when to use it. In AutoGen TypeScript, you pass tools into the assistant config and keep the actual secret handling inside the tool implementation.
// agent.ts
import { AssistantAgent } from "@autogenai/autogen";
import { getAccountSummary } from "./tools";

export const assistant = new AssistantAgent({
  name: "auth-assistant",
  modelClientOptions: {
    apiKey: process.env.OPENAI_API_KEY,
    model: "gpt-4o-mini",
  },
  tools: [getAccountSummary],
});
  1. Run a simple conversation and inspect the tool call path. If auth is working, you should see a successful JSON response from the protected API rather than a 401.
// index.ts
import { assistant } from "./agent";

async function main() {
  const result = await assistant.run({
    messages: [
      { role: "user", content: "Get me the account summary for account abc123." },
    ],
  });

  console.log(JSON.stringify(result, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
  1. Add basic guardrails before you ship this into production. Authentication failures should be explicit, and you should fail fast if required secrets are missing at startup.
// bootstrap.ts
const requiredEnv = ["OPENAI_API_KEY", "PROTECTED_API_TOKEN"];

for (const key of requiredEnv) {
  if (!process.env[key]) {
    throw new Error(`Missing required environment variable: ${key}`);
  }
}

Testing It

Run the app with tsx index.ts and confirm the agent can answer using data returned by your protected API. Then temporarily unset PROTECTED_API_TOKEN and verify that startup fails immediately instead of making unauthenticated requests.

Also test a bad token and confirm you get a clean HTTP error from AuthClient, not a silent fallback or malformed response. If your upstream API supports scoped tokens, try one token with read-only access and another with broader access so you can confirm permission boundaries behave as expected.

Next Steps

  • Add per-user authentication by passing user-scoped tokens into tools instead of one shared service token.
  • Add request signing or HMAC headers for APIs that do not use bearer tokens.
  • Move secrets into a real secret manager like AWS Secrets Manager or Azure Key Vault instead of environment variables.

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides