@airctrl/mcp 0.2.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/dist/tools.js ADDED
@@ -0,0 +1,955 @@
1
+ import { z } from 'zod';
2
+ import { generateSecret, canGenerate, isSecretFormat, SECRET_FORMATS, TEMPLATES, AirctrlError, } from '@airctrl/sdk';
3
+ /**
4
+ * Build the one shared error type (SSOT R8) from the MCP's `(code, message, status)` call convention.
5
+ * The transport + error now live only in `@airctrl/sdk`; this is a thin arg-order adapter, not a
6
+ * second error class.
7
+ */
8
+ function apiError(code, message, status) {
9
+ return new AirctrlError(message, status, code);
10
+ }
11
+ /** Respuesta OK de un tool: el JSON del control plane como texto. */
12
+ function ok(data) {
13
+ const payload = data === undefined ? { ok: true } : data;
14
+ return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
15
+ }
16
+ /** Error de un tool: mensaje legible + `isError` para que el agente lo vea. */
17
+ function fail(e) {
18
+ const msg = e instanceof AirctrlError
19
+ ? `${e.code}: ${e.message}`
20
+ : e instanceof Error
21
+ ? e.message
22
+ : 'unknown error';
23
+ return { content: [{ type: 'text', text: `AIRCTRL error — ${msg}` }], isError: true };
24
+ }
25
+ async function run(fn) {
26
+ try {
27
+ return ok(await fn());
28
+ }
29
+ catch (e) {
30
+ return fail(e);
31
+ }
32
+ }
33
+ /**
34
+ * Copy-paste connection config for a gateway (data-plane base URLs). Compartido
35
+ * por `setup_gateway` (S3.1) y `get_connection_config` — la única fuente de la
36
+ * forma del snippet. El token de conexión NO se incluye aquí (lo devuelve
37
+ * `create_gateway_token` / `setup_gateway`).
38
+ */
39
+ function buildConnectionConfig(config, gw) {
40
+ const base = `${config.apiUrl}/gw/${gw.slug}`;
41
+ return {
42
+ gateway: gw.name,
43
+ slug: gw.slug,
44
+ openai_sdk: { base_url: `${base}/compat`, note: 'OpenAI SDK: base_url here, api_key = gateway token' },
45
+ openai_native: `${base}/openai/v1/chat/completions`,
46
+ claude_code: {
47
+ ANTHROPIC_BASE_URL: `${base}/anthropic`,
48
+ ANTHROPIC_AUTH_TOKEN: 'sk-actrl-*** (from create_gateway_token or setup_gateway)',
49
+ },
50
+ };
51
+ }
52
+ /**
53
+ * Prefijo obligatorio de las env vars que guardan provider keys. El prompt SOLO
54
+ * nombra la variable (nunca la key); el server lee su valor. La allowlist por
55
+ * prefijo evita que un prompt malicioso pida leer cualquier env var del sistema
56
+ * (`AWS_SECRET_*`, `PATH`, …) — solo se leen las del namespace `AIRCTRL_MCP_KEY_*`.
57
+ */
58
+ const PROVIDER_KEY_PREFIX = 'AIRCTRL_MCP_KEY_';
59
+ /**
60
+ * Resuelve el valor de una provider key desde el entorno, con allowlist por
61
+ * prefijo. Recibe el **nombre** de la env var (p. ej. `AIRCTRL_MCP_KEY_ANTHROPIC`);
62
+ * valida que tenga el prefijo permitido y que exista, y devuelve su valor.
63
+ * NUNCA loguea el valor.
64
+ */
65
+ function resolveProviderKeyEnv(varName) {
66
+ if (!varName.startsWith(PROVIDER_KEY_PREFIX)) {
67
+ throw apiError('invalid_key_env', `For security, provider keys must come from an env var named ${PROVIDER_KEY_PREFIX}* (got '${varName}'). ` +
68
+ `Add e.g. ${PROVIDER_KEY_PREFIX}ANTHROPIC_PROD to your MCP client config with your key as the value.`, 400);
69
+ }
70
+ const value = process.env[varName];
71
+ if (!value) {
72
+ throw apiError('missing_key_env', `Env var '${varName}' is not set in this MCP server's environment. Add it to your MCP client config ` +
73
+ `(.mcp.json / Warp) with your provider key as its value.`, 400);
74
+ }
75
+ return value;
76
+ }
77
+ function resolveJsonHeadersEnv(varName) {
78
+ const raw = resolveProviderKeyEnv(varName);
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(raw);
82
+ }
83
+ catch {
84
+ throw apiError('invalid_headers_env', 'OTel headers env must contain a JSON object of string values.', 400);
85
+ }
86
+ if (parsed === null ||
87
+ typeof parsed !== 'object' ||
88
+ Array.isArray(parsed) ||
89
+ Object.values(parsed).some((value) => typeof value !== 'string')) {
90
+ throw apiError('invalid_headers_env', 'OTel headers env must contain a JSON object of string values.', 400);
91
+ }
92
+ return parsed;
93
+ }
94
+ /**
95
+ * Busca una credencial reutilizable para evitar duplicados: misma `label`
96
+ * (= nombre de la env var), mismo provider, válida y no revocada. El dedup es
97
+ * por **nombre de variable**, no por el valor de la key (el valor lo controla el
98
+ * dev; nosotros solo lo leemos). Devuelve la credencial o `null`.
99
+ */
100
+ async function findReusableCredential(client, accountId, match) {
101
+ const creds = await client.listProviderCredentials(accountId);
102
+ return (creds.find((c) => !c.revoked_at &&
103
+ c.validation_status === 'valid' &&
104
+ c.label === match.label &&
105
+ (match.credentialKind === undefined || c.credential_kind === match.credentialKind) &&
106
+ (match.providerSlug ? c.provider_slug === match.providerSlug : c.provider_id === match.providerId)) ?? null);
107
+ }
108
+ /**
109
+ * Registra los tools de gestión del gateway (Fase 2, P2-1). Cada tool valida su
110
+ * input con Zod y llama al control plane con el principal configurado (via `AirctrlClient`). Las
111
+ * responses de administración son metadata, excepto los valores de una sola
112
+ * lectura que el caller pidió explícitamente: gateway tokens recién creados y
113
+ * records descifrados por `get_secret` / `read_record` / `get_all`. Las provider
114
+ * keys NUNCA se devuelven (D-P2.5).
115
+ */
116
+ /**
117
+ * Vault password para descifrar records — SIEMPRE del env del server
118
+ * (`AIRCTRL_MCP_VAULT_PASSWORD`), NUNCA del prompt (mismo principio que las
119
+ * provider keys). Lanza un error accionable si no está configurado.
120
+ */
121
+ function recordUnlockPassword(config) {
122
+ if (config.principalType === 'service_account')
123
+ return undefined;
124
+ if (!config.vaultPassword) {
125
+ throw apiError('no_vault_password', 'Human record decryption needs a vault password. Set AIRCTRL_MCP_VAULT_PASSWORD in this MCP server config. Service Accounts use their configured credential bundle instead.', 0);
126
+ }
127
+ return config.vaultPassword;
128
+ }
129
+ /** Tools backed only by operations that explicitly accept Service Account credentials. */
130
+ export const SERVICE_ACCOUNT_MCP_TOOLS = [
131
+ 'list_providers',
132
+ 'get_connection_config',
133
+ 'list_gateway_tokens',
134
+ 'read_usage',
135
+ 'read_gateway_log',
136
+ 'read_gateway_key_access',
137
+ 'list_records',
138
+ 'get_secret',
139
+ 'read_record',
140
+ 'list_secret_types',
141
+ 'generate_secret',
142
+ 'get_all',
143
+ ];
144
+ function serverForPrincipal(server, config) {
145
+ if (config.principalType !== 'service_account')
146
+ return server;
147
+ const allowed = new Set(SERVICE_ACCOUNT_MCP_TOOLS);
148
+ const registerTool = server.registerTool.bind(server);
149
+ return {
150
+ registerTool(name, ...args) {
151
+ if (allowed.has(name))
152
+ return registerTool(name, ...args);
153
+ return undefined;
154
+ },
155
+ };
156
+ }
157
+ export function registerTools(inputServer, client, config) {
158
+ const server = serverForPrincipal(inputServer, config);
159
+ server.registerTool('list_accounts', {
160
+ title: 'List accessible accounts',
161
+ description: 'List the AIRCTRL accounts the authenticated developer can access. This discovers context only; it does not administer an account.',
162
+ inputSchema: {},
163
+ }, () => run(() => client.listAccounts()));
164
+ server.registerTool('list_projects', {
165
+ title: 'List accessible projects',
166
+ description: 'List projects the authenticated developer belongs to in one AIRCTRL account.',
167
+ inputSchema: {
168
+ accountId: z.string().uuid(),
169
+ includeArchived: z.boolean().optional(),
170
+ },
171
+ }, ({ accountId, includeArchived }) => run(() => client.listProjects({ accountId, includeArchived })));
172
+ server.registerTool('get_project', {
173
+ title: 'Get project',
174
+ description: 'Read one AIRCTRL project the authenticated developer can access.',
175
+ inputSchema: {
176
+ accountId: z.string().uuid(),
177
+ projectId: z.string().uuid(),
178
+ },
179
+ }, ({ accountId, projectId }) => run(() => client.getProject(projectId, { accountId })));
180
+ server.registerTool('create_project', {
181
+ title: 'Create project',
182
+ description: 'Create an AIRCTRL project in an account. The API checks projects:create and quota, then makes the creator Project Administrator.',
183
+ inputSchema: {
184
+ accountId: z.string().uuid(),
185
+ name: z.string().min(1),
186
+ description: z.string().optional(),
187
+ },
188
+ }, ({ accountId, name, description }) => run(() => client.createProject({ accountId, name, description })));
189
+ server.registerTool('update_project', {
190
+ title: 'Update project',
191
+ description: 'Replace a project name, description and active state. Pass null to clear the description; all three editable fields are required.',
192
+ inputSchema: {
193
+ accountId: z.string().uuid(),
194
+ projectId: z.string().uuid(),
195
+ name: z.string().min(1),
196
+ description: z.string().nullable(),
197
+ isActive: z.boolean(),
198
+ },
199
+ }, ({ accountId, projectId, name, description, isActive }) => run(() => client.updateProject(projectId, { name, description, isActive }, { accountId })));
200
+ server.registerTool('set_project_archive', {
201
+ title: 'Archive or restore project',
202
+ description: 'Archive or restore one AIRCTRL project.',
203
+ inputSchema: {
204
+ accountId: z.string().uuid(),
205
+ projectId: z.string().uuid(),
206
+ archived: z.boolean(),
207
+ },
208
+ }, ({ accountId, projectId, archived }) => run(() => client.setProjectArchiveState(projectId, archived, { accountId })));
209
+ server.registerTool('list_service_accounts', {
210
+ title: 'List Service Accounts',
211
+ description: 'List Service Account metadata and active/revoked state in one AIRCTRL account. Credential material is never returned.',
212
+ inputSchema: { accountId: z.string().uuid() },
213
+ }, ({ accountId }) => run(() => client.listServiceAccounts({ accountId })));
214
+ server.registerTool('get_service_account', {
215
+ title: 'Get Service Account',
216
+ description: 'Read metadata and active/revoked state for one Service Account. This does not manage its credentials.',
217
+ inputSchema: {
218
+ accountId: z.string().uuid(),
219
+ serviceAccountId: z.string().uuid(),
220
+ },
221
+ }, ({ accountId, serviceAccountId }) => run(() => client.getServiceAccount(serviceAccountId, { accountId })));
222
+ server.registerTool('list_providers', {
223
+ title: 'List providers',
224
+ description: 'List the AI providers AIRCTRL supports (OpenAI, Anthropic, Gemini, …) with their ids. Use this to get a providerId for add_provider_key or set_routing.',
225
+ inputSchema: {},
226
+ }, () => run(() => client.listProviders()));
227
+ server.registerTool('list_gateways', {
228
+ title: 'List gateways',
229
+ description: 'List the gateways in a project.',
230
+ inputSchema: { projectId: z.string().uuid() },
231
+ }, ({ projectId }) => run(() => client.listGateways(projectId)));
232
+ server.registerTool('create_gateway', {
233
+ title: 'Create gateway',
234
+ description: 'Create an empty gateway in a project. Use this only when you need a bare gateway; if the user is connecting a provider key, prefer ' +
235
+ 'setup_gateway, which creates the gateway, stores the key, and mints a token in one call.',
236
+ inputSchema: {
237
+ accountId: z.string().uuid(),
238
+ projectId: z.string().uuid(),
239
+ name: z.string().min(1).max(100),
240
+ slug: z.string().max(64).optional(),
241
+ defaultProviderId: z.string().uuid().nullable().optional(),
242
+ defaultModel: z.string().max(200).nullable().optional(),
243
+ credentialIds: z.array(z.string().uuid()).optional(),
244
+ credentialBindings: z.array(z.object({
245
+ credentialId: z.string().uuid(),
246
+ modelId: z.string().min(1).max(200),
247
+ })).optional(),
248
+ },
249
+ }, ({ accountId, ...args }) => run(() => client.createGateway({ accountId, ...args })));
250
+ server.registerTool('add_provider_key', {
251
+ title: 'Add provider key (BYOK)',
252
+ description: "Add an org provider API key (BYOK). NEVER pass the key itself — pass apiKeyEnv, the NAME of an environment " +
253
+ "variable in this MCP server's config that holds the key (must be named AIRCTRL_MCP_KEY_*, e.g. " +
254
+ "AIRCTRL_MCP_KEY_ANTHROPIC_PROD). The server reads that variable, validates the key against the provider, and " +
255
+ "stores it encrypted — it is NEVER returned. If a credential with the same variable name already exists it is " +
256
+ "reused (no duplicates). accountId and providerId come from the project / list_providers.",
257
+ inputSchema: {
258
+ accountId: z.string().uuid(),
259
+ providerId: z.string().uuid(),
260
+ apiKeyEnv: z.string().min(1),
261
+ label: z.string().min(1).max(100).optional(),
262
+ baseUrlOverride: z.string().optional(),
263
+ credentialKind: z.enum(['api_key', 'oauth', 'aws_sigv4', 'gcp_sa']).optional(),
264
+ },
265
+ }, ({ accountId, providerId, apiKeyEnv, label, baseUrlOverride, credentialKind }) => run(async () => {
266
+ const keyValue = resolveProviderKeyEnv(apiKeyEnv);
267
+ const credLabel = label?.trim() || apiKeyEnv;
268
+ const existing = await findReusableCredential(client, accountId, {
269
+ label: credLabel,
270
+ providerId,
271
+ credentialKind,
272
+ });
273
+ if (existing) {
274
+ return {
275
+ credential_id: existing.credential_id,
276
+ validation_status: existing.validation_status,
277
+ reused: true,
278
+ key_note: `Found an existing key '${credLabel}' — reusing it to avoid duplicates.`,
279
+ };
280
+ }
281
+ const created = await client.createProviderCredential({
282
+ accountId,
283
+ providerId,
284
+ label: credLabel,
285
+ apiKey: keyValue,
286
+ baseUrlOverride,
287
+ credentialKind,
288
+ });
289
+ return {
290
+ credential_id: created.credential_id,
291
+ validation_status: created.validation_status,
292
+ reused: false,
293
+ key_note: `Stored the key from '${apiKeyEnv}' (encrypted).`,
294
+ };
295
+ }));
296
+ server.registerTool('rotate_provider_key', {
297
+ title: 'Rotate provider key',
298
+ description: 'Replace an existing provider credential from an AIRCTRL_MCP_KEY_* environment variable. NEVER pass the provider key itself: pass apiKeyEnv, the variable name. The replacement is re-validated and re-encrypted.',
299
+ inputSchema: {
300
+ accountId: z.string().uuid(),
301
+ credentialId: z.string().uuid(),
302
+ apiKeyEnv: z.string().min(1),
303
+ },
304
+ }, ({ accountId, credentialId, apiKeyEnv }) => run(() => client.rotateProviderCredential(credentialId, resolveProviderKeyEnv(apiKeyEnv), { accountId })));
305
+ server.registerTool('set_routing', {
306
+ title: 'Set gateway routing',
307
+ description: 'Update gateway metadata/default routing and optionally attach a provider credential to one supported model. ' +
308
+ 'When attachCredentialId is present, defaultModel must be the model for that binding.',
309
+ inputSchema: {
310
+ accountId: z.string().uuid(),
311
+ gatewayId: z.string().uuid(),
312
+ name: z.string().min(1).max(100).optional(),
313
+ isActive: z.boolean().optional(),
314
+ defaultProviderId: z.string().uuid().nullable().optional(),
315
+ defaultModel: z.string().max(200).nullable().optional(),
316
+ attachCredentialId: z.string().uuid().optional(),
317
+ },
318
+ }, ({ accountId, gatewayId, name, isActive, defaultProviderId, defaultModel, attachCredentialId }) => run(async () => {
319
+ if (attachCredentialId && (typeof defaultModel !== 'string' || defaultModel.length === 0)) {
320
+ throw new Error('defaultModel is required when attachCredentialId is provided');
321
+ }
322
+ const attached = attachCredentialId
323
+ ? await client.attachGatewayCredential(gatewayId, attachCredentialId, defaultModel, { accountId })
324
+ : null;
325
+ // The backend only accepts a default route that already has a validated
326
+ // credential/model binding, so attach first and then choose it as the
327
+ // default when the caller supplied the provider explicitly.
328
+ const patch = {};
329
+ if (name !== undefined)
330
+ patch.name = name;
331
+ if (isActive !== undefined)
332
+ patch.isActive = isActive;
333
+ if (defaultProviderId !== undefined)
334
+ patch.defaultProviderId = defaultProviderId;
335
+ if (defaultModel !== undefined)
336
+ patch.defaultModel = defaultModel;
337
+ if (!attachCredentialId && Object.keys(patch).length === 0) {
338
+ throw apiError('invalid_gateway_patch', 'At least one routing or gateway field is required.', 400);
339
+ }
340
+ const gateway = Object.keys(patch).length
341
+ ? await client.updateGateway(gatewayId, patch, { accountId })
342
+ : null;
343
+ return { gateway, attached };
344
+ }));
345
+ server.registerTool('create_gateway_token', {
346
+ title: 'Create gateway token',
347
+ description: "Create a gateway token (the data-plane connection credential, 'sk-actrl-*'). The plaintext is returned ONCE — give it to the client (e.g. ANTHROPIC_AUTH_TOKEN). It is not retrievable again.",
348
+ inputSchema: {
349
+ accountId: z.string().uuid(),
350
+ gatewayId: z.string().uuid(),
351
+ name: z.string().min(1).max(64),
352
+ scopes: z.array(z.enum(['run', 'read_logs', 'manage'])).optional(),
353
+ expiresInDays: z.number().int().min(1).nullable().optional(),
354
+ principal: z.object({
355
+ type: z.enum(['user', 'service_account']),
356
+ id: z.string().uuid(),
357
+ }).optional(),
358
+ allowedModels: z.array(z.string().max(200)).optional(),
359
+ spendLimit: z.number().min(0).nullable().optional(),
360
+ spendWindow: z.enum(['daily', 'weekly', 'monthly']).optional(),
361
+ rateLimitPerMin: z.number().int().min(1).nullable().optional(),
362
+ },
363
+ }, ({ accountId, gatewayId, ...input }) => run(() => client.createGatewayToken(gatewayId, input, { accountId })));
364
+ server.registerTool('read_usage', {
365
+ title: 'Read gateway usage',
366
+ description: 'Read a gateway request logs (provider, model, status, tokens, cost, latency).',
367
+ inputSchema: {
368
+ gatewayId: z.string().uuid(),
369
+ since: z.string().optional(),
370
+ provider: z.string().max(64).optional(),
371
+ model: z.string().max(200).optional(),
372
+ status: z.number().int().min(100).max(599).optional(),
373
+ limit: z.number().int().min(1).max(200).optional(),
374
+ offset: z.number().int().min(0).optional(),
375
+ },
376
+ }, ({ gatewayId, ...input }) => run(() => client.listGatewayLogs(gatewayId, input)));
377
+ server.registerTool('list_usage_logs', {
378
+ title: 'List project usage logs',
379
+ description: 'Read request-log metadata across every gateway in one project.',
380
+ inputSchema: {
381
+ projectId: z.string().uuid(),
382
+ since: z.string().optional(),
383
+ provider: z.string().max(64).optional(),
384
+ model: z.string().max(200).optional(),
385
+ status: z.number().int().min(100).max(599).optional(),
386
+ gatewayId: z.string().uuid().optional(),
387
+ limit: z.number().int().min(1).max(200).optional(),
388
+ offset: z.number().int().min(0).optional(),
389
+ },
390
+ }, (input) => run(() => client.listUsageLogs(input)));
391
+ server.registerTool('read_usage_log', {
392
+ title: 'Read project usage log detail',
393
+ description: 'Read stored request and response bodies for one project usage log when authorized.',
394
+ inputSchema: { projectId: z.string().uuid(), logId: z.string().uuid() },
395
+ }, ({ projectId, logId }) => run(() => client.getUsageLogDetail(projectId, logId)));
396
+ server.registerTool('read_usage_spend', {
397
+ title: 'Read project spend',
398
+ description: 'Read spend versus configured caps for a project.',
399
+ inputSchema: { projectId: z.string().uuid() },
400
+ }, ({ projectId }) => run(() => client.getUsageSpend(projectId)));
401
+ server.registerTool('read_usage_metrics', {
402
+ title: 'Read project usage metrics',
403
+ description: 'Read bucketed usage metrics and KPIs for a project.',
404
+ inputSchema: {
405
+ projectId: z.string().uuid(),
406
+ since: z.string().optional(),
407
+ bucket: z.enum(['hour', 'day']).optional(),
408
+ },
409
+ }, ({ projectId, since, bucket }) => run(() => client.getUsageMetrics(projectId, { since, bucket })));
410
+ server.registerTool('get_connection_config', {
411
+ title: 'Get connection config',
412
+ description: 'Compose the copy-paste connection config for a gateway: the data-plane base URLs for the OpenAI SDK (/compat), OpenAI-native, and Claude Code (/anthropic). Pair with a token from create_gateway_token.',
413
+ inputSchema: { gatewayId: z.string().uuid() },
414
+ }, ({ gatewayId }) => run(async () => {
415
+ const gw = await client.getGateway(gatewayId);
416
+ return buildConnectionConfig(config, gw);
417
+ }));
418
+ server.registerTool('setup_gateway', {
419
+ title: 'Set up a gateway (one-shot)',
420
+ description: "One call for the common request 'connect my <provider> key to AIRCTRL'. NEVER pass the key itself — pass " +
421
+ 'apiKeyEnv, the NAME of an environment variable in this MCP server config that holds the key (must be named ' +
422
+ 'AIRCTRL_MCP_KEY_*, e.g. AIRCTRL_MCP_KEY_ANTHROPIC_PROD). Given a projectId, a provider slug (from ' +
423
+ 'list_providers: openai/anthropic/gemini) and apiKeyEnv, this: (1) reads the key from that env var and stores ' +
424
+ 'it encrypted (BYOK, validated against the provider) — reusing an existing credential with the same variable ' +
425
+ 'name instead of duplicating, (2) verifies defaultModel against that key\'s live catalog and creates a gateway ' +
426
+ 'with the exact key/model binding as its default route, (3) mints a gateway ' +
427
+ 'connection token, and (4) returns the copy-paste connection config. Prefer this over chaining create_gateway ' +
428
+ '+ add_provider_key + set_routing + create_gateway_token. The gateway token is returned ONCE; the provider key ' +
429
+ 'is never returned.',
430
+ inputSchema: {
431
+ projectId: z.string().uuid(),
432
+ provider: z.string().min(1),
433
+ apiKeyEnv: z.string().min(1),
434
+ name: z.string().min(1).max(100).optional(),
435
+ defaultModel: z.string().min(1).max(200),
436
+ tokenName: z.string().min(1).max(64).optional(),
437
+ baseUrlOverride: z.string().optional(),
438
+ },
439
+ }, (args) => run(async () => {
440
+ const { projectId, provider, apiKeyEnv, defaultModel, baseUrlOverride } = args;
441
+ // 1. Resolve the key value from the named env var (allowlisted prefix).
442
+ const keyValue = resolveProviderKeyEnv(apiKeyEnv);
443
+ // 2. Resolve the account from the project (also verifies membership).
444
+ const project = await client.get(`projects/${projectId}`);
445
+ if (!project?.account_id) {
446
+ throw apiError('project_not_found', `Project '${projectId}' not found, or your token has no access to it. Check the projectId and that your PAT's user is a member.`, 404);
447
+ }
448
+ // 3. Resolve the provider slug -> id from the registry.
449
+ const providers = await client.listProviders();
450
+ const prov = providers.find((p) => p.slug === provider.toLowerCase());
451
+ if (!prov) {
452
+ const slugs = providers.map((p) => p.slug).join(', ');
453
+ throw apiError('provider_not_found', `Unknown provider '${provider}'. Available: ${slugs}.`, 400);
454
+ }
455
+ const name = args.name?.trim() || `${prov.display_name} gateway`;
456
+ const tokenName = args.tokenName?.trim() || 'default';
457
+ // 4. Dedup by variable name (= label): reuse an existing valid credential
458
+ // instead of piling up duplicates. Otherwise store + validate the key.
459
+ const existing = await findReusableCredential(client, project.account_id, {
460
+ label: apiKeyEnv,
461
+ providerSlug: prov.slug,
462
+ });
463
+ let credentialId;
464
+ const reusedKey = existing !== null;
465
+ if (existing) {
466
+ credentialId = existing.credential_id;
467
+ }
468
+ else {
469
+ const credential = await client.createProviderCredential({
470
+ accountId: project.account_id,
471
+ providerId: prov.provider_id,
472
+ label: apiKeyEnv,
473
+ apiKey: keyValue,
474
+ baseUrlOverride,
475
+ });
476
+ credentialId = credential.credential_id;
477
+ }
478
+ // 5. Create the gateway with one explicit key/model binding and use it as the default route.
479
+ let gateway;
480
+ try {
481
+ gateway = await client.createGateway({
482
+ accountId: project.account_id,
483
+ projectId,
484
+ name,
485
+ defaultProviderId: prov.provider_id,
486
+ defaultModel,
487
+ credentialBindings: [{ credentialId, modelId: defaultModel }],
488
+ });
489
+ }
490
+ catch (e) {
491
+ // Roll back ONLY a credential we just created (never a reused one).
492
+ if (!reusedKey) {
493
+ try {
494
+ await client.revokeProviderCredential(credentialId, { accountId: project.account_id });
495
+ }
496
+ catch {
497
+ // best-effort cleanup; surface the original error below
498
+ }
499
+ }
500
+ throw e;
501
+ }
502
+ // 6. Mint the connection token (plaintext returned once).
503
+ const token = await client.createGatewayToken(gateway.gateway_id, { name: tokenName }, { accountId: project.account_id });
504
+ return {
505
+ gateway: { id: gateway.gateway_id, slug: gateway.slug, name: gateway.name },
506
+ provider: { slug: prov.slug, credential_id: credentialId },
507
+ key_note: reusedKey
508
+ ? `Found an existing key '${apiKeyEnv}' — reusing it to avoid duplicates.`
509
+ : `Stored the key from '${apiKeyEnv}' (encrypted).`,
510
+ token: {
511
+ value: token.plaintext,
512
+ prefix: token.token.token_prefix,
513
+ note: 'Shown once — store it now. Use as the gateway token (e.g. ANTHROPIC_AUTH_TOKEN or the OpenAI SDK api_key).',
514
+ },
515
+ connection: buildConnectionConfig(config, gateway),
516
+ };
517
+ }));
518
+ server.registerTool('delete_gateway', {
519
+ title: 'Delete gateway',
520
+ description: 'Soft-delete a gateway and revoke its connection tokens.',
521
+ inputSchema: { accountId: z.string().uuid(), gatewayId: z.string().uuid() },
522
+ }, ({ accountId, gatewayId }) => run(() => client.deleteGateway(gatewayId, { accountId })));
523
+ server.registerTool('list_gateway_tokens', {
524
+ title: 'List gateway tokens',
525
+ description: 'List gateway token metadata. Plaintext token values are never returned.',
526
+ inputSchema: { gatewayId: z.string().uuid() },
527
+ }, ({ gatewayId }) => run(() => client.listGatewayTokens(gatewayId)));
528
+ server.registerTool('revoke_gateway_token', {
529
+ title: 'Revoke gateway token',
530
+ description: 'Revoke a gateway token immediately.',
531
+ inputSchema: {
532
+ accountId: z.string().uuid(),
533
+ gatewayId: z.string().uuid(),
534
+ tokenId: z.string().uuid(),
535
+ },
536
+ }, ({ accountId, gatewayId, tokenId }) => run(() => client.revokeGatewayToken(gatewayId, tokenId, { accountId })));
537
+ server.registerTool('rename_gateway_token', {
538
+ title: 'Rename gateway token',
539
+ description: 'Change the display name of a gateway token.',
540
+ inputSchema: {
541
+ accountId: z.string().uuid(),
542
+ gatewayId: z.string().uuid(),
543
+ tokenId: z.string().uuid(),
544
+ name: z.string().min(1).max(64),
545
+ },
546
+ }, ({ accountId, gatewayId, tokenId, name }) => run(() => client.renameGatewayToken(gatewayId, tokenId, name, { accountId })));
547
+ server.registerTool('delete_gateway_token', {
548
+ title: 'Delete gateway token',
549
+ description: 'Delete a gateway token from the control-plane registry.',
550
+ inputSchema: {
551
+ accountId: z.string().uuid(),
552
+ gatewayId: z.string().uuid(),
553
+ tokenId: z.string().uuid(),
554
+ },
555
+ }, ({ accountId, gatewayId, tokenId }) => run(() => client.deleteGatewayToken(gatewayId, tokenId, { accountId })));
556
+ server.registerTool('set_gateway_settings', {
557
+ title: 'Set gateway settings',
558
+ description: 'Update gateway spend, rate, logging, guardrail, cache, and model settings.',
559
+ inputSchema: {
560
+ accountId: z.string().uuid(),
561
+ gatewayId: z.string().uuid(),
562
+ spendLimit: z.number().min(0).nullable().optional(),
563
+ spendWindow: z.enum(['daily', 'weekly', 'monthly']).optional(),
564
+ rateLimitPerMin: z.number().int().min(1).nullable().optional(),
565
+ loggingEnabled: z.boolean().optional(),
566
+ logBodies: z.boolean().optional(),
567
+ guardrailMode: z.enum(['off', 'flag', 'redact', 'block']).optional(),
568
+ cacheEnabled: z.boolean().optional(),
569
+ cacheTtlSeconds: z.number().int().min(60).optional(),
570
+ allowedModels: z.array(z.string().max(200)).optional(),
571
+ },
572
+ }, ({ accountId, gatewayId, ...settings }) => run(() => client.updateGatewaySettings(gatewayId, settings, { accountId })));
573
+ server.registerTool('get_otel_export', {
574
+ title: 'Get gateway OTel export',
575
+ description: 'Read the safe OpenTelemetry export configuration for a gateway.',
576
+ inputSchema: { accountId: z.string().uuid(), gatewayId: z.string().uuid() },
577
+ }, ({ accountId, gatewayId }) => run(() => client.getGatewayOtelExport(gatewayId, { accountId })));
578
+ server.registerTool('set_otel_export', {
579
+ title: 'Set gateway OTel export',
580
+ description: `Update OpenTelemetry export settings. Optional auth headers come only from an ${PROVIDER_KEY_PREFIX}* env var containing a JSON object.`,
581
+ inputSchema: {
582
+ accountId: z.string().uuid(),
583
+ gatewayId: z.string().uuid(),
584
+ enabled: z.boolean().optional(),
585
+ endpoint: z.string().nullable().optional(),
586
+ exportMetrics: z.boolean().optional(),
587
+ exportTraces: z.boolean().optional(),
588
+ headersEnv: z.string().optional(),
589
+ clearHeaders: z.boolean().optional(),
590
+ },
591
+ }, ({ accountId, gatewayId, headersEnv, clearHeaders, ...settings }) => run(() => {
592
+ if (headersEnv !== undefined && clearHeaders !== undefined) {
593
+ throw apiError('invalid_otel_headers', 'Use headersEnv or clearHeaders, not both.', 400);
594
+ }
595
+ const headers = clearHeaders
596
+ ? null
597
+ : headersEnv === undefined
598
+ ? undefined
599
+ : resolveJsonHeadersEnv(headersEnv);
600
+ return client.updateGatewayOtelExport(gatewayId, { ...settings, ...(headers === undefined ? {} : { headers }) }, { accountId });
601
+ }));
602
+ server.registerTool('detach_gateway_credential', {
603
+ title: 'Detach gateway credential',
604
+ description: 'Detach a provider credential from a gateway.',
605
+ inputSchema: {
606
+ accountId: z.string().uuid(),
607
+ gatewayId: z.string().uuid(),
608
+ credentialId: z.string().uuid(),
609
+ },
610
+ }, ({ accountId, gatewayId, credentialId }) => run(() => client.detachGatewayCredential(gatewayId, credentialId, { accountId })));
611
+ server.registerTool('read_gateway_log', {
612
+ title: 'Read gateway log detail',
613
+ description: 'Read stored request and response bodies for one gateway log when authorized.',
614
+ inputSchema: { gatewayId: z.string().uuid(), logId: z.string().uuid() },
615
+ }, ({ gatewayId, logId }) => run(() => client.getGatewayLogDetail(gatewayId, logId)));
616
+ server.registerTool('read_gateway_key_access', {
617
+ title: 'Read gateway key access',
618
+ description: 'Read the immutable provider-key access audit for a gateway.',
619
+ inputSchema: {
620
+ gatewayId: z.string().uuid(),
621
+ outcome: z.enum(['granted', 'denied', 'error']).optional(),
622
+ since: z.string().optional(),
623
+ limit: z.number().int().min(1).max(200).optional(),
624
+ offset: z.number().int().min(0).optional(),
625
+ },
626
+ }, ({ gatewayId, outcome, since, limit, offset }) => run(() => client.listGatewayKeyAccess(gatewayId, { outcome, since, limit, offset })));
627
+ server.registerTool('list_provider_credentials', {
628
+ title: 'List provider credentials',
629
+ description: 'List provider credential metadata for an account. Secret values are never returned.',
630
+ inputSchema: { accountId: z.string().uuid() },
631
+ }, ({ accountId }) => run(() => client.listProviderCredentials(accountId)));
632
+ server.registerTool('list_provider_models', {
633
+ title: 'List provider models',
634
+ description: 'List the live models available through the provider credential. Provider secrets are never returned.',
635
+ inputSchema: { accountId: z.string().uuid(), credentialId: z.string().uuid() },
636
+ }, ({ accountId, credentialId }) => run(() => client.listProviderCredentialModels(credentialId, { accountId })));
637
+ server.registerTool('rename_provider_credential', {
638
+ title: 'Rename provider credential',
639
+ description: 'Change the display label of a provider credential.',
640
+ inputSchema: {
641
+ accountId: z.string().uuid(),
642
+ credentialId: z.string().uuid(),
643
+ label: z.string().min(1).max(100),
644
+ },
645
+ }, ({ accountId, credentialId, label }) => run(() => client.updateProviderCredentialLabel(credentialId, label, { accountId })));
646
+ server.registerTool('revoke_provider_credential', {
647
+ title: 'Revoke provider credential',
648
+ description: 'Revoke a provider credential so gateways can no longer use it.',
649
+ inputSchema: { accountId: z.string().uuid(), credentialId: z.string().uuid() },
650
+ }, ({ accountId, credentialId }) => run(() => client.revokeProviderCredential(credentialId, { accountId })));
651
+ // ── Records — Universal secret injection (E3) ──────────────────────────────
652
+ server.registerTool('list_records', {
653
+ title: 'List records',
654
+ description: 'List accessible secret records — metadata only, never secret values. Optionally scope the list to one project.',
655
+ inputSchema: {
656
+ projectId: z.string().uuid().optional(),
657
+ accountId: z.string().uuid().optional(),
658
+ tab: z.enum(['owned', 'shared']).optional(),
659
+ includeArchived: z.boolean().optional(),
660
+ limit: z.number().int().min(1).max(1000).optional(),
661
+ offset: z.number().int().min(0).optional(),
662
+ },
663
+ }, ({ projectId, accountId, tab, includeArchived, limit, offset }) => run(() => projectId
664
+ ? client.listProjectRecords(projectId, { includeArchived, limit, offset })
665
+ : client.listRecords({ accountId, tab, includeArchived, limit, offset })));
666
+ server.registerTool('list_record_versions', {
667
+ title: 'List record versions',
668
+ description: 'List the immutable version history metadata for one record.',
669
+ inputSchema: { recordId: z.string().uuid() },
670
+ }, ({ recordId }) => run(() => client.getRecordVersions(recordId)));
671
+ server.registerTool('read_record_audit', {
672
+ title: 'Read record audit',
673
+ description: 'Read audit-event metadata for one record. Secret values are never returned.',
674
+ inputSchema: {
675
+ recordId: z.string().uuid(),
676
+ limit: z.number().int().min(1).max(1000).optional(),
677
+ },
678
+ }, ({ recordId, limit }) => run(() => client.getRecordAudit(recordId, limit)));
679
+ server.registerTool('update_record_metadata', {
680
+ title: 'Update record metadata',
681
+ description: 'Update a record name, tags, due date, or rotation interval without changing ciphertext.',
682
+ inputSchema: {
683
+ recordId: z.string().uuid(),
684
+ name: z.string().min(1).optional(),
685
+ tags: z.array(z.string()).optional(),
686
+ secretDueAt: z.string().nullable().optional(),
687
+ rotationIntervalDays: z.number().int().min(1).nullable().optional(),
688
+ },
689
+ }, ({ recordId, ...patch }) => {
690
+ if (Object.values(patch).every((value) => value === undefined)) {
691
+ return Promise.resolve(fail(apiError('invalid_record_metadata_patch', 'At least one metadata field is required.', 400)));
692
+ }
693
+ return run(() => client.updateRecordMetadata(recordId, patch));
694
+ });
695
+ server.registerTool('set_record_archive', {
696
+ title: 'Archive or restore record',
697
+ description: 'Set a record archived state. Use false to restore it.',
698
+ inputSchema: { recordId: z.string().uuid(), archived: z.boolean() },
699
+ }, ({ recordId, archived }) => run(() => client.setRecordArchiveState(recordId, archived)));
700
+ server.registerTool('transfer_record_ownership', {
701
+ title: 'Transfer record ownership',
702
+ description: 'Transfer a record to another eligible user.',
703
+ inputSchema: { recordId: z.string().uuid(), newOwnerUserId: z.string().uuid() },
704
+ }, ({ recordId, newOwnerUserId }) => run(() => client.transferRecordOwnership(recordId, newOwnerUserId)));
705
+ server.registerTool('rollback_record', {
706
+ title: 'Rollback record',
707
+ description: 'Create a new record version from a prior immutable version.',
708
+ inputSchema: { recordId: z.string().uuid(), targetVersionId: z.string().uuid() },
709
+ }, ({ recordId, targetVersionId }) => run(() => client.rollbackRecordToVersion(recordId, targetVersionId)));
710
+ server.registerTool('get_secret', {
711
+ title: 'Get a secret (decrypted)',
712
+ description: 'Fetch and decrypt a record locally. Humans use AIRCTRL_MCP_VAULT_PASSWORD; Service Accounts use their ' +
713
+ 'configured credential bundle. Never pass either through the prompt. This puts the secret into the agent ' +
714
+ "context — use only when the agent needs the value; for zero model-exposure, route the model call through the gateway instead.",
715
+ inputSchema: { recordId: z.string().uuid() },
716
+ }, ({ recordId }) => run(() => client.getSecret({ recordId, vaultPassword: recordUnlockPassword(config), audit: true })));
717
+ // G5·L4 — thin adapter over the SDK's scoped read (`AirctrlClient.readRecord`). No logic of its own:
718
+ // the tool params pass straight through to L2.
719
+ server.registerTool('read_record', {
720
+ title: 'Read a secret (scoped, decrypted)',
721
+ description: 'Scoped read of a record: pick which sections to return via `scope` (fields/meta/owner/access/full; ' +
722
+ 'default ["fields"]). `fields` is DECRYPTED client-side; `meta`/`owner`/`access` are metadata. The vault ' +
723
+ 'unlock material comes from the configured human password or Service Account credential (NEVER the prompt). Same ' +
724
+ 'model-exposure caveat as get_secret when requesting `fields`.',
725
+ inputSchema: {
726
+ recordId: z.string().uuid(),
727
+ scope: z.array(z.enum(['fields', 'meta', 'owner', 'access', 'full'])).optional(),
728
+ environment: z.string().optional(),
729
+ },
730
+ }, ({ recordId, scope, environment }) => run(() => client.readRecord({
731
+ recordId,
732
+ vaultPassword: recordUnlockPassword(config),
733
+ scope,
734
+ environment,
735
+ audit: true,
736
+ })));
737
+ server.registerTool('list_secret_types', {
738
+ title: 'List secret types + their fields',
739
+ description: 'List every secret type and, per type, its fields (name, primitive, required, masked) plus whether it is generatable. Use this to map arbitrary input (e.g. env vars, a pasted blob) to the right record type + field names before calling create_record.',
740
+ inputSchema: {},
741
+ }, () => run(async () => SECRET_FORMATS.map((f) => ({
742
+ format: f,
743
+ generatable: canGenerate(f),
744
+ fields: TEMPLATES[f].map((fld) => ({
745
+ name: fld.name,
746
+ primitive: fld.primitive,
747
+ required: !!fld.required,
748
+ masked: !!fld.masked,
749
+ })),
750
+ }))));
751
+ server.registerTool('create_record', {
752
+ title: 'Create a record',
753
+ description: 'Create a new secret record in a project. Either pass `fields` (the plaintext values for the type — see list_secret_types) or set `generate: true` for a generatable type to mint the material. Encrypted client-side with the vault password from this server config (AIRCTRL_MCP_VAULT_PASSWORD); the server never sees plaintext. accountId is resolved from the project. Returns the new recordId.',
754
+ inputSchema: {
755
+ projectId: z.string().uuid(),
756
+ name: z.string().min(1).max(200),
757
+ secretFormat: z.string(),
758
+ fields: z.record(z.string(), z.unknown()).optional(),
759
+ generate: z.boolean().optional(),
760
+ options: z.record(z.string(), z.unknown()).optional(),
761
+ tags: z.array(z.string()).optional(),
762
+ secretDueAt: z.string().nullable().optional(),
763
+ rotationIntervalDays: z.number().int().min(1).nullable().optional(),
764
+ idempotencyKey: z.string().min(1).optional(),
765
+ },
766
+ }, ({ projectId, name, secretFormat, fields, generate: gen, options, tags, secretDueAt, rotationIntervalDays, idempotencyKey, }) => run(async () => {
767
+ if (!isSecretFormat(secretFormat)) {
768
+ throw apiError('bad_format', `Unknown secret format '${secretFormat}'.`, 400);
769
+ }
770
+ const vaultPassword = recordUnlockPassword(config);
771
+ if (gen) {
772
+ if (!canGenerate(secretFormat)) {
773
+ throw apiError('not_generatable', `'${secretFormat}' can't be generated — pass explicit fields instead.`, 400);
774
+ }
775
+ return client.createGeneratedRecord({
776
+ projectId,
777
+ name,
778
+ secretFormat: secretFormat,
779
+ options: options ?? {},
780
+ extraFields: fields ?? {},
781
+ tags,
782
+ secretDueAt,
783
+ rotationIntervalDays,
784
+ idempotencyKey,
785
+ vaultPassword,
786
+ });
787
+ }
788
+ return client.createSecret({
789
+ projectId,
790
+ name,
791
+ secretFormat,
792
+ fieldValues: fields ?? {},
793
+ tags,
794
+ secretDueAt,
795
+ rotationIntervalDays,
796
+ idempotencyKey,
797
+ vaultPassword,
798
+ });
799
+ }));
800
+ server.registerTool('list_record_anomalies', {
801
+ title: 'List record anomalies',
802
+ description: 'Read recent security-relevant record events for the current user or one project.',
803
+ inputSchema: {
804
+ accountId: z.string().uuid().optional(),
805
+ scopeType: z.enum(['user', 'project']).optional(),
806
+ scopeId: z.string().uuid().optional(),
807
+ },
808
+ }, (input) => run(() => client.listRecordAnomalies(input)));
809
+ server.registerTool('list_record_activity', {
810
+ title: 'List record activity',
811
+ description: 'Read record activity buckets for one UTC day.',
812
+ inputSchema: {
813
+ day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
814
+ accountId: z.string().uuid().optional(),
815
+ scopeType: z.enum(['user', 'project']).optional(),
816
+ scopeId: z.string().uuid().optional(),
817
+ },
818
+ }, ({ day, ...input }) => run(() => client.listRecordActivity(day, input)));
819
+ server.registerTool('list_record_alerts', {
820
+ title: 'List record alerts',
821
+ description: 'Read the paginated record alert feed.',
822
+ inputSchema: {
823
+ accountId: z.string().uuid().optional(),
824
+ scopeType: z.enum(['user', 'project']).optional(),
825
+ scopeId: z.string().uuid().optional(),
826
+ limit: z.number().int().min(1).max(200).optional(),
827
+ offset: z.number().int().min(0).optional(),
828
+ },
829
+ }, (input) => run(() => client.listRecordAlerts(input)));
830
+ server.registerTool('list_record_access', {
831
+ title: 'List record access',
832
+ description: 'Read the paginated record access feed.',
833
+ inputSchema: {
834
+ accountId: z.string().uuid().optional(),
835
+ scopeType: z.enum(['user', 'project']).optional(),
836
+ scopeId: z.string().uuid().optional(),
837
+ limit: z.number().int().min(1).max(200).optional(),
838
+ offset: z.number().int().min(0).optional(),
839
+ actions: z.array(z.string().min(1)).optional(),
840
+ },
841
+ }, (input) => run(() => client.listRecordAccess(input)));
842
+ server.registerTool('set_secret', {
843
+ title: 'Set secret value',
844
+ description: 'Update a record by id, or upsert it by project/name/type. Plaintext is encrypted client-side; the API never sees it.',
845
+ inputSchema: {
846
+ recordId: z.string().uuid().optional(),
847
+ projectId: z.string().uuid().optional(),
848
+ name: z.string().min(1).max(200).optional(),
849
+ secretFormat: z.string().optional(),
850
+ fields: z.record(z.string(), z.unknown()),
851
+ changedFields: z.array(z.string()).optional(),
852
+ tags: z.array(z.string()).optional(),
853
+ secretDueAt: z.string().nullable().optional(),
854
+ rotationIntervalDays: z.number().int().min(1).nullable().optional(),
855
+ idempotencyKey: z.string().min(1).optional(),
856
+ },
857
+ }, ({ recordId, projectId, name, secretFormat, fields, changedFields, tags, secretDueAt, rotationIntervalDays, idempotencyKey, }) => run(async () => {
858
+ if (secretFormat !== undefined && !isSecretFormat(secretFormat)) {
859
+ throw apiError('bad_format', `Unknown secret format '${secretFormat}'.`, 400);
860
+ }
861
+ return client.setSecret({
862
+ recordId,
863
+ projectId,
864
+ name,
865
+ secretFormat,
866
+ fieldValues: fields,
867
+ changedFields,
868
+ tags,
869
+ secretDueAt,
870
+ rotationIntervalDays,
871
+ idempotencyKey,
872
+ vaultPassword: recordUnlockPassword(config),
873
+ });
874
+ }));
875
+ server.registerTool('rotate_record', {
876
+ title: 'Rotate record encryption key',
877
+ description: 'Rotate a record DEK and re-encrypt/re-seal it client-side. The API never sees plaintext.',
878
+ inputSchema: { recordId: z.string().uuid() },
879
+ }, ({ recordId }) => run(() => client.rotateRecord({ recordId, vaultPassword: recordUnlockPassword(config) })));
880
+ server.registerTool('share_record_user', {
881
+ title: 'Share record with user',
882
+ description: 'Seal a record DEK client-side to one user and create the grant.',
883
+ inputSchema: {
884
+ recordId: z.string().uuid(),
885
+ userId: z.string().uuid(),
886
+ permission: z.enum(['view', 'read']).optional(),
887
+ },
888
+ }, ({ recordId, userId, permission }) => run(() => client.shareRecordWithUser({
889
+ recordId,
890
+ granteeUserId: userId,
891
+ permission,
892
+ vaultPassword: recordUnlockPassword(config),
893
+ })));
894
+ server.registerTool('share_record_service_account', {
895
+ title: 'Share record with service account',
896
+ description: 'Seal a record DEK client-side to the current service-account identity and create the grant.',
897
+ inputSchema: {
898
+ accountId: z.string().uuid(),
899
+ recordId: z.string().uuid(),
900
+ serviceAccountId: z.string().uuid(),
901
+ },
902
+ }, ({ accountId, recordId, serviceAccountId }) => run(() => client.shareRecordWithServiceAccount({
903
+ accountId,
904
+ recordId,
905
+ serviceAccountId,
906
+ vaultPassword: recordUnlockPassword(config),
907
+ })));
908
+ server.registerTool('share_record_group', {
909
+ title: 'Share record with group',
910
+ description: 'Seal a record DEK client-side to every current group member and create the group grant.',
911
+ inputSchema: { recordId: z.string().uuid(), groupId: z.string().uuid() },
912
+ }, ({ recordId, groupId }) => run(() => client.shareRecordWithGroup({
913
+ recordId,
914
+ groupId,
915
+ vaultPassword: recordUnlockPassword(config),
916
+ })));
917
+ server.registerTool('revoke_record_user', {
918
+ title: 'Revoke record from user',
919
+ description: 'Revoke one user grant and remove its record wrapper.',
920
+ inputSchema: { recordId: z.string().uuid(), userId: z.string().uuid() },
921
+ }, ({ recordId, userId }) => run(() => client.revokeRecordFromUser(recordId, userId)));
922
+ server.registerTool('revoke_record_service_account', {
923
+ title: 'Revoke record from service account',
924
+ description: 'Revoke one service-account grant and remove its record wrapper.',
925
+ inputSchema: { recordId: z.string().uuid(), serviceAccountId: z.string().uuid() },
926
+ }, ({ recordId, serviceAccountId }) => run(() => client.revokeRecordFromServiceAccount(recordId, serviceAccountId)));
927
+ server.registerTool('revoke_record_group', {
928
+ title: 'Revoke record from group',
929
+ description: 'Revoke a group grant and remove its member record wrappers.',
930
+ inputSchema: { recordId: z.string().uuid(), groupId: z.string().uuid() },
931
+ }, ({ recordId, groupId }) => run(() => client.revokeRecordFromGroup(recordId, groupId)));
932
+ server.registerTool('generate_secret', {
933
+ title: 'Generate a secret',
934
+ description: 'Mint spec-correct secret material client-side and return the record fields to store — nothing is sent to a server (zero-knowledge). Generatable types: totp (Base32 seed), ssh (Ed25519 keypair, OpenSSH format), certificate (self-signed X.509), password, webhook (whsec_ signing secret), api_key (random token), oauth_client (client_secret + PKCE). Provider-issued/freeform types (database, cloud_iam, service_account, license, env, json, plain) are NOT generatable.',
935
+ inputSchema: {
936
+ format: z.string(),
937
+ options: z.record(z.string(), z.unknown()).optional(),
938
+ },
939
+ }, ({ format, options }) => run(async () => {
940
+ if (!isSecretFormat(format)) {
941
+ throw apiError('bad_format', `Unknown secret format '${format}'. One of: ${SECRET_FORMATS.join(', ')}.`, 400);
942
+ }
943
+ if (!canGenerate(format)) {
944
+ throw apiError('not_generatable', `'${format}' can't be generated — it's a provider-issued or freeform secret.`, 400);
945
+ }
946
+ const { fields } = await generateSecret(format, options ?? {});
947
+ return { format, fields };
948
+ }));
949
+ server.registerTool('get_all', {
950
+ title: 'Get all project secrets (decrypted)',
951
+ description: 'Decrypt every record in a project that the caller can access, returning name+value pairs (e.g. to inject as env ' +
952
+ 'vars). Unlock material comes from the configured human password or Service Account credential, never the prompt. Same model-exposure caveat as get_secret.',
953
+ inputSchema: { projectId: z.string().uuid() },
954
+ }, ({ projectId }) => run(() => client.getAll({ projectId, vaultPassword: recordUnlockPassword(config), audit: false })));
955
+ }