Connect an AI Agent with Vercel AI SDK
Use this guide to connect a Vercel AI SDK agent to Choreo Identity & Access Management 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 consent. It uses your delegated permissions.
Prerequisites
- Node.js 24 and npm.
- Your environment's data plane URL, shown as
https://<DATA_PLANE_URL>in this guide. Find it on the environment's Endpoints page. To open it, select your project, go to Deployment pipeline, and click Open environment on the environment's card. See Data Plane URL. - 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.
Register an Agent
Open the Choreo Identity & Access Management Console at https://console.cloud.choreolabs.com/iam/.
- In the Console, open Agents and click Add agent.
- Name it
Course Agent. Select Gemini as the Model Provider, entergemini-flash-lite-latestas the Model, and select an Owner. Complete the wizard to create the agent. - Copy the Client Secret when shown, then the Client ID from Overview → Agent details. Keep them for
.env; the secret appears only once.
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 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 |
Enable delegated access and consent:
- In Agents → Course Agent → Advanced, turn on Delegated mode. Keep Require PKCE on, leave Require pushed authorization requests off, and add
http://localhost:6274/callbackunder Authorized redirect URIs. Save. - In Flows, create
Course Enrollment Sign-infrom the Basic sign-in template. Add User Consent from Widgets between Authorization and Auth Assertion Generator. Connect both Allow and Deny responses back to User Consent. Turn on Fail flow when user denies consent and save. - On the agent's Flows tab, select Course Enrollment Sign-in as its Sign-in flow and save.
Reuse these resources if they already exist. The resource identifier names the local course tools; you do not need a service at that URL.
Saving a change does not make it live. You author in the control plane, and your users sign in on a separate data plane, so a change takes effect in an environment only after you deploy it. Go to Deploy, deploy the latest version to your first environment, then promote it to the next environment when you are ready.
Auto-sync deploys saved changes to your first environment within seconds. Turning it on is your choice, per project. See Deploy a Version, or learn why you deploy and how auto-sync works.
Create the Project
mkdir vercel-ai-sdk-quickstart
cd vercel-ai-sdk-quickstart
npm init -y
npm pkg set type=module
Create .env in this directory. Replace the credential placeholders:
THUNDERID_BASE_URL=https://<DATA_PLANE_URL>
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.
Build the Agent
The list_courses tool obtains an agent token, validates it with Choreo Identity & Access Management, 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');
// Decode only after introspection validates this exact token.
// Choreo Identity & Access Management's introspection response does not include the actor claim.
const claims = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString());
if (!claims.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:', claims.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
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.
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://<DATA_PLANE_URL>/oauth2/authorize?...
- Open the printed URL. Sign in as the student assigned the Student role.
- On the consent screen, 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.
To 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.
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. |
| 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 | Select Course Enrollment Sign-in on the agent's Flows tab. Confirm the flow includes User Consent. |
| 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.
Was this page helpful?