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.
Your agent will enroll you in a course after you sign in, and after you consent if the login flow asks for it. It uses your delegated permissions.
Prerequisites
- Node.js 24 and npm.
- A Google AI Studio API key with access to your Gemini model.
- A browser on the same computer as the sample. Sign-in uses local port
6274.
Each mode has one complete file. The sample runs one request with one available tool, then exits.
Run ThunderID
Start a local instance, or use one you already have:
Requires Node.js 18+
Full install guide →Open the Console at https://localhost:8090/console.
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.
- In Agents, click Add agent.
- Select the organization unit when prompted. The owner defaults to your signed-in user; keep it or choose another user.
- In Agent Details, set the Name schema attribute to
Course Agent. Selectgeminias the model provider and entergemini-flash-lite-latestas the model. If asked, leave Act on behalf of a signed-in user unchecked. - Complete the flow. Copy the client ID and client secret for
.env; the secret is shown only once.
Use a flow created from the Agent Onboarding Flow (On Behalf of a User) or Choose Mode template, and set it as the Console default. See configure onboarding for agents that act on behalf of users for the setup.
The student signs in through the agent's login flow. For a quick tryout, use the Default Authentication Flow, which signs the student in without a consent screen. To ask for consent, use a flow that includes User Consent instead. See how to build a sign-in flow and add consent to a flow.
- In Agents, click Add agent. Select the organization unit and owner when prompted.
- In Agent Details, set the Name schema attribute to
Course Enrollment Agent. Selectgeminias the model provider and entergemini-flash-lite-latestas the model. - If the flow asks for a mode, select Act on behalf of a signed-in user. Set Authorized redirect URIs to
http://localhost:6274/callback. Select the Default Authentication Flow as the Login flow and the student's User type. - Complete the flow. Copy the client ID and client secret for
.env; the secret is shown only once.
The administrator completes onboarding in the Console. The selected Login flow controls the student's later sign-in and consent; it does not run during agent creation.
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 name | Handle | Permission | Role | Assign to |
|---|---|---|---|---|
| List courses | read | courses:read | Course Reader | Agent → Course Agent |
Use an existing non-admin user as the student, or create one in Users with a username, email, and password. Create the following action under Courses. In Roles, create the role with that permission, then assign it on Assignments → Add assignment:
| Action name | Handle | Permission | Role | Assign to |
|---|---|---|---|---|
| Enroll in a course | enroll | courses:enroll | Student | User → your test student |
Use the user type selected during agent onboarding for this student.
Reuse these resources if they already exist. The resource identifier names the local course tools; you do not need a service at that URL.
Create the Project
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:
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:
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.
Build the Agent
The list_courses tool obtains an agent token, validates it with ThunderID, and checks courses:read before returning the catalog.
Save the complete sample beside .env:
Copy agent_own.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);
The enroll_course tool starts sign-in when called. After consent, it validates the delegated token and checks courses:enroll before enrolling the student identified by that token.
After sign-in and consent, the agent exchanges the authorization code for a delegated token using PKCE.
Save the complete sample beside .env. Its callback validates state and waits up to 180 seconds for sign-in and consent:
Copy agent_obo.ts
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
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!;
const REDIRECT_URI = 'http://localhost:6274/callback';
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 getUserToken(): Promise<string> {
const verifier = randomBytes(32).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
const state = randomBytes(32).toString('base64url');
const params = new URLSearchParams({
response_type: 'code', client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI, scope: 'openid courses:enroll', resource: RESOURCE, state, prompt: 'consent',
code_challenge: challenge, code_challenge_method: 'S256',
});
const code = await new Promise<string>((resolve, reject) => {
const finish = (error?: Error, value?: string) => {
clearTimeout(timer);
server.close();
if (error) reject(error);
else resolve(value!);
};
const server = createServer((req, res) => {
const url = new URL(req.url ?? '/', REDIRECT_URI);
const receivedState = Buffer.from(url.searchParams.get('state') ?? '');
const expectedState = Buffer.from(state);
const valid = url.pathname === '/callback'
&& url.searchParams.getAll('state').length === 1
&& receivedState.length === expectedState.length
&& timingSafeEqual(receivedState, expectedState)
&& ((url.searchParams.getAll('code').length === 1 && !url.searchParams.has('error'))
|| (url.searchParams.getAll('error').length === 1 && !url.searchParams.has('code')));
res.writeHead(valid ? 200 : 400, { 'Content-Type': 'text/plain', Connection: 'close' });
res.end(valid ? 'Return to your terminal.' : 'Invalid callback.');
if (!valid) return;
if (url.searchParams.has('error')) finish(new Error('Sign-in was denied or failed.'));
else finish(undefined, url.searchParams.get('code')!);
});
const timer = setTimeout(() => finish(new Error('Sign-in timed out. Run the sample again.')), 180_000);
server.on('error', error => finish(error));
server.listen(6274, 'localhost', () => {
console.log('Open this URL in your browser to sign in:');
console.log(`${BASE_URL}/oauth2/authorize?${params}`);
});
});
return (await post('/oauth2/token', {
grant_type: 'authorization_code', code,
redirect_uri: REDIRECT_URI, code_verifier: verifier,
})).access_token;
}
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;
}
const enrollments = new Map<string, Set<string>>();
let enrolling = false;
async function recordEnrollment(courseId: string, token: string) {
const identity = await validateToken(token, 'courses:enroll');
if (!identity.act?.sub) throw new Error('Enrollment requires a delegated user token.');
const studentId: string = identity.sub;
if (!enrollments.has(studentId)) enrollments.set(studentId, new Set());
const enrolled = enrollments.get(studentId)!;
const status = enrolled.has(courseId) ? 'already_enrolled' : 'enrolled';
enrolled.add(courseId);
const result = { student_id: studentId, course_id: courseId, status };
console.log('Verified agent:', identity.act.sub);
console.log('Tool result:', JSON.stringify(result));
return result;
}
const enrollCourse = tool({
description: 'Enroll the signed-in student in CS101 or CS205 after their consent.',
inputSchema: z.object({ course_id: z.string() }),
execute: async ({ course_id }) => {
if (!['CS101', 'CS205'].includes(course_id)) {
return { status: 'not_enrolled', reason: 'Unknown course ID.' };
}
if (enrolling) throw new Error('An enrollment is already awaiting consent.');
enrolling = true;
try {
console.log(`Enrolling you in ${course_id} needs your permission.`);
return await recordEnrollment(course_id, await getUserToken());
} finally {
enrolling = false;
}
},
});
const google = createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_API_KEY });
const agent = new ToolLoopAgent({
model: google(process.env.GEMINI_MODEL!),
instructions: 'Use enroll_course for the requested course. The tool handles sign-in and consent. Report success only if the tool succeeds. If it fails or consent is denied, stop without retrying.',
tools: { enroll_course: enrollCourse },
stopWhen: stepCountIs(3),
});
console.log('You: Enroll me in CS205.');
const response = await agent.generate({ prompt: 'Enroll me in CS205.' });
console.log('Agent:', response.text);
Tokens stay inside the tool implementation. Vercel AI SDK exposes only the tool's business arguments to the model.
Run the Agent
export NODE_EXTRA_CA_CERTS="$PWD/thunderid.pem"
npx tsx --env-file=.env agent_own.ts
Expect a result like this:
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.
export NODE_EXTRA_CA_CERTS="$PWD/thunderid.pem"
npx tsx --env-file=.env agent_obo.ts
The sample asks to enroll you in CS205, then prints a sign-in link:
You: Enroll me in CS205.
Enrolling you in CS205 needs your permission.
Open this URL in your browser to sign in:
https://localhost:8090/oauth2/authorize?...
- Open the printed URL. Sign in as the student assigned the Student role.
- If a consent screen appears, turn on
courses:enrolland click Allow. - Return to the terminal after the browser reaches the local redirect URI.
Expect a result like this:
Verified agent: <agent-id>
Tool result: {"student_id":"<student-id>","course_id":"CS205","status":"enrolled"}
Agent: You are enrolled in CS205.
student_id should match your signed-in student's User ID. The sample reads the agent's identity from the validated token's act.sub claim. Enrollment records disappear when the process exits.
With a consent flow, you can try denial: run the sample again and click Deny. The tool fails without recording an enrollment. Each run requests fresh consent.
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
| Symptom | Check |
|---|---|
HTTP 401 from token or introspection requests | Use the agent's current Client ID and secret. On Advanced, confirm Client authentication method is client_secret_basic. |
invalid_target | Match COURSE_RESOURCE to the resource server's Identifier. |
| Certificate verification fails | Export the running instance's certificate. Set NODE_EXTRA_CA_CERTS before starting the process, as shown above. |
| Gemini reports a model or quota error | Check GEMINI_MODEL, your API key, and your Google project quota. |
| Symptom | Check |
|---|---|
Token is not valid for courses:read | Assign Course Reader to the agent. |
| Symptom | Check |
|---|---|
Token is not valid for courses:enroll | Assign Student to the signed-in user and allow the permission on the consent screen. |
| No consent screen appears | The Default Authentication Flow does not ask for consent. Select a flow that includes User Consent on the agent's Flows tab. See add consent to a flow. |
| Sign-in fails before the redirect | Enable delegated mode and register http://localhost:6274/callback exactly. |
Port 6274 is in use, or sign-in times out | Stop the other sample, or run this sample again and complete sign-in within 180 seconds. |
What's Next
- Agent tokens explains own-identity access.
- Agent access on behalf of users covers delegated access and token refresh.
- Choose another framework to try the examples with LangChain, Google ADK, or CrewAI.
- Control agent access covers permission checks when moving tools behind a business API.