@corsair-dev/mastra 0.1.0
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 +191 -0
- package/README.md +140 -0
- package/dist/corsair-tool-provider.d.ts +235 -0
- package/dist/corsair-tool-provider.d.ts.map +1 -0
- package/dist/form-field-to-zod.d.ts +10 -0
- package/dist/form-field-to-zod.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +372 -0
- package/package.json +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(which shall not include Communications that are clearly marked or
|
|
39
|
+
otherwise designated in writing by the copyright owner as "Not a Work").
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution".
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
Copyright (c) 2026 Corsair
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# @corsair-dev/mastra
|
|
2
|
+
|
|
3
|
+
A [Mastra](https://mastra.ai) `ToolProvider` for [Corsair](https://corsair.dev) — expose 200+ integrations (Slack, GitHub, Gmail, Linear, Stripe, …) to your Mastra agents, backed by **managed OAuth** and with **credentials that stay in your own database**.
|
|
4
|
+
|
|
5
|
+
Each Corsair plugin becomes a toolkit and each operation becomes a tool. The same provider works two ways:
|
|
6
|
+
|
|
7
|
+
- **Editor / managed** — register it with `MastraEditor` and Mastra's connection UI drives the OAuth lifecycle (the VNext surface).
|
|
8
|
+
- **Code-config** — call `resolveTools()` yourself and hand the tools to an `Agent`.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @corsair-dev/mastra @mastra/core corsair
|
|
14
|
+
# plus a plugin per integration you use, e.g. Slack:
|
|
15
|
+
npm install @corsair-dev/slack
|
|
16
|
+
# and, for the managed-connection editor UI:
|
|
17
|
+
npm install @mastra/editor
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`@mastra/core` is a peer dependency.
|
|
21
|
+
|
|
22
|
+
## Usage
|
|
23
|
+
|
|
24
|
+
Create a Corsair instance, then a provider:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { createCorsair } from 'corsair';
|
|
28
|
+
import { CorsairToolProvider } from '@corsair-dev/mastra';
|
|
29
|
+
import { slack } from '@corsair-dev/slack';
|
|
30
|
+
|
|
31
|
+
const corsair = createCorsair({
|
|
32
|
+
plugins: [slack({ authType: 'managed' })],
|
|
33
|
+
database,
|
|
34
|
+
kek: process.env.CORSAIR_KEK,
|
|
35
|
+
hub: { projectApiKey: process.env.CORSAIR_API_KEY },
|
|
36
|
+
multiTenancy: true,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const provider = new CorsairToolProvider({
|
|
40
|
+
corsair,
|
|
41
|
+
// Map a Mastra request to a Corsair tenant (per-user, per-org, …):
|
|
42
|
+
tenantId: (req) => req.authorId ?? 'default',
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## Tenancy
|
|
47
|
+
|
|
48
|
+
`tenantId` is the single knob that maps a Mastra request to a Corsair **tenant** — each tenant owns its own connections and credentials. It also derives the Mastra connection scope for you, so there is nothing else to wire up:
|
|
49
|
+
|
|
50
|
+
| `tenantId` | Meaning | Derived scope |
|
|
51
|
+
| ------------------------ | ------------------------------------------ | ------------------- |
|
|
52
|
+
| `'acme'` (string) | Pin every request to one tenant | `'shared'` |
|
|
53
|
+
| `(req) => …` (function) | Resolve per request (multi-tenant SaaS) | `'caller-supplied'` |
|
|
54
|
+
| _omitted_ | Connection's tenant → author id → default | `'per-author'` |
|
|
55
|
+
|
|
56
|
+
When Mastra **resolves and runs** tools it passes the connection id, author id, toolkit, and live request context, so you can bucket by whatever your app authenticates on (user, org, workspace):
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
new CorsairToolProvider({
|
|
60
|
+
corsair,
|
|
61
|
+
tenantId: ({ authorId, requestContext }) =>
|
|
62
|
+
orgIdFrom(requestContext) ?? authorId ?? 'default',
|
|
63
|
+
});
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
> **Starting a new connection needs a resolvable tenant.** Mastra's `authorize` (the OAuth kickoff for a _fresh_ connection) receives only `toolkit` and `connectionId` — no `authorId` or `requestContext`. A function resolver can therefore scope existing connections but has nothing to resolve a brand-new one from, so it throws rather than guess. To start OAuth under multi-tenancy, either pin `tenantId` to a string or hand it a `connectionId` minted by `encodeConnectionId(tenant, toolkit)`.
|
|
67
|
+
|
|
68
|
+
Pass `defaultScope` explicitly to override the derived one.
|
|
69
|
+
|
|
70
|
+
### With the Mastra editor (managed connections)
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import { Mastra } from '@mastra/core';
|
|
74
|
+
import { MastraEditor } from '@mastra/editor';
|
|
75
|
+
|
|
76
|
+
export const mastra = new Mastra({
|
|
77
|
+
agents: {
|
|
78
|
+
/* … */
|
|
79
|
+
},
|
|
80
|
+
editor: new MastraEditor({
|
|
81
|
+
toolProviders: { corsair: provider },
|
|
82
|
+
}),
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### Code-config (resolve tools directly)
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { Agent } from '@mastra/core/agent';
|
|
90
|
+
|
|
91
|
+
const tools = await provider.resolveTools(['slack.api.channels.list']);
|
|
92
|
+
|
|
93
|
+
const agent = new Agent({
|
|
94
|
+
id: 'my-agent',
|
|
95
|
+
name: 'My Agent',
|
|
96
|
+
instructions: 'You have Slack tools via Corsair.',
|
|
97
|
+
model,
|
|
98
|
+
tools,
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Choosing which tools
|
|
103
|
+
|
|
104
|
+
You rarely hand-write slugs. Pick the level that fits:
|
|
105
|
+
|
|
106
|
+
**Let users choose in the editor (most common).** With `MastraEditor`, the
|
|
107
|
+
playground lists every Corsair toolkit and tool and users toggle them — no code.
|
|
108
|
+
Scope what's offered with the provider's allowlist (inherited from
|
|
109
|
+
`BaseToolProvider`, same as Composio/Arcade):
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
// only Slack shows up; omit both to offer everything Corsair has
|
|
113
|
+
new CorsairToolProvider({ corsair, allowedToolkits: ['slack'] });
|
|
114
|
+
new CorsairToolProvider({ corsair, allowedTools: ['slack.api.channels.list'] });
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
**Code-config — specific tools:**
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const tools = await provider.resolveTools([
|
|
121
|
+
'slack.api.channels.list',
|
|
122
|
+
'slack.api.messages.post',
|
|
123
|
+
]);
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
**Code-config — a whole toolkit, or every operation Corsair offers:**
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
// one toolkit: pass { toolkit: 'slack' }; omit it for every registered plugin
|
|
130
|
+
const { data } = await provider.listTools({ toolkit: 'slack' });
|
|
131
|
+
const tools = await provider.resolveTools(data.map((t) => t.slug));
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
`listTools()` returns metadata (browse/pick); `resolveTools()` returns the
|
|
135
|
+
executable tools you hand to an `Agent`. All operations of every plugin you
|
|
136
|
+
register on the `corsair` instance are reachable this way.
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
Apache-2.0
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import type { AuthFlowStatus, AuthorizeOpts, BaseToolProviderOptions, ListConnectionsOpts, ListConnectionsResult, ListToolsOpts, ListToolsResult, ResolveToolsOpts, ToolProviderCapabilities, ToolProviderHealth, ToolProviderInfo, ToolProviderToolkit } from '@mastra/core/tool-provider';
|
|
2
|
+
import { BaseToolProvider } from '@mastra/core/tool-provider';
|
|
3
|
+
import type { ToolAction } from '@mastra/core/tools';
|
|
4
|
+
import type { AnyCorsairInstance } from 'corsair';
|
|
5
|
+
/**
|
|
6
|
+
* A Corsair plugin's connection state for one tenant, as reported by
|
|
7
|
+
* `corsair.manage.connectionStatus`.
|
|
8
|
+
*/
|
|
9
|
+
type PluginConnectionState = 'connected' | 'missing_credentials' | 'not_connected';
|
|
10
|
+
/**
|
|
11
|
+
* Context passed to a {@link CorsairToolProviderConfig.tenantId} resolver
|
|
12
|
+
* function so it can map a Mastra request to a Corsair tenant.
|
|
13
|
+
*/
|
|
14
|
+
export type TenantResolveInput = {
|
|
15
|
+
/** The connection bucket Mastra is resolving, if any (decodes to a tenant). */
|
|
16
|
+
connectionId?: string;
|
|
17
|
+
/** The agent author's id, when the runtime provides one. */
|
|
18
|
+
authorId?: string;
|
|
19
|
+
/** The toolkit (Corsair plugin) slug being resolved. */
|
|
20
|
+
toolkit?: string;
|
|
21
|
+
/**
|
|
22
|
+
* Mastra's live per-request context. Use its typed accessors to derive the
|
|
23
|
+
* tenant for `caller-supplied` (multi-tenant) deployments.
|
|
24
|
+
*/
|
|
25
|
+
requestContext?: unknown;
|
|
26
|
+
};
|
|
27
|
+
type CorsairRootInstance = Extract<AnyCorsairInstance, {
|
|
28
|
+
manage: unknown;
|
|
29
|
+
}>;
|
|
30
|
+
/**
|
|
31
|
+
* Configuration for {@link CorsairToolProvider}. Extends
|
|
32
|
+
* {@link BaseToolProviderOptions} so `allowedToolkits` / `allowedTools` /
|
|
33
|
+
* `defaultScope` are accepted alongside the Corsair-specific fields.
|
|
34
|
+
*/
|
|
35
|
+
export interface CorsairToolProviderConfig extends BaseToolProviderOptions {
|
|
36
|
+
/**
|
|
37
|
+
* A root Corsair instance from `createCorsair()`, single- or multi-tenant.
|
|
38
|
+
* The provider scopes to a tenant itself, so pass the root, not a
|
|
39
|
+
* `withTenant()` client.
|
|
40
|
+
*/
|
|
41
|
+
corsair: CorsairRootInstance;
|
|
42
|
+
/**
|
|
43
|
+
* How a Mastra request maps to a Corsair **tenant** — Corsair's multi-tenancy
|
|
44
|
+
* primitive, where each tenant owns its own connections and credentials.
|
|
45
|
+
* Three modes, each of which also picks the Mastra connection scope for you:
|
|
46
|
+
*
|
|
47
|
+
* - **`string`** — pin every request to one tenant (single-tenant apps).
|
|
48
|
+
* Derives `defaultScope: 'shared'`.
|
|
49
|
+
* - **function** — choose the tenant for a *new* connection from the author
|
|
50
|
+
* id or request context (multi-tenant SaaS). Derives
|
|
51
|
+
* `defaultScope: 'caller-supplied'`.
|
|
52
|
+
* - **omitted** — fall back to the author id, then `'default'`. Derives
|
|
53
|
+
* `defaultScope: 'per-author'`.
|
|
54
|
+
*
|
|
55
|
+
* This mapping is authoritative for tenant isolation: a `connectionId` never
|
|
56
|
+
* overrides a pinned tenant, and when the caller is known a connectionId
|
|
57
|
+
* naming a different tenant is rejected (see {@link resolveTenant}). The
|
|
58
|
+
* derived scope is only a default; pass `defaultScope` to override it.
|
|
59
|
+
*/
|
|
60
|
+
tenantId?: string | ((input: TenantResolveInput) => string | Promise<string>);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Encodes a `(tenant, toolkit)` pair into the opaque `connectionId`/`authId`
|
|
64
|
+
* string Mastra passes around, so the provider can recover the pair later.
|
|
65
|
+
*
|
|
66
|
+
* This token is encoded, not signed — treat it as a server-minted handle, not a
|
|
67
|
+
* capability. The provider never lets it override the configured tenant (see
|
|
68
|
+
* {@link CorsairToolProviderConfig.tenantId}), so keep connection ids
|
|
69
|
+
* server-side and derive them from your authenticated identity; do not accept
|
|
70
|
+
* one verbatim from an untrusted caller.
|
|
71
|
+
*
|
|
72
|
+
* @param tenantId - The Corsair tenant this connection belongs to.
|
|
73
|
+
* @param toolkit - The Corsair plugin (toolkit) slug.
|
|
74
|
+
* @returns A base64url token that {@link decodeConnectionId} can reverse.
|
|
75
|
+
*/
|
|
76
|
+
export declare function encodeConnectionId(tenantId: string, toolkit: string): string;
|
|
77
|
+
/**
|
|
78
|
+
* Reverses {@link encodeConnectionId}.
|
|
79
|
+
*
|
|
80
|
+
* @param id - A token previously produced by {@link encodeConnectionId}.
|
|
81
|
+
* @returns The `(tenantId, toolkit)` pair, or `null` when the token is
|
|
82
|
+
* malformed (never throws).
|
|
83
|
+
*/
|
|
84
|
+
export declare function decodeConnectionId(id: string): {
|
|
85
|
+
tenantId: string;
|
|
86
|
+
toolkit: string;
|
|
87
|
+
} | null;
|
|
88
|
+
/**
|
|
89
|
+
* Maps a Corsair connection state to a Mastra {@link AuthFlowStatus}. Only a
|
|
90
|
+
* live credential (`'connected'`) completes the flow; every other state stays
|
|
91
|
+
* `'pending'` so an in-progress authorize poll is not aborted.
|
|
92
|
+
*/
|
|
93
|
+
export declare function mapAuthStatus(state?: PluginConnectionState): AuthFlowStatus;
|
|
94
|
+
/**
|
|
95
|
+
* Splits Corsair's newline-delimited operation listing (from `listOperations`)
|
|
96
|
+
* into individual tool slugs, tolerating blank lines and surrounding
|
|
97
|
+
* whitespace.
|
|
98
|
+
*/
|
|
99
|
+
export declare function parseOperationPaths(listing: string): string[];
|
|
100
|
+
/**
|
|
101
|
+
* Exposes Corsair as a Mastra {@link BaseToolProvider}: each Corsair plugin is a
|
|
102
|
+
* toolkit, each operation is a tool, and Corsair Hub's managed OAuth backs the
|
|
103
|
+
* authorize / connection-status lifecycle.
|
|
104
|
+
*
|
|
105
|
+
* Extending `BaseToolProvider` provides the allowlist filtering and the legacy
|
|
106
|
+
* `listTools()` / `resolveTools()` shims for free, so the same provider drives
|
|
107
|
+
* both the Mastra editor (via the VNext surface) and static, code-config agents
|
|
108
|
+
* (via `resolveTools`).
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```ts
|
|
112
|
+
* const provider = new CorsairToolProvider({
|
|
113
|
+
* corsair, // createCorsair({ ... })
|
|
114
|
+
* tenantId: (req) => req.authorId ?? 'default',
|
|
115
|
+
* });
|
|
116
|
+
*
|
|
117
|
+
* // Register with the Mastra editor:
|
|
118
|
+
* new Mastra({ editor: new MastraEditor({ toolProviders: { corsair: provider } }) });
|
|
119
|
+
*
|
|
120
|
+
* // …or resolve tools directly for a code-config agent:
|
|
121
|
+
* const tools = await provider.resolveTools(['slack.api.channels.list']);
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
124
|
+
export declare class CorsairToolProvider extends BaseToolProvider {
|
|
125
|
+
/** Provider identity surfaced in the Mastra tool picker. */
|
|
126
|
+
readonly info: ToolProviderInfo;
|
|
127
|
+
/** Feature flags the Mastra runtime branches on (batch status, in-place reauth, …). */
|
|
128
|
+
readonly capabilities: ToolProviderCapabilities;
|
|
129
|
+
private readonly corsair;
|
|
130
|
+
private readonly tenantConfig;
|
|
131
|
+
/**
|
|
132
|
+
* @param config - The Corsair instance plus optional tenant mapping and the
|
|
133
|
+
* inherited {@link BaseToolProviderOptions} allowlists. When `defaultScope`
|
|
134
|
+
* is omitted it is derived from `tenantId` (see {@link scopeForTenant}).
|
|
135
|
+
*/
|
|
136
|
+
constructor(config: CorsairToolProviderConfig);
|
|
137
|
+
/** Returns the Corsair instance for use with inspect helpers. */
|
|
138
|
+
private asInstance;
|
|
139
|
+
/** Corsair's management namespace (plugins / connection status / connect). */
|
|
140
|
+
private get manage();
|
|
141
|
+
/**
|
|
142
|
+
* Resolves a request to a Corsair tenant.
|
|
143
|
+
*
|
|
144
|
+
* The configured mapping is authoritative; a `connectionId` only ever carries
|
|
145
|
+
* a *claim* that must agree with it. `connectionId` is unauthenticated
|
|
146
|
+
* (base64url, not signed), so it must never let a caller reach a tenant the
|
|
147
|
+
* configuration wouldn't grant:
|
|
148
|
+
*
|
|
149
|
+
* - **Pinned (`string`)** — always that tenant; a connectionId for a different
|
|
150
|
+
* tenant is forged or stale and is ignored.
|
|
151
|
+
* - **Caller-known** (`authorId`/`requestContext` present) — derive the tenant
|
|
152
|
+
* from the caller and reject a connectionId that names a *different* tenant
|
|
153
|
+
* (cross-tenant access attempt).
|
|
154
|
+
* - **No caller context** (`authorize`, `getConnectionStatus`; see
|
|
155
|
+
* {@link AuthorizeOpts}) — the connectionId is the only tenant source.
|
|
156
|
+
* - **Fresh connection + function resolver** — unsupported: Mastra passes no
|
|
157
|
+
* author/request context to `authorize`, so throw rather than silently open
|
|
158
|
+
* OAuth under a fallback tenant.
|
|
159
|
+
*/
|
|
160
|
+
private resolveTenant;
|
|
161
|
+
/** Scopes the Corsair instance to a tenant (multi-tenant), else returns it as-is. */
|
|
162
|
+
private scopedInstance;
|
|
163
|
+
/**
|
|
164
|
+
* Every registered Corsair plugin becomes a toolkit. The base class applies
|
|
165
|
+
* `allowedToolkits` filtering on top before exposing this to the editor.
|
|
166
|
+
*/
|
|
167
|
+
protected listAllToolkits(): Promise<ToolProviderToolkit[]>;
|
|
168
|
+
/**
|
|
169
|
+
* Lists a plugin's API operations as tools, honouring the `toolkit`, `search`
|
|
170
|
+
* and pagination options. The base class applies `allowedTools` filtering on
|
|
171
|
+
* top.
|
|
172
|
+
*/
|
|
173
|
+
protected listAllTools(opts: ListToolsOpts): Promise<ListToolsResult>;
|
|
174
|
+
/**
|
|
175
|
+
* The JSON Schema for one tool's input, so the editor's tool-detail view can
|
|
176
|
+
* render it without materialising the tool. Built from Corsair's structured
|
|
177
|
+
* schema; `null` when the operation is unknown or takes no input.
|
|
178
|
+
*/
|
|
179
|
+
getToolSchema(toolSlug: string): Promise<Record<string, unknown> | null>;
|
|
180
|
+
/**
|
|
181
|
+
* Materialises executable Mastra tools for the requested slugs, bound to the
|
|
182
|
+
* resolved tenant's Corsair credentials. The runtime calls this once per
|
|
183
|
+
* connection; each tool's `execute` runs the Corsair operation with the
|
|
184
|
+
* managed token from your database.
|
|
185
|
+
*
|
|
186
|
+
* `ToolAction<any, any, any>` matches the abstract base class signature from
|
|
187
|
+
* `@mastra/core` — the input/output schemas are dynamically derived per plugin
|
|
188
|
+
* at runtime and cannot be statically parameterised.
|
|
189
|
+
*/
|
|
190
|
+
resolveToolsVNext(opts: ResolveToolsOpts): Promise<Record<string, ToolAction<any, any, any>>>;
|
|
191
|
+
/**
|
|
192
|
+
* Starts Corsair Hub's managed-OAuth flow for a toolkit and returns the
|
|
193
|
+
* connect URL to send the user to, plus an opaque `authId` to poll.
|
|
194
|
+
*/
|
|
195
|
+
authorize(opts: AuthorizeOpts): Promise<{
|
|
196
|
+
url: string;
|
|
197
|
+
authId: string;
|
|
198
|
+
}>;
|
|
199
|
+
/**
|
|
200
|
+
* Polls a managed-OAuth flow: returns `'completed'` once the tenant has a
|
|
201
|
+
* live credential for the toolkit, otherwise `'pending'` (`'failed'` only for
|
|
202
|
+
* an unreadable `authId`).
|
|
203
|
+
*/
|
|
204
|
+
getAuthStatus(authId: string): Promise<AuthFlowStatus>;
|
|
205
|
+
/**
|
|
206
|
+
* Batch-checks whether each `(connectionId, toolkit)` is still connected,
|
|
207
|
+
* grouping by resolved tenant so one status call covers many items. Result is
|
|
208
|
+
* keyed by `connectionId`.
|
|
209
|
+
*/
|
|
210
|
+
getConnectionStatus(opts: {
|
|
211
|
+
items: Array<{
|
|
212
|
+
connectionId: string;
|
|
213
|
+
toolkit: string;
|
|
214
|
+
}>;
|
|
215
|
+
}): Promise<Record<string, {
|
|
216
|
+
connected: boolean;
|
|
217
|
+
}>>;
|
|
218
|
+
/**
|
|
219
|
+
* Lists the already-connected accounts for the given user bucket(s) + toolkit
|
|
220
|
+
* so the picker can offer them without re-running OAuth. Corsair models one
|
|
221
|
+
* connection per (tenant, toolkit), so at most one item per bucket.
|
|
222
|
+
*/
|
|
223
|
+
listConnections(opts: ListConnectionsOpts): Promise<ListConnectionsResult>;
|
|
224
|
+
/**
|
|
225
|
+
* Revokes a connection by removing its stored credentials (and account-scoped
|
|
226
|
+
* data) through Corsair's management API. Idempotent per the ToolProvider
|
|
227
|
+
* contract: an unreadable `connectionId` or an already-gone connection
|
|
228
|
+
* resolves without error.
|
|
229
|
+
*/
|
|
230
|
+
revokeConnection(connectionId: string): Promise<void>;
|
|
231
|
+
/** Reports provider health by probing Corsair's management API. */
|
|
232
|
+
getHealth(): Promise<ToolProviderHealth>;
|
|
233
|
+
}
|
|
234
|
+
export {};
|
|
235
|
+
//# sourceMappingURL=corsair-tool-provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"corsair-tool-provider.d.ts","sourceRoot":"","sources":["../src/corsair-tool-provider.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { FormFieldSchema } from 'corsair';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* Converts the machine-readable schema from Corsair's `getStructuredSchema`
|
|
5
|
+
* into a Zod schema, so a Corsair operation can back a Mastra `createTool`
|
|
6
|
+
* `inputSchema`. Applies the field's `description` and `optional` flag on top of
|
|
7
|
+
* its base type.
|
|
8
|
+
*/
|
|
9
|
+
export declare function formFieldToZod(field: FormFieldSchema): z.ZodTypeAny;
|
|
10
|
+
//# sourceMappingURL=form-field-to-zod.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-field-to-zod.d.ts","sourceRoot":"","sources":["../src/form-field-to-zod.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,eAAe,GAAG,CAAC,CAAC,UAAU,CAKnE"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** @packageDocumentation */
|
|
2
|
+
export type { CorsairToolProviderConfig, TenantResolveInput, } from './corsair-tool-provider.js';
|
|
3
|
+
export { CorsairToolProvider, decodeConnectionId, encodeConnectionId, mapAuthStatus, parseOperationPaths, } from './corsair-tool-provider.js';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAE5B,YAAY,EACX,yBAAyB,EACzB,kBAAkB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACN,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EAClB,aAAa,EACb,mBAAmB,GACnB,MAAM,4BAA4B,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
// src/corsair-tool-provider.ts
|
|
2
|
+
import { BaseToolProvider } from "@mastra/core/tool-provider";
|
|
3
|
+
import { getStructuredSchema, listOperations } from "corsair";
|
|
4
|
+
import { z as z2 } from "zod";
|
|
5
|
+
|
|
6
|
+
// src/form-field-to-zod.ts
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
function formFieldToZod(field) {
|
|
9
|
+
let schema = baseType(field);
|
|
10
|
+
if (field.description) schema = schema.describe(field.description);
|
|
11
|
+
if (field.optional) schema = schema.optional();
|
|
12
|
+
return schema;
|
|
13
|
+
}
|
|
14
|
+
function baseType(field) {
|
|
15
|
+
switch (field.kind) {
|
|
16
|
+
case "string":
|
|
17
|
+
return field.enum && field.enum.length > 0 ? z.enum(field.enum) : z.string();
|
|
18
|
+
case "number":
|
|
19
|
+
return z.number();
|
|
20
|
+
case "boolean":
|
|
21
|
+
return z.boolean();
|
|
22
|
+
case "literal":
|
|
23
|
+
return z.literal(field.value);
|
|
24
|
+
case "object": {
|
|
25
|
+
const shape = {};
|
|
26
|
+
for (const [key, value] of Object.entries(field.fields)) {
|
|
27
|
+
shape[key] = formFieldToZod(value);
|
|
28
|
+
}
|
|
29
|
+
return z.object(shape);
|
|
30
|
+
}
|
|
31
|
+
case "array":
|
|
32
|
+
return z.array(formFieldToZod(field.items));
|
|
33
|
+
case "unknown":
|
|
34
|
+
return z.unknown();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/corsair-tool-provider.ts
|
|
39
|
+
function scopeForTenant(tenantId) {
|
|
40
|
+
if (typeof tenantId === "string") return "shared";
|
|
41
|
+
if (typeof tenantId === "function") return "caller-supplied";
|
|
42
|
+
return "per-author";
|
|
43
|
+
}
|
|
44
|
+
function encodeConnectionId(tenantId, toolkit) {
|
|
45
|
+
return Buffer.from(
|
|
46
|
+
JSON.stringify({ t: tenantId, k: toolkit }),
|
|
47
|
+
"utf8"
|
|
48
|
+
).toString("base64url");
|
|
49
|
+
}
|
|
50
|
+
function decodeConnectionId(id) {
|
|
51
|
+
try {
|
|
52
|
+
const parsed = JSON.parse(Buffer.from(id, "base64url").toString("utf8"));
|
|
53
|
+
if (parsed && typeof parsed.t === "string" && typeof parsed.k === "string") {
|
|
54
|
+
return { tenantId: parsed.t, toolkit: parsed.k };
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
function mapAuthStatus(state) {
|
|
61
|
+
return state === "connected" ? "completed" : "pending";
|
|
62
|
+
}
|
|
63
|
+
function parseOperationPaths(listing) {
|
|
64
|
+
return listing.split("\n").map((line) => line.trim()).filter(Boolean);
|
|
65
|
+
}
|
|
66
|
+
async function invokeOperation(instance, path, args) {
|
|
67
|
+
const segments = path.split(".");
|
|
68
|
+
const method = segments.pop();
|
|
69
|
+
if (!method) throw new Error(`Invalid operation path: ${path}`);
|
|
70
|
+
let target = instance;
|
|
71
|
+
for (const segment of segments) {
|
|
72
|
+
const next = target?.[segment];
|
|
73
|
+
if (next == null) throw new Error(`Unknown operation path: ${path}`);
|
|
74
|
+
target = next;
|
|
75
|
+
}
|
|
76
|
+
const fn = target[method];
|
|
77
|
+
if (typeof fn !== "function")
|
|
78
|
+
throw new Error(`Operation is not callable: ${path}`);
|
|
79
|
+
return fn.call(target, args);
|
|
80
|
+
}
|
|
81
|
+
var CorsairToolProvider = class extends BaseToolProvider {
|
|
82
|
+
/** Provider identity surfaced in the Mastra tool picker. */
|
|
83
|
+
info = {
|
|
84
|
+
id: "corsair",
|
|
85
|
+
name: "Corsair",
|
|
86
|
+
description: "Managed OAuth and 200+ API integrations, with credentials stored in your own database."
|
|
87
|
+
};
|
|
88
|
+
/** Feature flags the Mastra runtime branches on (batch status, in-place reauth, …). */
|
|
89
|
+
capabilities = {
|
|
90
|
+
multipleConnectionsPerToolkit: false,
|
|
91
|
+
batchConnectionStatus: true,
|
|
92
|
+
reauthorizeReusesConnectionId: true,
|
|
93
|
+
supportsRevoke: true
|
|
94
|
+
};
|
|
95
|
+
corsair;
|
|
96
|
+
tenantConfig;
|
|
97
|
+
/**
|
|
98
|
+
* @param config - The Corsair instance plus optional tenant mapping and the
|
|
99
|
+
* inherited {@link BaseToolProviderOptions} allowlists. When `defaultScope`
|
|
100
|
+
* is omitted it is derived from `tenantId` (see {@link scopeForTenant}).
|
|
101
|
+
*/
|
|
102
|
+
constructor(config) {
|
|
103
|
+
super({
|
|
104
|
+
allowedToolkits: config.allowedToolkits,
|
|
105
|
+
allowedTools: config.allowedTools,
|
|
106
|
+
defaultScope: config.defaultScope ?? scopeForTenant(config.tenantId)
|
|
107
|
+
});
|
|
108
|
+
this.corsair = config.corsair;
|
|
109
|
+
this.tenantConfig = config.tenantId;
|
|
110
|
+
}
|
|
111
|
+
/** Returns the Corsair instance for use with inspect helpers. */
|
|
112
|
+
asInstance() {
|
|
113
|
+
return this.corsair;
|
|
114
|
+
}
|
|
115
|
+
/** Corsair's management namespace (plugins / connection status / connect). */
|
|
116
|
+
get manage() {
|
|
117
|
+
return this.corsair.manage;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Resolves a request to a Corsair tenant.
|
|
121
|
+
*
|
|
122
|
+
* The configured mapping is authoritative; a `connectionId` only ever carries
|
|
123
|
+
* a *claim* that must agree with it. `connectionId` is unauthenticated
|
|
124
|
+
* (base64url, not signed), so it must never let a caller reach a tenant the
|
|
125
|
+
* configuration wouldn't grant:
|
|
126
|
+
*
|
|
127
|
+
* - **Pinned (`string`)** — always that tenant; a connectionId for a different
|
|
128
|
+
* tenant is forged or stale and is ignored.
|
|
129
|
+
* - **Caller-known** (`authorId`/`requestContext` present) — derive the tenant
|
|
130
|
+
* from the caller and reject a connectionId that names a *different* tenant
|
|
131
|
+
* (cross-tenant access attempt).
|
|
132
|
+
* - **No caller context** (`authorize`, `getConnectionStatus`; see
|
|
133
|
+
* {@link AuthorizeOpts}) — the connectionId is the only tenant source.
|
|
134
|
+
* - **Fresh connection + function resolver** — unsupported: Mastra passes no
|
|
135
|
+
* author/request context to `authorize`, so throw rather than silently open
|
|
136
|
+
* OAuth under a fallback tenant.
|
|
137
|
+
*/
|
|
138
|
+
async resolveTenant(input) {
|
|
139
|
+
if (typeof this.tenantConfig === "string") return this.tenantConfig;
|
|
140
|
+
const claimed = input.connectionId ? decodeConnectionId(input.connectionId)?.tenantId : void 0;
|
|
141
|
+
if (input.authorId != null || input.requestContext != null) {
|
|
142
|
+
const derived = typeof this.tenantConfig === "function" ? await this.tenantConfig(input) : input.authorId ?? "default";
|
|
143
|
+
if (claimed != null && claimed !== derived) {
|
|
144
|
+
throw new Error(
|
|
145
|
+
"CorsairToolProvider: connectionId tenant does not match the caller \u2014 refusing cross-tenant access."
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
return derived;
|
|
149
|
+
}
|
|
150
|
+
if (claimed != null) return claimed;
|
|
151
|
+
if (typeof this.tenantConfig === "function") {
|
|
152
|
+
throw new Error(
|
|
153
|
+
"CorsairToolProvider: cannot resolve a tenant for a new connection. A function `tenantId` resolver needs author or request context, which Mastra does not pass to authorize \u2014 pin `tenantId` to a string, or supply a connectionId from encodeConnectionId(tenant, toolkit)."
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
return "default";
|
|
157
|
+
}
|
|
158
|
+
/** Scopes the Corsair instance to a tenant (multi-tenant), else returns it as-is. */
|
|
159
|
+
scopedInstance(tenantId) {
|
|
160
|
+
const withTenant = this.corsair.withTenant;
|
|
161
|
+
return typeof withTenant === "function" ? withTenant.call(this.corsair, tenantId) : this.asInstance();
|
|
162
|
+
}
|
|
163
|
+
// ── Discovery (BaseToolProvider layers allowlist filtering on top) ──────────
|
|
164
|
+
/**
|
|
165
|
+
* Every registered Corsair plugin becomes a toolkit. The base class applies
|
|
166
|
+
* `allowedToolkits` filtering on top before exposing this to the editor.
|
|
167
|
+
*/
|
|
168
|
+
async listAllToolkits() {
|
|
169
|
+
const plugins = await this.manage.plugins.list();
|
|
170
|
+
return plugins.map((plugin) => ({ slug: plugin.id, name: plugin.id }));
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Lists a plugin's API operations as tools, honouring the `toolkit`, `search`
|
|
174
|
+
* and pagination options. The base class applies `allowedTools` filtering on
|
|
175
|
+
* top.
|
|
176
|
+
*/
|
|
177
|
+
async listAllTools(opts) {
|
|
178
|
+
const listing = listOperations(this.asInstance(), {
|
|
179
|
+
plugin: opts?.toolkit,
|
|
180
|
+
type: "api"
|
|
181
|
+
});
|
|
182
|
+
let paths = parseOperationPaths(listing);
|
|
183
|
+
if (opts?.search) {
|
|
184
|
+
const needle = opts.search.toLowerCase();
|
|
185
|
+
paths = paths.filter((path) => path.toLowerCase().includes(needle));
|
|
186
|
+
}
|
|
187
|
+
const all = paths.map((path) => ({
|
|
188
|
+
slug: path,
|
|
189
|
+
name: path.split(".").pop() ?? path,
|
|
190
|
+
toolkit: path.split(".")[0]
|
|
191
|
+
}));
|
|
192
|
+
const perPage = opts?.perPage;
|
|
193
|
+
if (!perPage) {
|
|
194
|
+
return { data: all, pagination: { page: 1, hasMore: false } };
|
|
195
|
+
}
|
|
196
|
+
const page = opts?.page ?? 1;
|
|
197
|
+
const start = (page - 1) * perPage;
|
|
198
|
+
return {
|
|
199
|
+
data: all.slice(start, start + perPage),
|
|
200
|
+
pagination: { page, perPage, hasMore: start + perPage < all.length }
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* The JSON Schema for one tool's input, so the editor's tool-detail view can
|
|
205
|
+
* render it without materialising the tool. Built from Corsair's structured
|
|
206
|
+
* schema; `null` when the operation is unknown or takes no input.
|
|
207
|
+
*/
|
|
208
|
+
async getToolSchema(toolSlug) {
|
|
209
|
+
const schema = getStructuredSchema(this.asInstance(), toolSlug);
|
|
210
|
+
if (!schema?.input) return null;
|
|
211
|
+
return z2.toJSONSchema(formFieldToZod(schema.input));
|
|
212
|
+
}
|
|
213
|
+
// ── Runtime ─────────────────────────────────────────────────────────────────
|
|
214
|
+
/**
|
|
215
|
+
* Materialises executable Mastra tools for the requested slugs, bound to the
|
|
216
|
+
* resolved tenant's Corsair credentials. The runtime calls this once per
|
|
217
|
+
* connection; each tool's `execute` runs the Corsair operation with the
|
|
218
|
+
* managed token from your database.
|
|
219
|
+
*
|
|
220
|
+
* `ToolAction<any, any, any>` matches the abstract base class signature from
|
|
221
|
+
* `@mastra/core` — the input/output schemas are dynamically derived per plugin
|
|
222
|
+
* at runtime and cannot be statically parameterised.
|
|
223
|
+
*/
|
|
224
|
+
async resolveToolsVNext(opts) {
|
|
225
|
+
if (opts.toolSlugs.length === 0) return {};
|
|
226
|
+
const tenantId = await this.resolveTenant({
|
|
227
|
+
connectionId: opts.connectionId,
|
|
228
|
+
authorId: opts.authorId,
|
|
229
|
+
toolkit: opts.toolkit,
|
|
230
|
+
requestContext: opts.requestContext
|
|
231
|
+
});
|
|
232
|
+
const scoped = this.scopedInstance(tenantId);
|
|
233
|
+
const { createTool } = await import(
|
|
234
|
+
/* webpackIgnore: true */
|
|
235
|
+
/* turbopackIgnore: true */
|
|
236
|
+
"@mastra/core/tools"
|
|
237
|
+
);
|
|
238
|
+
const tools = {};
|
|
239
|
+
for (const slug of opts.toolSlugs) {
|
|
240
|
+
const schema = getStructuredSchema(this.asInstance(), slug);
|
|
241
|
+
const inputSchema = schema?.input ? formFieldToZod(schema.input) : z2.object({});
|
|
242
|
+
const description = opts.toolMeta?.[slug]?.description ?? schema?.description ?? slug;
|
|
243
|
+
tools[slug] = createTool({
|
|
244
|
+
id: slug,
|
|
245
|
+
description,
|
|
246
|
+
inputSchema,
|
|
247
|
+
execute: async (inputData) => invokeOperation(
|
|
248
|
+
scoped,
|
|
249
|
+
slug,
|
|
250
|
+
inputData ?? {}
|
|
251
|
+
)
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
return tools;
|
|
255
|
+
}
|
|
256
|
+
// ── Managed OAuth lifecycle ───────────────────────────────────────────────
|
|
257
|
+
/**
|
|
258
|
+
* Starts Corsair Hub's managed-OAuth flow for a toolkit and returns the
|
|
259
|
+
* connect URL to send the user to, plus an opaque `authId` to poll.
|
|
260
|
+
*/
|
|
261
|
+
async authorize(opts) {
|
|
262
|
+
const tenantId = await this.resolveTenant({
|
|
263
|
+
connectionId: opts.connectionId,
|
|
264
|
+
toolkit: opts.toolkit
|
|
265
|
+
});
|
|
266
|
+
const link = await this.manage.connect.createLink({
|
|
267
|
+
plugin: opts.toolkit,
|
|
268
|
+
tenantId
|
|
269
|
+
});
|
|
270
|
+
return {
|
|
271
|
+
url: link.connectUrl,
|
|
272
|
+
authId: encodeConnectionId(tenantId, opts.toolkit)
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Polls a managed-OAuth flow: returns `'completed'` once the tenant has a
|
|
277
|
+
* live credential for the toolkit, otherwise `'pending'` (`'failed'` only for
|
|
278
|
+
* an unreadable `authId`).
|
|
279
|
+
*/
|
|
280
|
+
async getAuthStatus(authId) {
|
|
281
|
+
const decoded = decodeConnectionId(authId);
|
|
282
|
+
if (!decoded) return "failed";
|
|
283
|
+
const status = await this.manage.connectionStatus.get({
|
|
284
|
+
tenantId: decoded.tenantId
|
|
285
|
+
});
|
|
286
|
+
return mapAuthStatus(status[decoded.toolkit]);
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Batch-checks whether each `(connectionId, toolkit)` is still connected,
|
|
290
|
+
* grouping by resolved tenant so one status call covers many items. Result is
|
|
291
|
+
* keyed by `connectionId`.
|
|
292
|
+
*/
|
|
293
|
+
async getConnectionStatus(opts) {
|
|
294
|
+
const result = {};
|
|
295
|
+
const byTenant = /* @__PURE__ */ new Map();
|
|
296
|
+
for (const item of opts.items) {
|
|
297
|
+
const tenantId = await this.resolveTenant({
|
|
298
|
+
connectionId: item.connectionId,
|
|
299
|
+
toolkit: item.toolkit
|
|
300
|
+
});
|
|
301
|
+
const group = byTenant.get(tenantId) ?? [];
|
|
302
|
+
group.push(item);
|
|
303
|
+
byTenant.set(tenantId, group);
|
|
304
|
+
}
|
|
305
|
+
for (const [tenantId, items] of byTenant) {
|
|
306
|
+
const status = await this.manage.connectionStatus.get({ tenantId });
|
|
307
|
+
for (const item of items) {
|
|
308
|
+
result[item.connectionId] = {
|
|
309
|
+
connected: status[item.toolkit] === "connected"
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return result;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Lists the already-connected accounts for the given user bucket(s) + toolkit
|
|
317
|
+
* so the picker can offer them without re-running OAuth. Corsair models one
|
|
318
|
+
* connection per (tenant, toolkit), so at most one item per bucket.
|
|
319
|
+
*/
|
|
320
|
+
async listConnections(opts) {
|
|
321
|
+
const targets = opts.userIds?.length ? opts.userIds : [opts.userId];
|
|
322
|
+
const items = [];
|
|
323
|
+
for (const userId of targets) {
|
|
324
|
+
const tenantId = await this.resolveTenant({
|
|
325
|
+
authorId: userId,
|
|
326
|
+
toolkit: opts.toolkit
|
|
327
|
+
});
|
|
328
|
+
const status = await this.manage.connectionStatus.get({ tenantId });
|
|
329
|
+
if (status[opts.toolkit] === "connected") {
|
|
330
|
+
items.push({
|
|
331
|
+
connectionId: encodeConnectionId(tenantId, opts.toolkit),
|
|
332
|
+
status: "active",
|
|
333
|
+
authorId: userId
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return { items, pagination: { page: 1, hasMore: false } };
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Revokes a connection by removing its stored credentials (and account-scoped
|
|
341
|
+
* data) through Corsair's management API. Idempotent per the ToolProvider
|
|
342
|
+
* contract: an unreadable `connectionId` or an already-gone connection
|
|
343
|
+
* resolves without error.
|
|
344
|
+
*/
|
|
345
|
+
async revokeConnection(connectionId) {
|
|
346
|
+
const decoded = decodeConnectionId(connectionId);
|
|
347
|
+
if (!decoded) return;
|
|
348
|
+
await this.manage.disconnect({
|
|
349
|
+
plugin: decoded.toolkit,
|
|
350
|
+
tenantId: decoded.tenantId
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
/** Reports provider health by probing Corsair's management API. */
|
|
354
|
+
async getHealth() {
|
|
355
|
+
try {
|
|
356
|
+
await this.manage.plugins.list();
|
|
357
|
+
return { ok: true };
|
|
358
|
+
} catch (err) {
|
|
359
|
+
return {
|
|
360
|
+
ok: false,
|
|
361
|
+
message: err instanceof Error ? err.message : "unavailable"
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
export {
|
|
367
|
+
CorsairToolProvider,
|
|
368
|
+
decodeConnectionId,
|
|
369
|
+
encodeConnectionId,
|
|
370
|
+
mapAuthStatus,
|
|
371
|
+
parseOperationPaths
|
|
372
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@corsair-dev/mastra",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Corsair ToolProvider for Mastra. Expose 200+ integrations to Mastra agents with managed OAuth and credentials that stay in your own database.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mastra",
|
|
7
|
+
"tool-provider",
|
|
8
|
+
"ai-agents",
|
|
9
|
+
"tools",
|
|
10
|
+
"tool-calling",
|
|
11
|
+
"integrations",
|
|
12
|
+
"managed-oauth",
|
|
13
|
+
"corsair"
|
|
14
|
+
],
|
|
15
|
+
"author": "Corsair (https://corsair.dev)",
|
|
16
|
+
"license": "Apache-2.0",
|
|
17
|
+
"homepage": "https://corsair.dev",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/corsairdev/corsair.git",
|
|
21
|
+
"directory": "adapters/mastra"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"main": "./dist/index.js",
|
|
25
|
+
"module": "./dist/index.js",
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"dev-source": "./src/index.ts",
|
|
33
|
+
"types": "./dist/index.d.ts",
|
|
34
|
+
"default": "./dist/index.js"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"dependencies": {
|
|
38
|
+
"zod": "^4.4.0",
|
|
39
|
+
"corsair": "0.1.129"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@mastra/core": ">=1.64.0"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"@mastra/core": {
|
|
46
|
+
"optional": true
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@mastra/core": "^1.64.0",
|
|
51
|
+
"@types/node": "^22.0.0",
|
|
52
|
+
"tsup": "^8.0.1",
|
|
53
|
+
"tsx": "^4.20.6",
|
|
54
|
+
"typescript": "^5.8.0"
|
|
55
|
+
},
|
|
56
|
+
"files": [
|
|
57
|
+
"dist"
|
|
58
|
+
],
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "tsup && tsc -p tsconfig.build.json",
|
|
61
|
+
"build:watch": "tsup --watch",
|
|
62
|
+
"typecheck": "tsc --noEmit",
|
|
63
|
+
"test": "tsx src/corsair-tool-provider.check.ts && tsx src/form-field-to-zod.check.ts"
|
|
64
|
+
}
|
|
65
|
+
}
|