@clerk/agent-toolkit 0.0.6-canary.v20250306110334

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Clerk, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,256 @@
1
+ <p align="center">
2
+ <a href="https://clerk.com?utm_source=github&utm_medium=clerk_agent_toolkit" target="_blank" rel="noopener noreferrer">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://images.clerk.com/static/logo-dark-mode-400x400.png">
5
+ <img src="https://images.clerk.com/static/logo-light-mode-400x400.png" height="64">
6
+ </picture>
7
+ </a>
8
+ <br />
9
+ <h1 align="center">@clerk/agent-toolkit</h1>
10
+ </p>
11
+
12
+ <div align="center">
13
+
14
+ [![Chat on Discord](https://img.shields.io/discord/856971667393609759.svg?logo=discord)](https://clerk.com/discord)
15
+ [![Clerk documentation](https://img.shields.io/badge/documentation-clerk-green.svg)](https://clerk.com/docs?utm_source=github&utm_medium=clerk_agent_toolkit)
16
+ [![Follow on Twitter](https://img.shields.io/twitter/follow/ClerkDev?style=social)](https://twitter.com/intent/follow?screen_name=ClerkDev)
17
+
18
+ [Changelog](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/CHANGELOG.md)
19
+ ·
20
+ [Report a Bug](https://github.com/clerk/javascript/issues/new?assignees=&labels=needs-triage&projects=&template=BUG_REPORT.yml)
21
+ ·
22
+ [Request a Feature](https://feedback.clerk.com/roadmap)
23
+ ·
24
+ [Get Help](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_agent_toolkit)
25
+
26
+ </div>
27
+
28
+ > [!IMPORTANT]
29
+ >
30
+ > Agent behavior is typically non-deterministic. Ensure you thoroughly test your integration and evaluate your application's performance. Additionally, consider scoping this toolkit's tools to specific users to limit resource access.
31
+ >
32
+ > If your app's code path is predetermined, it's always preferable to call APIs directly instead of using agents and tool calling.
33
+ >
34
+ > This SDK is recommended for testing purposes only unless you are confident in the agent's behavior and have implemented necessary security measures such as guardrails and best practices.
35
+
36
+ ## Table of Contents
37
+
38
+ <!-- TOC -->
39
+
40
+ - [Table of Contents](#table-of-contents)
41
+ - [Getting Started](#getting-started)
42
+ - [API Reference](#api-reference)
43
+ - [Import Paths](#import-paths)
44
+ - [Methods](#methods)
45
+ - [Prerequisites](#prerequisites)
46
+ - [Example Repository](#example-repository)
47
+ - [Using Vercel's AI SDK](#using-vercels-ai-sdk)
48
+ - [Using Langchain](#using-langchain)
49
+ - [Advanced Usage](#advanced-usage)
50
+ - [Using a Custom `clerkClient`](#using-a-custom-clerkclient)
51
+ - [Support](#support)
52
+ - [Contributing](#contributing)
53
+ - [License](#license)
54
+ <!-- TOC -->
55
+
56
+ ## Getting Started
57
+
58
+ Use this SDK to integrate [Clerk](https://clerk.com/?utm_source=github&utm_medium=clerk_agent_toolkit) into your agentic workflows. The Clerk Agent Toolkit enables popular agent frameworks, including Vercel's AI SDK and LangChain, to integrate with Clerk using tools (also known as function calling).
59
+
60
+ This package exposes a subset of Clerk's functionality to agent frameworks, allowing you to build powerful agentic systems capable of managing users, user data, organizations, and more.
61
+
62
+ ## API Reference
63
+
64
+ ### Import Paths
65
+
66
+ The Clerk Agent Toolkit package provides two main import paths:
67
+
68
+ - `@clerk/agent-toolkit/ai-sdk`: Helpers for integrating with Vercel's AI SDK.
69
+ - `@clerk/agent-toolkit/langchain`: Helpers for integrating with Langchain.
70
+
71
+ The toolkit offers the same tools and core APIs across frameworks, but their public interfaces may vary slightly to align with each framework's design:
72
+
73
+ ### Methods
74
+
75
+ **Initialization & generic helpers**:
76
+
77
+ - `createClerkToolkit(options)`: Instantiates a new Clerk toolkit.
78
+ - `toolkit.injectSessionClaims(systemPrompt)`: Injects session claims (`userId`, `sessionId`, `orgId`, etc.) into the system prompt, making them accessible to the AI model.
79
+
80
+ **Available tools**:
81
+
82
+ Currently, are only exposing a subset of Clerk Backend API functionality as tools. We plan to expand this list as we receive feedback from the community. You are welcome to open an issue or reach out to us on Discord to request additional tools.
83
+
84
+ - `toolkit.users()`: Provides tools for managing users. [Details](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/src/lib/tools/users.ts).
85
+ - `toolkit.organizations()`: Provides tools for managing organizations. [Details](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/src/lib/tools/organizations.ts).
86
+ - `toolkit.invitations()`: Provides tools for managing invitations. [Details](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/src/lib/tools/invitations.ts).
87
+ - `toolkit.allTools()`: Returns all available tools.
88
+
89
+ **Langchain-specific methods:**
90
+
91
+ - `toolkit.toolMap()`: Returns an object mapping available tools, useful for calling tools by name.
92
+
93
+ For more details on each tool, refer to the framework-specific directories or the [Clerk Backend API documentation](https://clerk.com/docs/reference/backend-api).
94
+
95
+ ## Prerequisites
96
+
97
+ - `ai-sdk`: `"^3.4.7 || ^4.0.0"`, or `langchain`: `"^0.3.6"`
98
+ - An existing Clerk application. [Create your account for free](https://dashboard.clerk.com/sign-up?utm_source=github&utm_medium=clerk_agent_toolkit).
99
+ - An API key for an AI model compatible with Langchain
100
+
101
+ ## Example Repository
102
+
103
+ - [Clerk AI SDK Example](https://github.com/clerk/agent-toolkit-example)
104
+
105
+ ## Using Vercel's AI SDK
106
+
107
+ 1. Install the Clerk Agent Toolkit package:
108
+
109
+ ```shell
110
+ npm install @clerk/agent-toolkit
111
+ ```
112
+
113
+ 2. Set the Clerk secret key as an environment variable in your project. Ensure you also configure any required LLM model keys.
114
+
115
+ ```
116
+ CLERK_SECRET_KEY=sk_
117
+ ```
118
+
119
+ 3. Import the helper from the `/ai-sdk` path, instantiate a new Clerk `toolkit`, and use it in your agent function:
120
+
121
+ ```typescript
122
+ // Import the helper from the ai-sdk path
123
+ import { createClerkToolkit } from '@clerk/agent-toolkit/ai-sdk';
124
+ import { openai } from '@ai-sdk/openai';
125
+ import { streamText } from 'ai';
126
+ import { auth } from '@clerk/nextjs/server';
127
+ import { systemPrompt } from '@/lib/ai/prompts';
128
+
129
+ export const maxDuration = 30;
130
+
131
+ export async function POST(req: Request) {
132
+ const { messages } = await req.json();
133
+ // Optional - get the userId from the request
134
+ const { userId } = await auth.protect();
135
+
136
+ // Instantiate a new Clerk toolkit
137
+ // Optional - scope the toolkit to a specific user
138
+ const toolkit = await createClerkToolkit({ context: { userId } });
139
+
140
+ const result = streamText({
141
+ model: openai('gpt-4o'),
142
+ messages,
143
+ // Optional - inject session claims into the system prompt
144
+ system: toolkit.injectSessionClaims(systemPrompt),
145
+ tools: {
146
+ // Provide the tools you want to use
147
+ ...toolkit.users(),
148
+ ...toolkit.organizations(),
149
+ },
150
+ });
151
+
152
+ return result.toDataStreamResponse();
153
+ }
154
+ ```
155
+
156
+ ## Using Langchain
157
+
158
+ 1. Install the Clerk Agent Toolkit package:
159
+
160
+ ```shell
161
+ npm install @clerk/agent-toolkit
162
+ ```
163
+
164
+ 2. Set the Clerk secret key as an environment variable:
165
+
166
+ ```shell
167
+ CLERK_SECRET_KEY=sk_
168
+ ```
169
+
170
+ 3. Import the helper from the `/langchain` path, instantiate a new Clerk `toolkit`, and use it in your agent function:
171
+
172
+ ```typescript
173
+ // Import the helper from the langchain path
174
+ import { createClerkToolkit } from '@clerk/agent-toolkit/langchain';
175
+ import { ChatOpenAI } from '@langchain/openai';
176
+ import { auth } from '@clerk/nextjs/server';
177
+ import { HumanMessage, SystemMessage } from '@langchain/core/messages';
178
+ import { LangChainAdapter } from 'ai';
179
+ import { systemPrompt } from '@/lib/ai/prompts';
180
+
181
+ export const maxDuration = 30;
182
+
183
+ export async function POST(req: Request) {
184
+ const { prompt } = await req.json();
185
+ const { userId } = await auth.protect();
186
+
187
+ // Instantiate a new Clerk toolkit
188
+ // Optional - scope the toolkit to a specific user
189
+ const toolkit = await createClerkToolkit({ context: { userId } });
190
+
191
+ const model = new ChatOpenAI({ model: 'gpt-4o', temperature: 0 });
192
+
193
+ // Bind the tools you want to use to the model
194
+ const modelWithTools = model.bindTools(toolkit.users());
195
+
196
+ const messages = [new SystemMessage(toolkit.injectSessionClaims(systemPrompt)), new HumanMessage(prompt)];
197
+ const aiMessage = await modelWithTools.invoke(messages);
198
+ messages.push(aiMessage);
199
+
200
+ for (const toolCall of aiMessage.tool_calls || []) {
201
+ // Call the selected tool
202
+ const selectedTool = toolkit.toolMap()[toolCall.name];
203
+ const toolMessage = await selectedTool.invoke(toolCall);
204
+ messages.push(toolMessage);
205
+ }
206
+
207
+ // To simplify the setup, this example uses the ai-sdk langchain adapter
208
+ // to stream the results back to the /langchain page.
209
+ // For more details, see: https://sdk.vercel.ai/providers/adapters/langchain
210
+ const stream = await modelWithTools.stream(messages);
211
+ return LangChainAdapter.toDataStreamResponse(stream);
212
+ }
213
+ ```
214
+
215
+ ## Advanced Usage
216
+
217
+ ### Using a Custom `clerkClient`
218
+
219
+ If you need to set the Clerk secret key dynamically or use different Clerk instances, pass a custom `clerkClient`. Install `@clerk/backend` into your project and call the `createClerkClient` function:
220
+
221
+ ```typescript
222
+ import { createClerkToolkit } from '@clerk/agent-toolkit/ai-sdk';
223
+ import { createClerkClient } from '@clerk/backend';
224
+
225
+ export async function POST(req: Request) {
226
+ // Create a new Clerk client
227
+ const clerkClient = createClerkClient({ secretKey: 'sk_' });
228
+
229
+ // Instantiate a new Clerk toolkit with the custom client
230
+ const toolkit = await createClerkToolkit({ clerkClient });
231
+
232
+ // Use the toolkit as usual
233
+ const result = streamText({
234
+ model: openai('gpt-4o'),
235
+ messages,
236
+ tools: toolkit.users(),
237
+ });
238
+ }
239
+ ```
240
+
241
+ ## Support
242
+
243
+ You can get in touch with us in any of the following ways:
244
+
245
+ - Join our official community [Discord server](https://clerk.com/discord)
246
+ - On [our support page](https://clerk.com/contact/support?utm_source=github&utm_medium=clerk_agent_toolkit)
247
+
248
+ ## Contributing
249
+
250
+ We're open to all community contributions! If you'd like to contribute in any way, please read [our contribution guidelines](https://github.com/clerk/javascript/blob/main/docs/CONTRIBUTING.md) and [code of conduct](https://github.com/clerk/javascript/blob/main/docs/CODE_OF_CONDUCT.md).
251
+
252
+ ## License
253
+
254
+ This project is licensed under the **MIT license**.
255
+
256
+ See [LICENSE](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/LICENSE) for more information.
@@ -0,0 +1,37 @@
1
+ import { S as SdkAdapter, C as ClerkToolkitBase, f as flatTools, a as CreateClerkToolkitParams, t as tools } from '../index-BtdcFG6Y.js';
2
+ import { Tool } from 'ai';
3
+ import '@clerk/backend';
4
+ import 'zod';
5
+ import '@clerk/backend/internal';
6
+
7
+ /**
8
+ * Converts a `ClerkTool` to an AI SDK `Tool`.
9
+ */
10
+ declare const adapter: SdkAdapter<Tool>;
11
+
12
+ type AdaptedTools = {
13
+ [key in keyof typeof tools]: () => {
14
+ [tool in keyof (typeof tools)[key]]: ReturnType<typeof adapter>;
15
+ };
16
+ };
17
+ type ClerkToolkit = ClerkToolkitBase & {
18
+ /**
19
+ * Returns an object with all the tools from all categories in the Clerk toolkit.
20
+ *
21
+ * Most LLM providers recommend that for each LLM call, the number of available tools should be kept to a minimum,
22
+ * usually around 10-20 tools. This increases the LLM's accuracy when picking the right tool.
23
+ *
24
+ * As a result, we also recommend to use the fine-grained tool categories, for example, `toolkit.users` instead.
25
+ */
26
+ allTools: () => {
27
+ [key in keyof typeof flatTools]: ReturnType<typeof adapter>;
28
+ };
29
+ } & AdaptedTools;
30
+ /**
31
+ * Creates a Clerk toolkit with the given parameters.
32
+ * The toolkit is a collection of tools that can be used to augment the AI's capabilities,
33
+ * For more details, refer to the [package's docs](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/README.md).
34
+ */
35
+ declare const createClerkToolkit: (params?: CreateClerkToolkitParams) => Promise<ClerkToolkit>;
36
+
37
+ export { type ClerkToolkit, createClerkToolkit };
@@ -0,0 +1,42 @@
1
+ import {
2
+ clerkClient,
3
+ defaultToolkitContext,
4
+ flatTools,
5
+ injectSessionClaims,
6
+ shallowTransform,
7
+ tools
8
+ } from "../chunk-K5TBM24J.js";
9
+
10
+ // src/ai-sdk/adapter.ts
11
+ import { tool } from "ai";
12
+ var adapter = (clerkClient2, context, clerkTool) => {
13
+ return tool({
14
+ description: clerkTool.description,
15
+ parameters: clerkTool.parameters,
16
+ execute: clerkTool.bindRunnable(clerkClient2, context)
17
+ });
18
+ };
19
+
20
+ // src/ai-sdk/index.ts
21
+ var createClerkToolkit = async (params = {}) => {
22
+ const clerkClient2 = params.clerkClient || clerkClient;
23
+ const context = params.context || defaultToolkitContext;
24
+ const adaptedTools = shallowTransform(tools, (toolSection) => {
25
+ return () => shallowTransform(toolSection, (t) => {
26
+ return adapter(clerkClient2, context, t);
27
+ });
28
+ });
29
+ const allTools = () => {
30
+ return shallowTransform(flatTools, (t) => adapter(clerkClient2, context, t));
31
+ };
32
+ adaptedTools.organizations();
33
+ return Promise.resolve({
34
+ ...adaptedTools,
35
+ allTools,
36
+ injectSessionClaims: injectSessionClaims(context)
37
+ });
38
+ };
39
+ export {
40
+ createClerkToolkit
41
+ };
42
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/ai-sdk/adapter.ts","../../src/ai-sdk/index.ts"],"sourcesContent":["import type { Tool } from 'ai';\nimport { tool } from 'ai';\n\nimport type { SdkAdapter } from '../lib/types';\n\n/**\n * Converts a `ClerkTool` to an AI SDK `Tool`.\n */\nexport const adapter: SdkAdapter<Tool> = (clerkClient, context, clerkTool) => {\n return tool({\n description: clerkTool.description,\n parameters: clerkTool.parameters,\n execute: clerkTool.bindRunnable(clerkClient, context),\n });\n};\n","import { clerkClient as _clerkClient } from '../lib/clerk-client';\nimport { defaultToolkitContext } from '../lib/constants';\nimport { injectSessionClaims } from '../lib/inject-session-claims';\nimport { flatTools, tools } from '../lib/tools';\nimport type { ClerkToolkitBase, CreateClerkToolkitParams } from '../lib/types';\nimport { shallowTransform } from '../lib/utils';\nimport { adapter } from './adapter';\n\ntype AdaptedTools = {\n [key in keyof typeof tools]: () => { [tool in keyof (typeof tools)[key]]: ReturnType<typeof adapter> };\n};\n\nexport type ClerkToolkit = ClerkToolkitBase & {\n /**\n * Returns an object with all the tools from all categories in the Clerk toolkit.\n *\n * Most LLM providers recommend that for each LLM call, the number of available tools should be kept to a minimum,\n * usually around 10-20 tools. This increases the LLM's accuracy when picking the right tool.\n *\n * As a result, we also recommend to use the fine-grained tool categories, for example, `toolkit.users` instead.\n */\n allTools: () => { [key in keyof typeof flatTools]: ReturnType<typeof adapter> };\n} & AdaptedTools;\n\n/**\n * Creates a Clerk toolkit with the given parameters.\n * The toolkit is a collection of tools that can be used to augment the AI's capabilities,\n * For more details, refer to the [package's docs](https://github.com/clerk/javascript/blob/main/packages/agent-toolkit/README.md).\n */\nexport const createClerkToolkit = async (params: CreateClerkToolkitParams = {}): Promise<ClerkToolkit> => {\n const clerkClient = params.clerkClient || _clerkClient;\n const context = params.context || defaultToolkitContext;\n\n const adaptedTools = shallowTransform(tools, toolSection => {\n return () =>\n shallowTransform(toolSection, t => {\n return adapter(clerkClient, context, t);\n });\n }) as AdaptedTools;\n\n const allTools = () => {\n return shallowTransform(flatTools, t => adapter(clerkClient, context, t));\n };\n\n adaptedTools.organizations();\n\n return Promise.resolve({\n ...adaptedTools,\n allTools,\n injectSessionClaims: injectSessionClaims(context),\n });\n};\n"],"mappings":";;;;;;;;;;AACA,SAAS,YAAY;AAOd,IAAM,UAA4B,CAACA,cAAa,SAAS,cAAc;AAC5E,SAAO,KAAK;AAAA,IACV,aAAa,UAAU;AAAA,IACvB,YAAY,UAAU;AAAA,IACtB,SAAS,UAAU,aAAaA,cAAa,OAAO;AAAA,EACtD,CAAC;AACH;;;ACeO,IAAM,qBAAqB,OAAO,SAAmC,CAAC,MAA6B;AACxG,QAAMC,eAAc,OAAO,eAAe;AAC1C,QAAM,UAAU,OAAO,WAAW;AAElC,QAAM,eAAe,iBAAiB,OAAO,iBAAe;AAC1D,WAAO,MACL,iBAAiB,aAAa,OAAK;AACjC,aAAO,QAAQA,cAAa,SAAS,CAAC;AAAA,IACxC,CAAC;AAAA,EACL,CAAC;AAED,QAAM,WAAW,MAAM;AACrB,WAAO,iBAAiB,WAAW,OAAK,QAAQA,cAAa,SAAS,CAAC,CAAC;AAAA,EAC1E;AAEA,eAAa,cAAc;AAE3B,SAAO,QAAQ,QAAQ;AAAA,IACrB,GAAG;AAAA,IACH;AAAA,IACA,qBAAqB,oBAAoB,OAAO;AAAA,EAClD,CAAC;AACH;","names":["clerkClient","clerkClient"]}