- Get an Auth0 access token.
- Use the Auth0 access token to make a tool call to your API endpoint, in this case, Auth0’s
/userinfoendpoint. - Return the data to the user via an AI agent.
Pick your tech stack
LangGraph.js + Next.js
Vercel AI + Next.js
LangGraph + FastAPI
- Cloudflare Agents
Prerequisites
Before getting started, make sure you have completed the following steps:1
Create an Auth0 Account
To continue with this quickstart, you need to have an Auth0 account.
2
Create an Auth0 Application
Go to your Auth0 Dashboard to create a new Auth0 Application.
- Navigate to Applications > Applications in the left sidebar.
- Click the Create Application button in the top right.
- In the pop-up select Regular Web Applications and click Create.
- Once the Application is created, switch to the Settings tab.
- Scroll down to the Application URIs section.
- Set Allowed Callback URLs as:
http://localhost:3000/auth/callback - Set Allowed Logout URLs as:
http://localhost:3000 - Click Save in the bottom right to save your changes.
3
OpenAI Platform
Set up an OpenAI account and API key.
Download sample app
Start by downloading and extracting the sample app. Then open in your preferred IDE.Install dependencies
In the root directory of your project, install the following dependencies:@langchain/langgraph: The core LangGraph module.@langchain/openai: OpenAI provider for LangChain.langchain: The core LangChain module.zod: TypeScript-first schema validation library.langgraph-nextjs-api-passthrough: API passthrough for LangGraph.
Report incorrect code
Copy
Ask AI
npm install @langchain/[email protected] @langchain/[email protected] [email protected] zod@3 [email protected]
Update the environment file
Copy the.env.example file to .env.local and update the variables with your Auth0 credentials. You can find your Auth0 domain, client ID, and client secret in the application you created in the Auth0 Dashboard.Pass credentials to the agent
You have to pass the access token from the user’s session to the agent. First, create a helper function to get the access token from the session. Add the following function tosrc/lib/auth0.ts:src/lib/auth0.ts
Report incorrect code
Copy
Ask AI
import { Auth0Client } from '@auth0/nextjs-auth0/server';
export const auth0 = new Auth0Client({
authorizationParameters: {
scope: process.env.AUTH0_SCOPE,
audience: process.env.AUTH0_AUDIENCE,
},
});
export const getAccessToken = async () => {
const tokenResult = await auth0.getAccessToken();
if(!tokenResult || !tokenResult.token) {
throw new Error("No access token found in Auth0 session");
}
return tokenResult.token;
};
/src/app/api/chat/[..._path]/route.ts file to pass the access token to the agent:src/app/api/chat/[..._path]/route.ts
Report incorrect code
Copy
Ask AI
import { initApiPassthrough } from "langgraph-nextjs-api-passthrough";
import { getAccessToken } from "@/lib/auth0";
export const { GET, POST, PUT, PATCH, DELETE, OPTIONS, runtime } =
initApiPassthrough({
apiUrl: process.env.LANGGRAPH_API_URL,
baseRoute: "chat/",
headers: async () => {
const accessToken = await getAccessToken();
return {
Authorization: `Bearer ${accessToken}`,
};
});
Add Custom Authentication
For more information on how to add custom authentication for your LangGraph Platform application, read the Custom Auth guide.
langgraph.json, add the path to your auth file:langgraph.json
Report incorrect code
Copy
Ask AI
{
"node_version": "20",
"graphs": {
"agent": "./src/lib/agent.ts:agent"
},
"env": ".env",
"auth": {
"path": "./src/lib/auth.ts:authHandler"
}
}
auth.ts file, add your auth logic:src/lib/auth.ts
Report incorrect code
Copy
Ask AI
import { createRemoteJWKSet, jwtVerify } from "jose";
const { Auth, HTTPException } = require("@langchain/langgraph-sdk/auth");
const AUTH0_DOMAIN = process.env.AUTH0_DOMAIN;
const AUTH0_AUDIENCE = process.env.AUTH0_AUDIENCE;
// JWKS endpoint for Auth0
const JWKS = createRemoteJWKSet(
new URL(`https://${AUTH0_DOMAIN}/.well-known/jwks.json`)
);
// Create the Auth instance
const auth = new Auth();
// Register the authentication handler
auth.authenticate(async (request: Request) => {
const authHeader = request.headers.get("Authorization");
const xApiKeyHeader = request.headers.get("x-api-key");
/**
* LangGraph Platform will convert the `Authorization` header from the client to an `x-api-key` header automatically
* as of now: https://docs.langchain.com/langgraph-platform/custom-auth
*
* We can still leverage the `Authorization` header when served in other infrastructure w/ langgraph-cli
* or when running locally.
*/
// This header is required in Langgraph Cloud.
if (!authHeader && !xApiKeyHeader) {
throw new HTTPException(401, {
message: "Invalid auth header provided.",
});
}
// prefer the xApiKeyHeader first
let token = xApiKeyHeader || authHeader;
// Remove "Bearer " prefix if present
if (token && token.startsWith("Bearer ")) {
token = token.substring(7);
}
// Validate Auth0 Access Token using common JWKS endpoint
if (!token) {
throw new HTTPException(401, {
message:
"Authorization header format must be of the form: Bearer <token>",
});
}
if (token) {
try {
// Verify the JWT using Auth0 JWKS
const { payload } = await jwtVerify(token, JWKS, {
issuer: `https://${AUTH0_DOMAIN}/`,
audience: AUTH0_AUDIENCE,
});
console.log("✅ Auth0 JWT payload resolved!", payload);
// Return the verified payload - this becomes available in graph nodes
return {
identity: payload.sub!,
email: payload.email as string,
permissions:
typeof payload.scope === "string" ? payload.scope.split(" ") : [],
auth_type: "auth0",
// include the access token for use with Auth0 Token Vault exchanges by tools
getRawAccessToken: () => token,
// Add any other claims you need
...payload,
};
} catch (jwtError) {
console.log(
"Auth0 JWT validation failed:",
jwtError instanceof Error ? jwtError.message : "Unknown error"
);
throw new HTTPException(401, {
message: "Invalid Authorization token provided.",
});
}
}
});
export { auth as authHandler };
Define a tool to call your API
In this step, you’ll create a LangChain tool to make the first-party API call. The tool fetches an access token to call the API.In this example, after taking in an Auth0 access token during user login, the tool returns the user profile of the currently logged-in user by calling the /userinfo endpoint.src/lib/tools/user-info.ts
Report incorrect code
Copy
Ask AI
import { tool } from "@langchain/core/tools";
export const getUserInfoTool = tool(
async (_input, config?) => {
// Access credentials from config
const accessToken = config?.configurable?.langgraph_auth_user?.getRawAccessToken();
if (!accessToken) {
return "There is no user logged in.";
}
const response = await fetch(
`https://${process.env.AUTH0_DOMAIN}/userinfo`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
if (response.ok) {
return { result: await response.json() };
}
return "I couldn't verify your identity";
},
{
name: "get_user_info",
description: "Get information about the current logged in user.",
}
);
Add the tool to the AI agent
The AI agent processes and runs the user’s request through the AI pipeline, including the tool call. Update thesrc/lib/agent.ts file to add the tool to the agent.src/lib/agent.ts
Report incorrect code
Copy
Ask AI
//...
import { getUserInfoTool } from "./tools/user-info";
//... existing code
const tools = [
//... existing tools
getUserInfoTool,
];
//... existing code
.env.local file:.env.local
Report incorrect code
Copy
Ask AI
# ...
# You can use any provider of your choice supported by Vercel AI
OPENAI_API_KEY="YOUR_API_KEY"
.env.local accordingly.Test your application
To test the application, runnpm run all:dev and navigate to http://localhost:3000.This will open the LangGraph Studio in a new tab. You can close it as we won’t
require it for testing the application.
"who am I?" to trigger the tool call and test whether it successfully retrieves information about the logged-in user.Report incorrect code
Copy
Ask AI
User: who am I?
AI: It seems that there is no user currently logged in. If you need assistance with anything else, feel free to ask!
User: who am I?
AI: You are Deepu Sasidharan. Here are your details: - .........
Prerequisites
Before getting started, make sure you have completed the following steps:1
Create an Auth0 Account
To continue with this quickstart, you need to have an Auth0 account.
2
Create an Auth0 Application
Go to your Auth0 Dashboard to create a new Auth0 Application.
- Navigate to Applications > Applications in the left sidebar.
- Click the Create Application button in the top right.
- In the pop-up select Regular Web Applications and click Create.
- Once the Application is created, switch to the Settings tab.
- Scroll down to the Application URIs section.
- Set Allowed Callback URLs as:
http://localhost:3000/auth/callback - Set Allowed Logout URLs as:
http://localhost:3000 - Click Save in the bottom right to save your changes.
3
OpenAI Platform
Set up an OpenAI account and API key.
Download sample app
Start by downloading and extracting the sample app. Then open in your preferred IDE.Install dependencies
In the root directory of your project, install the following dependencies:ai: Core Vercel AI SDK module that interacts with various AI model providers.@ai-sdk/openai: OpenAI provider for the Vercel AI SDK.@ai-sdk/react: React UI components for the Vercel AI SDK.zod: TypeScript-first schema validation library.
Report incorrect code
Copy
Ask AI
npm install [email protected] @ai-sdk/[email protected] @ai-sdk/[email protected] [email protected]
Update the environment file
Copy the.env.example file to .env.local and update the variables with your Auth0 credentials. You can find your Auth0 domain, client ID, and client secret in the application you created in the Auth0 Dashboard.Define a tool to call your API
In this step, you’ll create a Vercel AI tool to make the first-party API call. The tool fetches an access token to call the API.In this example, after taking in an Auth0 access token during user login, the tool returns the user profile of the currently logged-in user by calling the /userinfo endpoint.src/lib/tools/user-info.ts
Report incorrect code
Copy
Ask AI
import { tool } from "ai";
import { z } from "zod";
import { auth0 } from "../auth0";
export const getUserInfoTool = tool({
description: "Get information about the current logged in user.",
inputSchema: z.object({}),
execute: async () => {
const session = await auth0.getSession();
if (!session) {
return "There is no user logged in.";
}
const response = await fetch(
`https://${process.env.AUTH0_DOMAIN}/userinfo`,
{
headers: {
Authorization: `Bearer ${session.tokenSet.accessToken}`,
},
}
);
if (response.ok) {
return { result: await response.json() };
}
return "I couldn't verify your identity";
},
});
Add the tool to the AI agent
The AI agent processes and runs the user’s request through the AI pipeline, including the tool call. Vercel AI simplifies this task with thestreamText() method. Update the /src/app/api/chat/route.ts file with the following code:src/app/api/chat/route.ts
Report incorrect code
Copy
Ask AI
//...
import { getUserInfoTool } from "@/lib/tools/user-info";
//... existing code
export async function POST(req: NextRequest) {
const { id, messages }: { id: string; messages: Array<UIMessage> } = await req.json();
setAIContext({ threadID: id });
const tools = {
getUserInfoTool,
};
const stream = createUIMessageStream({
originalMessages: messages,
execute: async ({ writer }) => {
const result = streamText({
model: openai('gpt-4o-mini'),
system: AGENT_SYSTEM_TEMPLATE,
messages: convertToModelMessages(messages),
stopWhen: stepCountIs(5),
tools,
});
writer.merge(
result.toUIMessageStream({
sendReasoning: true,
})
);
},
onError: (err: any) => {
console.log(err);
return `An error occurred! ${err.message}`;
},
});
return createUIMessageStreamResponse({ stream });
}
//... existing code
.env.local file:.env.local
Report incorrect code
Copy
Ask AI
# ...
# You can use any provider of your choice supported by Vercel AI
OPENAI_API_KEY="YOUR_API_KEY"
.env.local accordingly.Test your application
To test the application, runnpm run dev and navigate to http://localhost:3000. To interact with the AI agent, you can ask questions like "who am I?" to trigger the tool call and test whether it successfully retrieves information about the logged-in user.Report incorrect code
Copy
Ask AI
User: who am I?
AI: It seems that there is no user currently logged in. If you need assistance with anything else, feel free to ask!
User: who am I?
AI: You are Deepu Sasidharan. Here are your details: - .........
Prerequisites
Before getting started, make sure you have completed the following steps:1
Create an Auth0 Account
To continue with this quickstart, you need to have an Auth0 account.
2
Create an Auth0 Application
Go to your Auth0 Dashboard to create a new Auth0 Application.
- Navigate to Applications > Applications in the left sidebar.
- Click the Create Application button in the top right.
- In the pop-up select Regular Web Applications and click Create.
- Once the Application is created, switch to the Settings tab.
- Scroll down to the Application URIs section.
- Set Allowed Callback URLs as:
http://localhost:8000/api/auth/callback - Set Allowed Logout URLs as:
http://localhost:5173 - Click Save in the bottom right to save your changes.
3
OpenAI Platform
Set up an OpenAI account and API key.
Download sample app
Start by downloading and extracting the sample app. Then open in your preferred IDE.The project is divided into two parts:backend/: contains the backend code for the Web app and API written in Python using FastAPI and the LangGraph agent.frontend/: contains the frontend code for the Web app written in React as a Vite SPA.
Install dependencies
In thebackend directory of your project, install the following dependencies:langgraph: LangGraph for building stateful, multi-actor applications with LLMs.langchain-openai: LangChain integrations for OpenAI.langgraph-cli: LangGraph CLI for running a local LangGraph server.
Report incorrect code
Copy
Ask AI
cd backend
uv sync
uv add langgraph langchain-openai "langgraph-cli[inmem]"
Update the environment file
Copy the.env.example file to .env and update the variables with your Auth0 credentials. You can find your Auth0 domain, client ID, and client secret in the application you created in the Auth0 Dashboard.Pass credentials to the agent
First, you have to pass the access token from the user’s session to the agent. The FastAPI backend will proxy requests to the LangGraph server with the user’s credentials.Update the API route to pass the access token to the agent inapp/api/routes/chat.py:app/api/routes/chat.py
Report incorrect code
Copy
Ask AI
# ...
from app.core.auth import auth_client
# ...
@agent_router.api_route(
"/{full_path:path}", methods=["GET", "POST", "DELETE", "PATCH", "PUT", "OPTIONS"]
)
async def api_route(
request: Request, full_path: str, auth_session=Depends(auth_client.require_session)
):
try:
# ... existing code
# Prepare body
body = await request.body()
if request.method in ("POST", "PUT", "PATCH") and body:
content = await request.json()
content["config"] = {
"configurable": {
"_credentials": {
"access_token": auth_session.get("token_sets")[0].get(
"access_token"
),
}
}
}
body = json.dumps(content).encode("utf-8")
# ... existing code
Define a tool to call your API
In this step, you’ll create a LangChain tool to make the first-party API call. The tool fetches an access token to call the API.In this example, after taking in an Auth0 access token during user login, the tool returns the user profile of the currently logged-in user by calling the /userinfo endpoint.Create a user info tool inapp/agents/tools/user_info.py:app/agents/tools/user_info.py
Report incorrect code
Copy
Ask AI
import httpx
from langchain_core.tools import StructuredTool
from langchain_core.runnables.config import RunnableConfig
from pydantic import BaseModel
from app.core.config import settings
class UserInfoSchema(BaseModel):
pass
async def get_user_info_fn(config: RunnableConfig):
"""Get information about the current logged in user from Auth0 /userinfo endpoint."""
# Access credentials from config
if "configurable" not in config or "_credentials" not in config["configurable"]:
return "There is no user logged in."
credentials = config["configurable"]["_credentials"]
access_token = credentials.get("access_token")
if not access_token:
return "There is no user logged in."
try:
async with httpx.AsyncClient() as client:
response = await client.get(
f"https://{settings.AUTH0_DOMAIN}/userinfo",
headers={
"Authorization": f"Bearer {access_token}",
},
)
if response.status_code == 200:
user_info = response.json()
return f"User information: {user_info}"
else:
return "I couldn't verify your identity"
except Exception as e:
return f"Error getting user info: {str(e)}"
get_user_info = StructuredTool(
name="get_user_info",
description="Get information about the current logged in user.",
args_schema=UserInfoSchema,
coroutine=get_user_info_fn,
)
Add the tool to the AI agent
The AI agent processes and runs the user’s request through the AI pipeline, including the tool call. Update theapp/agents/assistant0.py file to add the tool to the agent:app/agents/assistant0.py
Report incorrect code
Copy
Ask AI
# ...
from app.agents.tools.user_info import get_user_info
tools = [get_user_info]
llm = ChatOpenAI(model="gpt-4.1-mini")
# ... existing code
agent = create_react_agent(
llm,
tools=ToolNode(tools, handle_tool_errors=False),
prompt=get_prompt(),
)
.env file:.env
Report incorrect code
Copy
Ask AI
# ...
OPENAI_API_KEY="YOUR_API_KEY"
.env accordingly.Test your application
To test the application, start the FastAPI backend, LangGraph server, and the frontend:- In a new terminal, start the FastAPI backend:
Report incorrect code
Copy
Ask AI
cd backend
source .venv/bin/activate
fastapi dev app/main.py
- In another terminal, start the LangGraph server:
Report incorrect code
Copy
Ask AI
cd backend
source .venv/bin/activate
uv pip install -U langgraph-api
langgraph dev --port 54367 --allow-blocking
This will open the LangGraph Studio in a new tab. You can close it as we won’t
require it for testing the application.
- In another terminal, start the frontend:
Report incorrect code
Copy
Ask AI
cd frontend
cp .env.example .env # Copy the `.env.example` file to `.env`.
npm install
npm run dev
http://localhost:5173 in your browser and interact with the AI agent. You can ask questions like "who am I?" to trigger the tool call and test whether it successfully retrieves information about the logged-in user.Report incorrect code
Copy
Ask AI
User: who am I?
AI: It seems that there is no user currently logged in. If you need assistance with anything else, feel free to ask!
User: who am I?
AI: You are Deepu Sasidharan. Here are your details: - .........
Prerequisites
Before getting started, make sure you have completed the following steps:1
Create an Auth0 Account
To continue with this quickstart, you need to have an Auth0 account.
2
Create an Auth0 Application
Go to your Auth0 Dashboard to create a new Auth0 Application.
- Navigate to Applications > Applications in the left sidebar.
- Click the Create Application button in the top right.
- In the pop-up select Regular Web Applications and click Create.
- Once the Application is created, switch to the Settings tab.
- Scroll down to the Application URIs section.
- Set Allowed Callback URLs as:
http://localhost:3000/auth/callback - Set Allowed Logout URLs as:
http://localhost:3000 - Click Save in the bottom right to save your changes.
3
OpenAI Platform
Set up an OpenAI account and API key.
Start from our Cloudflare Agents template
Our Auth0 Cloudflare Agents Starter Kit provides a starter project that includes the necessary dependencies and configuration to get you up and running quickly.To create a new Cloudflare Agents project using the template, run the following command in your terminal:Report incorrect code
Copy
Ask AI
npx create-cloudflare@latest --template auth0-lab/cloudflare-agents-starter
About the dependencies
The start kit is similar to the Cloudflare Agents starter kit but includes the following dependencies to integrate with Auth0 and Vercel AI:hono: Hono Web Application framework.@auth0/auth0-hono: Auth0 SDK for the Hono web framework.hono-agents: Hono Agents to add intelligent, stateful AI agents to your Hono app.@auth0/auth0-cloudflare-agents-api: Auth0 Cloudflare Agents API SDK to secure Cloudflare Agents using bearer tokens from Auth0.@auth0/ai: Auth0 AI SDK to provide base abstractions for authentication and authorization in AI applications.@auth0/ai-vercel: Auth0 Vercel AI SDK to provide building blocks for using Auth0 for AI Agents with the Vercel AI SDK.@auth0/ai-cloudflare: Auth0 Cloudflare AI SDK to provide building blocks for using Auth0 for AI Agents with the Cloudflare Agents API.
Report incorrect code
Copy
Ask AI
npm remove agents
npm install hono \
@auth0/auth0-hono \
hono-agents \
@auth0/auth0-cloudflare-agents-api \
@auth0/ai-cloudflare \
@auth0/ai-vercel \
@auth0/ai
Set up environment variables
In the root directory of your project, copy the.dev.vars.example into .dev.vars file and configure the Auth0 and OpenAI variables..dev.vars
Report incorrect code
Copy
Ask AI
# ...
# You can use any provider of your choice supported by Vercel AI
OPENAI_API_KEY="OPENAI API KEY"
#auth0
AUTH0_DOMAIN="YOUR-ACCOUNT.us.auth0.com"
AUTH0_CLIENT_ID="YOUR CLIENT ID"
AUTH0_CLIENT_SECRET="YOUR CLIENT SECRET"
AUTH0_SESSION_ENCRYPTION_KEY="RANDOM 32 CHARS"
AUTH0_AUDIENCE="YOUR AUDIENCE"
BASE_URL="http://localhost:3000"
.dev.vars accordingly.Configure a persistent store
For persisting Auth0 session data and other key-value pairs, you need to configure a persistent store with your Cloudflare agent worker. When constructing theCloudflareKVStore instance with your Cloudflare agent worker, you can use Workers KV and a KV namespace as the persistent store. This enables you to store Auth0 session data and other key-value pairs with easy access from your Cloudflare agent workers.Report incorrect code
Copy
Ask AI
import { CloudflareKVStore } from '@auth0/ai-cloudflare';
...
return new CloudflareKVStore({ kv: this.env.YOUR_KV_NAMESPACE });
kv prop accepts any store which implements the KVNamespace interface, so any persistent store which implements this interface will work.Define a tool to call your API
In this step, you’ll create a Vercel AI tool to make the first-party API call to the Auth0 API. You will do the same for third-party APIs.After taking in an Auth0 access token during user login, the Cloudflare Worker sends the token to the Cloudflare Agent using the Authorization header in every web request or WebSocket connection.Since the Agent defined in the class Chat insrc/agent/chat.ts uses the AuthAgent trait from the @auth0/auth0-cloudflare-agents-api it validates the signature of the token and that it matches the audience of the Agent.The tool we are defining here uses the same access token to call Auth0’s /userinfo endpoint.src/agent/tools.ts
Report incorrect code
Copy
Ask AI
/**
* Tool definitions for the AI chat agent
* Tools can either require human confirmation or execute automatically
*/
import { tool } from "ai";
import { z } from "zod";
import { getCurrentAgent } from "agents";
import { unstable_scheduleSchema } from "agents/schedule";
import { format, toZonedTime } from "date-fns-tz";
import { buyStock } from "./auth0-ai-sample-tools/buy-stock";
import { checkUsersCalendar } from "./auth0-ai-sample-tools/check-user-calendar";
/**
* Weather information tool that requires human confirmation
* When invoked, this will present a confirmation dialog to the user
* The actual implementation is in the executions object below
*/
const getWeatherInformation = tool({
description: "show the weather in a given city to the user",
inputSchema: z.object({ city: z.string() }),
});
/**
* Local time tool that executes automatically
* Since it includes an execute function, it will run without user confirmation
* This is suitable for low-risk operations that don't need oversight
*/
const getLocalTime = tool({
description: "get the local time for a specified location",
inputSchema: z.object({
timeZone: z.string().describe("IANA time zone name"),
}),
execute: async ({ timeZone: location }) => {
const now = new Date();
const zonedDate = toZonedTime(now, location);
const output = format(zonedDate, "yyyy-MM-dd HH:mm:ssXXX", {
timeZone: location,
});
return output;
},
});
const scheduleTask = tool({
description: "A tool to schedule a task to be executed at a later time",
inputSchema: unstable_scheduleSchema,
execute: async ({ when, description }) => {
const { agent } = getCurrentAgent();
function throwError(msg: string): string {
throw new Error(msg);
}
if (when.type === "no-schedule") {
return "Not a valid schedule input";
}
const input =
when.type === "scheduled"
? when.date // scheduled
: when.type === "delayed"
? when.delayInSeconds // delayed
: when.type === "cron"
? when.cron // cron
: throwError("not a valid schedule input");
try {
agent!.schedule(input!, "executeTask" as keyof typeof agent, description);
} catch (error) {
console.error("error scheduling task", error);
return `Error scheduling task: ${error}`;
}
return `Task scheduled for type "${when.type}" : ${input}`;
},
});
/**
* Tool to list all scheduled tasks
* This executes automatically without requiring human confirmation
*/
const getScheduledTasks = tool({
description: "List all tasks that have been scheduled",
inputSchema: z.object({}),
execute: async () => {
const { agent } = getCurrentAgent();
try {
const tasks = agent!.getSchedules();
if (!tasks || tasks.length === 0) {
return "No scheduled tasks found.";
}
return tasks;
} catch (error) {
console.error("Error listing scheduled tasks", error);
return `Error listing scheduled tasks: ${error}`;
}
},
});
/**
* Tool to cancel a scheduled task by its ID
* This executes automatically without requiring human confirmation
*/
const cancelScheduledTask = tool({
description: "Cancel a scheduled task using its ID",
inputSchema: z.object({
taskId: z.string().describe("The ID of the task to cancel"),
}),
execute: async ({ taskId }) => {
const { agent } = getCurrentAgent();
try {
await agent!.cancelSchedule(taskId);
return `Task ${taskId} has been successfully canceled.`;
} catch (error) {
console.error("Error canceling scheduled task", error);
return `Error canceling task ${taskId}: ${error}`;
}
},
});
/**
* Export all available tools
* These will be provided to the AI model to describe available capabilities
*/
export const tools = {
getWeatherInformation,
getLocalTime,
scheduleTask,
getScheduledTasks,
cancelScheduledTask,
checkUsersCalendar,
buyStock,
};
/**
* Implementation of confirmation-required tools
* This object contains the actual logic for tools that need human approval
* Each function here corresponds to a tool above that doesn't have an execute function
*/
export const executions = {
getWeatherInformation: async ({ city }: { city: string }) => {
console.log(`Getting weather information for ${city}`);
return `The weather in ${city} is sunny`;
},
};
tools export of the src/agent/chat.ts file, add the tools to the allTools array:src/agent/chat.ts
Report incorrect code
Copy
Ask AI
async onChatMessage() {
const allTools = {
...tools,
...(this.mcp?.getAITools?.() ?? {}),
};
... // The rest of the code
Test your application
To test the application, runnpm run start and navigate to http://localhost:3000/ and interact with the AI agent. You can ask questions like “who am I?” to trigger the tool call and test whether it successfully retrieves information about the logged-in user.Report incorrect code
Copy
Ask AI
User: who am I?
AI: It seems that there is no user currently logged in. If you need assistance with anything else, feel free to ask!
User: who am I?
AI: You are Juan Martinez. Here are your details: - .........
Next steps
- Call your APIs on user’s behalf docs.
- To set up third-party tool calling, complete the Call other’s APIs on user’s behalf quickstart.
- To explore the Auth0 Next.js SDK, see the GitHub repo.