-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathGatewayPrimitive.ts
More file actions
431 lines (387 loc) · 15.1 KB
/
Copy pathGatewayPrimitive.ts
File metadata and controls
431 lines (387 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
import { findConfigRoot, setEnvVar } from '../../lib';
import type { AgentCoreGateway, AgentCoreGatewayTarget, AgentCoreMcpSpec, GatewayAuthorizerType } from '../../schema';
import { AgentCoreGatewaySchema } from '../../schema';
import type { AddGatewayOptions as CLIAddGatewayOptions } from '../commands/add/types';
import { validateAddGatewayOptions } from '../commands/add/validate';
import { getErrorMessage } from '../errors';
import type { RemovalPreview, RemovalResult, SchemaChange } from '../operations/remove/types';
import type { AddGatewayConfig } from '../tui/screens/mcp/types';
import { BasePrimitive } from './BasePrimitive';
import { SOURCE_CODE_NOTE } from './constants';
import { computeDefaultCredentialEnvVarName } from './credential-utils';
import type { AddResult, AddScreenComponent, RemovableResource } from './types';
import type { Command } from '@commander-js/extra-typings';
/**
* Options for adding a gateway resource (CLI-level).
*/
export interface AddGatewayOptions {
name: string;
description?: string;
authorizerType: GatewayAuthorizerType;
discoveryUrl?: string;
allowedAudience?: string;
allowedClients?: string;
allowedScopes?: string;
agentClientId?: string;
agentClientSecret?: string;
agents?: string;
}
/**
* GatewayPrimitive handles all gateway add/remove operations.
* Absorbs logic from create-mcp.ts (gateway) and remove-gateway.ts.
* Uses mcp.json instead of agentcore.json.
*/
export class GatewayPrimitive extends BasePrimitive<AddGatewayOptions, RemovableResource> {
readonly kind = 'gateway';
readonly label = 'Gateway';
readonly primitiveSchema = AgentCoreGatewaySchema;
async add(options: AddGatewayOptions): Promise<AddResult<{ gatewayName: string }>> {
try {
const config = this.buildGatewayConfig(options);
const result = await this.createGatewayFromWizard(config);
return { success: true, gatewayName: result.name };
} catch (err) {
return { success: false, error: getErrorMessage(err) };
}
}
async remove(gatewayName: string): Promise<RemovalResult> {
try {
const mcpSpec = await this.configIO.readMcpSpec();
const gateway = mcpSpec.agentCoreGateways.find(g => g.name === gatewayName);
if (!gateway) {
return { success: false, error: `Gateway "${gatewayName}" not found.` };
}
const newMcpSpec = this.computeRemovedGatewayMcpSpec(mcpSpec, gatewayName);
await this.configIO.writeMcpSpec(newMcpSpec);
return { success: true };
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error';
return { success: false, error: message };
}
}
async previewRemove(gatewayName: string): Promise<RemovalPreview> {
const mcpSpec = await this.configIO.readMcpSpec();
const gateway = mcpSpec.agentCoreGateways.find(g => g.name === gatewayName);
if (!gateway) {
throw new Error(`Gateway "${gatewayName}" not found.`);
}
const summary: string[] = [`Removing gateway: ${gatewayName}`];
const schemaChanges: SchemaChange[] = [];
if (gateway.targets.length > 0) {
summary.push(`Note: ${gateway.targets.length} target(s) behind this gateway will become unassigned`);
}
const afterMcpSpec = this.computeRemovedGatewayMcpSpec(mcpSpec, gatewayName);
schemaChanges.push({
file: 'agentcore/mcp.json',
before: mcpSpec,
after: afterMcpSpec,
});
return { summary, directoriesToDelete: [], schemaChanges };
}
async getRemovable(): Promise<RemovableResource[]> {
try {
if (!this.configIO.configExists('mcp')) {
return [];
}
const mcpSpec = await this.configIO.readMcpSpec();
return mcpSpec.agentCoreGateways.map(g => ({ name: g.name }));
} catch {
return [];
}
}
/**
* Get list of existing gateway names.
*/
async getExistingGateways(): Promise<string[]> {
try {
if (!this.configIO.configExists('mcp')) {
return [];
}
const mcpSpec = await this.configIO.readMcpSpec();
return mcpSpec.agentCoreGateways.map(g => g.name);
} catch {
return [];
}
}
/**
* Get list of unassigned targets from mcp.json.
*/
async getUnassignedTargets(): Promise<AgentCoreGatewayTarget[]> {
try {
if (!this.configIO.configExists('mcp')) {
return [];
}
const mcpSpec = await this.configIO.readMcpSpec();
return mcpSpec.unassignedTargets ?? [];
} catch {
return [];
}
}
/**
* Compute the default env var name for a gateway.
*/
static computeDefaultGatewayEnvVarName(gatewayName: string): string {
const sanitized = gatewayName.toUpperCase().replace(/-/g, '_');
return `AGENTCORE_GATEWAY_${sanitized}_URL`;
}
registerCommands(addCmd: Command, removeCmd: Command): void {
addCmd
.command('gateway', { hidden: true })
.description('Add a gateway to the project')
.option('--name <name>', 'Gateway name')
.option('--description <desc>', 'Gateway description')
.option('--authorizer-type <type>', 'Authorizer type: NONE or CUSTOM_JWT')
.option('--discovery-url <url>', 'OIDC discovery URL (for CUSTOM_JWT)')
.option('--allowed-audience <audience>', 'Comma-separated allowed audiences (for CUSTOM_JWT)')
.option('--allowed-clients <clients>', 'Comma-separated allowed client IDs (for CUSTOM_JWT)')
.option('--allowed-scopes <scopes>', 'Comma-separated allowed scopes (for CUSTOM_JWT)')
.option('--agent-client-id <id>', 'Agent OAuth client ID')
.option('--agent-client-secret <secret>', 'Agent OAuth client secret')
.option('--agents <agents>', 'Comma-separated agent names')
.option('--json', 'Output as JSON')
.action(async (rawOptions: Record<string, string | boolean | undefined>) => {
const cliOptions = rawOptions as unknown as CLIAddGatewayOptions;
try {
if (!findConfigRoot()) {
console.error('No agentcore project found. Run `agentcore create` first.');
process.exit(1);
}
const validation = validateAddGatewayOptions(cliOptions);
if (!validation.valid) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: validation.error }));
} else {
console.error(validation.error);
}
process.exit(1);
}
const result = await this.add({
name: cliOptions.name!,
description: cliOptions.description,
authorizerType: cliOptions.authorizerType ?? 'NONE',
discoveryUrl: cliOptions.discoveryUrl,
allowedAudience: cliOptions.allowedAudience,
allowedClients: cliOptions.allowedClients,
allowedScopes: cliOptions.allowedScopes,
agentClientId: cliOptions.agentClientId,
agentClientSecret: cliOptions.agentClientSecret,
agents: cliOptions.agents,
});
if (cliOptions.json) {
console.log(JSON.stringify(result));
} else if (result.success) {
console.log(`Added gateway '${result.gatewayName}'`);
} else {
console.error(result.error);
}
process.exit(result.success ? 0 : 1);
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
});
removeCmd
.command('gateway', { hidden: true })
.description('Remove a gateway from the project')
.option('--name <name>', 'Name of resource to remove')
.option('--force', 'Skip confirmation prompt')
.option('--json', 'Output as JSON')
.action(async (cliOptions: { name?: string; force?: boolean; json?: boolean }) => {
try {
if (!findConfigRoot()) {
console.error('No agentcore project found. Run `agentcore create` first.');
process.exit(1);
}
if (cliOptions.name || cliOptions.force || cliOptions.json) {
if (!cliOptions.name) {
console.log(JSON.stringify({ success: false, error: '--name is required' }));
process.exit(1);
}
const result = await this.remove(cliOptions.name);
console.log(
JSON.stringify({
success: result.success,
resourceType: this.kind,
resourceName: cliOptions.name,
message: result.success ? `Removed gateway '${cliOptions.name}'` : undefined,
note: result.success ? SOURCE_CODE_NOTE : undefined,
error: !result.success ? result.error : undefined,
})
);
process.exit(result.success ? 0 : 1);
} else {
const [{ render }, { default: React }, { RemoveFlow }] = await Promise.all([
import('ink'),
import('react'),
import('../tui/screens/remove'),
]);
const { clear, unmount } = render(
React.createElement(RemoveFlow, {
isInteractive: false,
force: cliOptions.force,
initialResourceType: this.kind,
initialResourceName: cliOptions.name,
onExit: () => {
clear();
unmount();
process.exit(0);
},
})
);
}
} catch (error) {
if (cliOptions.json) {
console.log(JSON.stringify({ success: false, error: getErrorMessage(error) }));
} else {
console.error(`Error: ${getErrorMessage(error)}`);
}
process.exit(1);
}
});
}
addScreen(): AddScreenComponent {
return null;
}
/**
* Build gateway config from CLI options.
*/
private buildGatewayConfig(options: AddGatewayOptions): AddGatewayConfig {
const config: AddGatewayConfig = {
name: options.name,
description: options.description ?? `Gateway for ${options.name}`,
authorizerType: options.authorizerType,
jwtConfig: undefined,
};
if (options.authorizerType === 'CUSTOM_JWT' && options.discoveryUrl) {
config.jwtConfig = {
discoveryUrl: options.discoveryUrl,
allowedAudience: options.allowedAudience
? options.allowedAudience
.split(',')
.map(s => s.trim())
.filter(Boolean)
: [],
allowedClients: options.allowedClients
? options.allowedClients
.split(',')
.map(s => s.trim())
.filter(Boolean)
: [],
...(options.allowedScopes
? {
allowedScopes: options.allowedScopes
.split(',')
.map(s => s.trim())
.filter(Boolean),
}
: {}),
...(options.agentClientId ? { agentClientId: options.agentClientId } : {}),
...(options.agentClientSecret ? { agentClientSecret: options.agentClientSecret } : {}),
};
}
return config;
}
/**
* Create a gateway (absorbed from create-mcp.ts createGatewayFromWizard).
*/
private async createGatewayFromWizard(config: AddGatewayConfig): Promise<{ name: string }> {
const mcpSpec: AgentCoreMcpSpec = this.configIO.configExists('mcp')
? await this.configIO.readMcpSpec()
: { agentCoreGateways: [] };
if (mcpSpec.agentCoreGateways.some(g => g.name === config.name)) {
throw new Error(`Gateway "${config.name}" already exists.`);
}
// Move selected unassigned targets to the new gateway
const selectedNames = new Set(config.selectedTargets ?? []);
const movedTargets: AgentCoreGatewayTarget[] = [];
if (selectedNames.size > 0 && mcpSpec.unassignedTargets) {
const remaining: AgentCoreGatewayTarget[] = [];
for (const target of mcpSpec.unassignedTargets) {
if (selectedNames.has(target.name)) {
movedTargets.push(target);
} else {
remaining.push(target);
}
}
mcpSpec.unassignedTargets = remaining.length > 0 ? remaining : undefined;
}
const gateway: AgentCoreGateway = {
name: config.name,
description: config.description,
targets: movedTargets,
authorizerType: config.authorizerType,
authorizerConfiguration: this.buildAuthorizerConfiguration(config),
};
mcpSpec.agentCoreGateways.push(gateway);
await this.configIO.writeMcpSpec(mcpSpec);
// Auto-create OAuth credential if agent client credentials are provided
if (config.jwtConfig?.agentClientId && config.jwtConfig?.agentClientSecret) {
await this.createManagedOAuthCredential(config.name, config.jwtConfig);
}
return { name: config.name };
}
/**
* Auto-create a managed OAuth credential for gateway inbound auth.
* Stores the credential in agentcore.json and writes the client secret to .env.
*/
private async createManagedOAuthCredential(
gatewayName: string,
jwtConfig: NonNullable<AddGatewayConfig['jwtConfig']>
): Promise<void> {
const credentialName = `${gatewayName}-oauth`;
const project = await this.readProjectSpec();
// Skip if credential already exists
if (project.credentials.some(c => c.name === credentialName)) {
return;
}
project.credentials.push({
type: 'OAuthCredentialProvider',
name: credentialName,
discoveryUrl: jwtConfig.discoveryUrl,
vendor: 'CustomOauth2',
managed: true,
usage: 'inbound',
});
await this.writeProjectSpec(project);
// Write client secret to .env
const envVarName = computeDefaultCredentialEnvVarName(credentialName);
await setEnvVar(envVarName, jwtConfig.agentClientSecret!);
}
/**
* Build authorizer configuration from wizard config.
*/
private buildAuthorizerConfiguration(config: AddGatewayConfig): AgentCoreGateway['authorizerConfiguration'] {
if (config.authorizerType !== 'CUSTOM_JWT' || !config.jwtConfig) {
return undefined;
}
return {
customJwtAuthorizer: {
discoveryUrl: config.jwtConfig.discoveryUrl,
allowedAudience: config.jwtConfig.allowedAudience,
allowedClients: config.jwtConfig.allowedClients,
...(config.jwtConfig.allowedScopes && config.jwtConfig.allowedScopes.length > 0
? { allowedScopes: config.jwtConfig.allowedScopes }
: {}),
},
};
}
/**
* Compute MCP spec after removing a gateway.
* Moves the gateway's targets to unassignedTargets so they are preserved.
*/
private computeRemovedGatewayMcpSpec(mcpSpec: AgentCoreMcpSpec, gatewayName: string): AgentCoreMcpSpec {
const gateway = mcpSpec.agentCoreGateways.find(g => g.name === gatewayName);
const orphanedTargets = gateway?.targets ?? [];
const existingUnassigned = mcpSpec.unassignedTargets ?? [];
const mergedUnassigned = [...existingUnassigned, ...orphanedTargets];
return {
...mcpSpec,
agentCoreGateways: mcpSpec.agentCoreGateways.filter(g => g.name !== gatewayName),
...(mergedUnassigned.length > 0 ? { unassignedTargets: mergedUnassigned } : {}),
};
}
}