Skip to main content

Connect an AI Agent with Vercel AI SDK

Use this guide to connect a Vercel AI SDK agent to ThunderID using its own identity or acting on behalf of a user. Choose a mode to see its setup, code, and expected result.

Your agent will list the available courses using its own permissions. No student signs in.

Prerequisites​

Each mode has one complete file. The sample runs one request with one available tool, then exits.

1

Run ThunderID

Start a local instance, or use one you already have:

$npx thunderid

Requires Node.js 18+

Full install guide →

Open the Console at https://localhost:8090/console.

2

Register an Agent

The Console runs the agent onboarding flow that is set as its default. Before you start, make sure that flow creates the type of agent this mode needs.

Use the built-in onboarding flow, or a flow created from the Agent Onboarding Flow (Own Identity) or Choose Mode template. If an on-behalf-of flow is the current default, set an own-identity flow as the Console default. See select a flow template for the templates.

  1. In Agents, click Add agent.
  2. Select the organization unit when prompted. The owner defaults to your signed-in user; keep it or choose another user.
  3. In Agent Details, set the Name schema attribute to Course Agent. Select gemini as the model provider and enter gemini-flash-lite-latest as the model. If asked, leave Act on behalf of a signed-in user unchecked.
  4. Complete the flow. Copy the client ID and client secret for .env; the secret is shown only once.
3

Configure Access

In Resource servers, create an API resource server named Course Catalog with Identifier https://courses.example.com and permission delimiter :. On Resources, create Courses with handle courses.

Create the following action under Courses. In Roles, create the role with that permission, then assign it on Assignments → Add assignment:

Action nameHandlePermissionRoleAssign to
List coursesreadcourses:readCourse ReaderAgent → Course Agent

Reuse these resources if they already exist. The resource identifier names the local course tools; you do not need a service at that URL.

4

Create the Project

bash
mkdir vercel-ai-sdk-quickstart
cd vercel-ai-sdk-quickstart
npm init -y
npm pkg set type=module
npm install --save-exact ai@7.0.114 @ai-sdk/google@4.0.80 zod@4.6.5
npm install --save-dev --save-exact tsx@4.23.15 @types/node@24.19.0

Create .env in this directory. Replace the credential placeholders:

.env
dotenv
THUNDERID_BASE_URL=https://localhost:8090
AGENT_CLIENT_ID=replace-with-your-client-id
AGENT_SECRET=replace-with-your-client-secret
GOOGLE_API_KEY=replace-with-your-google-api-key
GEMINI_MODEL=gemini-flash-lite-latest
COURSE_RESOURCE=https://courses.example.com

Keep .env out of version control. Use your instance's HTTPS URL for THUNDERID_BASE_URL, and the resource server's Identifier for COURSE_RESOURCE.

For a local instance, save its public certificate beside .env:

bash
openssl s_client -connect localhost:8090 -servername localhost </dev/null 2>/dev/null | openssl x509 -out thunderid.pem

You can also copy config/certs/server.cert from your installation directory and rename it to thunderid.pem. For a publicly trusted certificate, omit the local certificate configuration.

5

Build the Agent

The list_courses tool obtains an agent token, validates it with ThunderID, and checks courses:read before returning the catalog.

ThunderID
User
AI
Agent
🛠️ Tool
Validate
List courses
1asks
2get token
3access token
4calls tool

Save the complete sample beside .env:

Copy agent_own.ts
agent_own.ts
ts
import { ToolLoopAgent, stepCountIs, tool } from 'ai';
import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { z } from 'zod';

const BASE_URL = process.env.THUNDERID_BASE_URL!.replace(/\/$/, '');
const CLIENT_ID = process.env.AGENT_CLIENT_ID!;
const CLIENT_SECRET = process.env.AGENT_SECRET!;
const RESOURCE = process.env.COURSE_RESOURCE!;

async function post(path: string, data: Record<string, string>) {
const encode = (value: string) => new URLSearchParams({ v: value }).toString().slice(2);
const basic = Buffer.from(`${encode(CLIENT_ID)}:${encode(CLIENT_SECRET)}`).toString('base64');
const response = await fetch(`${BASE_URL}${path}`, {
method: 'POST',
headers: { Authorization: `Basic ${basic}` },
body: new URLSearchParams(data),
signal: AbortSignal.timeout(30_000),
redirect: 'error',
});
if (!response.ok) {
throw new Error(`${path} returned HTTP ${response.status}; check the agent configuration.`);
}
return response.json();
}

async function validateToken(token: string, permission: string) {
const identity = await post('/oauth2/introspect', { token });
const audiences = Array.isArray(identity.aud) ? identity.aud : [identity.aud];
if (identity.active !== true || identity.client_id !== CLIENT_ID || !identity.sub
|| !audiences.includes(RESOURCE) || !identity.scope?.split(' ').includes(permission)) {
throw new Error(`The token is not valid for ${permission} on ${RESOURCE}.`);
}
return identity;
}

async function readCourses(token: string) {
const identity = await validateToken(token, 'courses:read');
console.log('Verified agent:', identity.sub);
const result = { courses: [
{ id: 'CS101', name: 'Introduction to Computer Science' },
{ id: 'CS205', name: 'Data Structures' },
] };
console.log('Tool result:', JSON.stringify(result));
return result;
}

const listCourses = tool({
description: "List the available courses using the agent's own identity.",
inputSchema: z.object({}),
execute: async () => {
const { access_token } = await post('/oauth2/token', {
grant_type: 'client_credentials', resource: RESOURCE, scope: 'courses:read',
});
return readCourses(access_token);
},
});

const google = createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_API_KEY });
const agent = new ToolLoopAgent({
model: google(process.env.GEMINI_MODEL!),
instructions: 'Use list_courses to get the catalog. Report only the tool result. If it fails, report the error without retrying.',
tools: { list_courses: listCourses },
stopWhen: stepCountIs(3),
});
console.log('You: List the available courses.');
const response = await agent.generate({ prompt: 'List the available courses.' });
console.log('Agent:', response.text);

Tokens stay inside the tool implementation. Vercel AI SDK exposes only the tool's business arguments to the model.

6

Run the Agent

bash
export NODE_EXTRA_CA_CERTS="$PWD/thunderid.pem"
npx tsx --env-file=.env agent_own.ts

Expect a result like this:

text
You: List the available courses.
Verified agent: <agent-id>
Tool result: {"courses":[{"id":"CS101","name":"Introduction to Computer Science"},{"id":"CS205","name":"Data Structures"}]}
Agent: The available courses are CS101 and CS205.

Verified agent should match the Agent ID in the Console. The tool used the agent's permissions without student sign-in.

The agent's wording and JSON spacing can vary. The Tool result line confirms the operation completed.

In PowerShell, set $env:NODE_EXTRA_CA_CERTS = "$PWD/thunderid.pem" before running the sample. Omit the certificate variable for a publicly trusted certificate.

Resolve common errors
SymptomCheck
HTTP 401 from token or introspection requestsUse the agent's current Client ID and secret. On Advanced, confirm Client authentication method is client_secret_basic.
invalid_targetMatch COURSE_RESOURCE to the resource server's Identifier.
Certificate verification failsExport the running instance's certificate. Set NODE_EXTRA_CA_CERTS before starting the process, as shown above.
Gemini reports a model or quota errorCheck GEMINI_MODEL, your API key, and your Google project quota.
SymptomCheck
Token is not valid for courses:readAssign Course Reader to the agent.

What's Next​

Explore with AI

ThunderID LogoThunderID Logo

Product

DocsAPIsSDKs
© Copyright Linux Foundation Europe.For web site terms of use, trademark policy and other project policies please see https://linuxfoundation.eu/en/policies.