-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathvalidate.ts
More file actions
714 lines (631 loc) · 26.6 KB
/
validate.ts
File metadata and controls
714 lines (631 loc) · 26.6 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
import { ConfigIO, findConfigRoot } from '../../../lib';
import {
AgentNameSchema,
BuildTypeSchema,
GatewayExceptionLevelSchema,
GatewayNameSchema,
ModelProviderSchema,
ProtocolModeSchema,
RuntimeAuthorizerTypeSchema,
SDKFrameworkSchema,
TARGET_TYPE_AUTH_CONFIG,
TargetLanguageSchema,
getSupportedFrameworksForProtocol,
getSupportedModelProviders,
matchEnumValue,
} from '../../../schema';
import { parseAndValidateLifecycleOptions } from '../shared/lifecycle-utils';
import { validateVpcOptions } from '../shared/vpc-utils';
import { validateJwtAuthorizerOptions } from './auth-options';
import type {
AddAgentOptions,
AddCredentialOptions,
AddGatewayOptions,
AddGatewayTargetOptions,
AddMemoryOptions,
} from './types';
import { existsSync, readFileSync } from 'fs';
import { dirname, extname, isAbsolute, join, resolve } from 'path';
export interface ValidationResult {
valid: boolean;
error?: string;
}
// Constants
const MEMORY_OPTIONS = ['none', 'shortTerm', 'longAndShortTerm'] as const;
const VALID_STRATEGIES = ['SEMANTIC', 'SUMMARIZATION', 'USER_PREFERENCE', 'EPISODIC'];
/**
* Validate that a credential name exists in the project spec.
*/
async function validateCredentialExists(credentialName: string): Promise<ValidationResult> {
try {
const configIO = new ConfigIO();
const project = await configIO.readProjectSpec();
const credentialExists = project.credentials.some(c => c.name === credentialName);
if (!credentialExists) {
const availableCredentials = project.credentials.map(c => c.name);
if (availableCredentials.length === 0) {
return {
valid: false,
error: `Credential "${credentialName}" not found. No credentials are configured. Add credentials using 'agentcore add credential'.`,
};
}
return {
valid: false,
error: `Credential "${credentialName}" not found. Available credentials: ${availableCredentials.join(', ')}`,
};
}
return { valid: true };
} catch {
return { valid: false, error: 'Failed to read project configuration' };
}
}
// Agent validation
export function validateAddAgentOptions(options: AddAgentOptions): ValidationResult {
// Normalize enum flag values (case-insensitive matching)
if (options.protocol)
options.protocol =
(matchEnumValue(ProtocolModeSchema, options.protocol) as typeof options.protocol) ?? options.protocol;
if (options.framework)
options.framework =
(matchEnumValue(SDKFrameworkSchema, options.framework) as typeof options.framework) ?? options.framework;
if (options.modelProvider)
options.modelProvider =
(matchEnumValue(ModelProviderSchema, options.modelProvider) as typeof options.modelProvider) ??
options.modelProvider;
if (options.language)
options.language =
(matchEnumValue(TargetLanguageSchema, options.language) as typeof options.language) ?? options.language;
if (options.build) options.build = matchEnumValue(BuildTypeSchema, options.build) ?? options.build;
if (!options.name) {
return { valid: false, error: '--name is required' };
}
const nameResult = AgentNameSchema.safeParse(options.name);
if (!nameResult.success) {
return { valid: false, error: nameResult.error.issues[0]?.message ?? 'Invalid agent name' };
}
// Validate build type if provided
if (options.build) {
const buildResult = BuildTypeSchema.safeParse(options.build);
if (!buildResult.success) {
return { valid: false, error: `Invalid build type: ${options.build}. Use CodeZip or Container` };
}
}
// Validate and normalize protocol
const protocol = options.protocol ?? 'HTTP';
const protocolResult = ProtocolModeSchema.safeParse(protocol);
if (!protocolResult.success) {
return { valid: false, error: `Invalid protocol: ${protocol}. Use HTTP, MCP, or A2A` };
}
options.protocol = protocolResult.data;
const isByoPath = options.type === 'byo';
const isImportPath = options.type === 'import';
// Import path: validate import-specific options and return early
if (isImportPath) {
if (!options.agentId) {
return { valid: false, error: '--agent-id is required for import path' };
}
if (!options.agentAliasId) {
return { valid: false, error: '--agent-alias-id is required for import path' };
}
if (!options.region) {
return { valid: false, error: '--region is required for import path' };
}
if (!options.framework) {
return { valid: false, error: '--framework is required for import path' };
}
if (options.framework !== 'Strands' && options.framework !== 'LangChain_LangGraph') {
return { valid: false, error: 'Import path only supports Strands or LangChain_LangGraph frameworks' };
}
if (!options.memory) {
return { valid: false, error: '--memory is required for import path' };
}
if (!MEMORY_OPTIONS.includes(options.memory as (typeof MEMORY_OPTIONS)[number])) {
return {
valid: false,
error: `Invalid memory option: ${options.memory}. Use none, shortTerm, or longAndShortTerm`,
};
}
// Parse and validate lifecycle configuration for import path
const lcResult = parseAndValidateLifecycleOptions(options);
if (!lcResult.valid) return lcResult;
if (lcResult.idleTimeout !== undefined) options.idleTimeout = lcResult.idleTimeout;
if (lcResult.maxLifetime !== undefined) options.maxLifetime = lcResult.maxLifetime;
// Force import defaults
options.modelProvider = 'Bedrock' as typeof options.modelProvider;
options.language = 'Python' as typeof options.language;
return { valid: true };
}
// MCP protocol: no framework, model provider, or memory
if (protocol === 'MCP') {
if (options.framework) {
return { valid: false, error: '--framework is not applicable for MCP protocol' };
}
if (options.modelProvider) {
return { valid: false, error: '--model-provider is not applicable for MCP protocol' };
}
if (options.memory && options.memory !== 'none') {
return { valid: false, error: '--memory is not applicable for MCP protocol' };
}
if (!options.language) {
return { valid: false, error: '--language is required' };
}
const langResult = TargetLanguageSchema.safeParse(options.language);
if (!langResult.success) {
return { valid: false, error: `Invalid language: ${options.language}` };
}
if (isByoPath && !options.codeLocation) {
return { valid: false, error: '--code-location is required for BYO path' };
}
// Parse and validate lifecycle configuration for MCP path
const mcpLcResult = parseAndValidateLifecycleOptions(options);
if (!mcpLcResult.valid) return mcpLcResult;
if (mcpLcResult.idleTimeout !== undefined) options.idleTimeout = mcpLcResult.idleTimeout;
if (mcpLcResult.maxLifetime !== undefined) options.maxLifetime = mcpLcResult.maxLifetime;
return { valid: true };
}
// Non-MCP protocols: validate framework
if (!options.framework) {
return { valid: false, error: '--framework is required' };
}
const fwResult = SDKFrameworkSchema.safeParse(options.framework);
if (!fwResult.success) {
return { valid: false, error: `Invalid framework: ${options.framework}` };
}
// Validate framework is supported for the protocol
if (protocol !== 'HTTP') {
const supportedFrameworks = getSupportedFrameworksForProtocol(protocol);
if (!supportedFrameworks.includes(options.framework)) {
return { valid: false, error: `${options.framework} does not support ${protocol} protocol` };
}
}
if (!options.modelProvider) {
return { valid: false, error: '--model-provider is required' };
}
const mpResult = ModelProviderSchema.safeParse(options.modelProvider);
if (!mpResult.success) {
return { valid: false, error: `Invalid model provider: ${options.modelProvider}` };
}
const supportedProviders = getSupportedModelProviders(options.framework);
if (!supportedProviders.includes(options.modelProvider)) {
return { valid: false, error: `${options.framework} does not support ${options.modelProvider}` };
}
if (!options.language) {
return { valid: false, error: '--language is required' };
}
const langResult = TargetLanguageSchema.safeParse(options.language);
if (!langResult.success) {
return { valid: false, error: `Invalid language: ${options.language}` };
}
if (isByoPath) {
if (!options.codeLocation) {
return { valid: false, error: '--code-location is required for BYO path' };
}
} else {
if (options.language === 'TypeScript') {
return { valid: false, error: 'Create path only supports Python (TypeScript templates not yet available)' };
}
if (options.language === 'Other') {
return { valid: false, error: 'Create path only supports Python' };
}
if (!options.memory) {
return { valid: false, error: '--memory is required for create path' };
}
if (!MEMORY_OPTIONS.includes(options.memory as (typeof MEMORY_OPTIONS)[number])) {
return {
valid: false,
error: `Invalid memory option: ${options.memory}. Use none, shortTerm, or longAndShortTerm`,
};
}
}
// Parse and validate lifecycle configuration
const lifecycleResult = parseAndValidateLifecycleOptions(options);
if (!lifecycleResult.valid) return lifecycleResult;
if (lifecycleResult.idleTimeout !== undefined) options.idleTimeout = lifecycleResult.idleTimeout;
if (lifecycleResult.maxLifetime !== undefined) options.maxLifetime = lifecycleResult.maxLifetime;
// Validate VPC options
const vpcResult = validateVpcOptions(options);
if (!vpcResult.valid) {
return { valid: false, error: vpcResult.error };
}
// Validate authorizer options (applies to both create and BYO paths)
if (options.authorizerType) {
const authResult = RuntimeAuthorizerTypeSchema.safeParse(options.authorizerType);
if (!authResult.success) {
return { valid: false, error: 'Invalid authorizer type. Use AWS_IAM or CUSTOM_JWT' };
}
if (options.authorizerType === 'CUSTOM_JWT') {
const jwtResult = validateJwtAuthorizerOptions(options);
if (!jwtResult.valid) return jwtResult;
}
}
// Validate OAuth client credentials require CUSTOM_JWT
if (options.clientId && options.authorizerType !== 'CUSTOM_JWT') {
return { valid: false, error: 'OAuth client credentials are only valid with CUSTOM_JWT authorizer' };
}
return { valid: true };
}
// Gateway validation
export function validateAddGatewayOptions(options: AddGatewayOptions): ValidationResult {
if (!options.name) {
return { valid: false, error: '--name is required' };
}
const nameResult = GatewayNameSchema.safeParse(options.name);
if (!nameResult.success) {
return { valid: false, error: nameResult.error.issues[0]?.message ?? 'Invalid gateway name' };
}
if (options.authorizerType && !['NONE', 'CUSTOM_JWT'].includes(options.authorizerType)) {
return { valid: false, error: 'Invalid authorizer type. Use NONE or CUSTOM_JWT' };
}
if (options.authorizerType === 'CUSTOM_JWT') {
const jwtResult = validateJwtAuthorizerOptions(options);
if (!jwtResult.valid) return jwtResult;
}
// Validate OAuth client credentials require CUSTOM_JWT
if (options.clientId && options.authorizerType !== 'CUSTOM_JWT') {
return { valid: false, error: 'OAuth client credentials are only valid with CUSTOM_JWT authorizer' };
}
// Validate exception level if provided
if (options.exceptionLevel) {
const levelResult = GatewayExceptionLevelSchema.safeParse(options.exceptionLevel);
if (!levelResult.success) {
return { valid: false, error: `Invalid exception level: ${options.exceptionLevel}. Use NONE or DEBUG` };
}
}
// Validate policy engine options
if (options.policyEngine && !options.policyEngineMode) {
return { valid: false, error: '--policy-engine-mode is required when --policy-engine is specified' };
}
if (options.policyEngineMode && !options.policyEngine) {
return { valid: false, error: '--policy-engine is required when --policy-engine-mode is specified' };
}
if (options.policyEngineMode && !['LOG_ONLY', 'ENFORCE'].includes(options.policyEngineMode)) {
return { valid: false, error: `Invalid policy engine mode: ${options.policyEngineMode}. Use LOG_ONLY or ENFORCE` };
}
return { valid: true };
}
// Gateway Target validation
export async function validateAddGatewayTargetOptions(options: AddGatewayTargetOptions): Promise<ValidationResult> {
// Normalize enum flag values (case-insensitive matching)
if (options.language)
options.language =
(matchEnumValue(TargetLanguageSchema, options.language) as typeof options.language) ?? options.language;
if (!options.name) {
return { valid: false, error: '--name is required' };
}
if (!options.type) {
return {
valid: false,
error:
'--type is required. Valid options: mcp-server, api-gateway, open-api-schema, smithy-model, lambda-function-arn',
};
}
const typeMap: Record<string, string> = {
'mcp-server': 'mcpServer',
'api-gateway': 'apiGateway',
'open-api-schema': 'openApiSchema',
'smithy-model': 'smithyModel',
'lambda-function-arn': 'lambdaFunctionArn',
};
const mappedType = typeMap[options.type];
if (!mappedType) {
return {
valid: false,
error: `Invalid type: ${options.type}. Valid options: mcp-server, api-gateway, open-api-schema, smithy-model, lambda-function-arn`,
};
}
options.type = mappedType;
// Gateway is required — a gateway target must be attached to a gateway
if (!options.gateway) {
return {
valid: false,
error:
"--gateway is required. A gateway target must be attached to a gateway. Create a gateway first with 'agentcore add gateway'.",
};
}
// Validate the specified gateway exists
const gatewayConfigIO = new ConfigIO();
let existingGateways: string[] = [];
try {
const project = await gatewayConfigIO.readProjectSpec();
existingGateways = project.agentCoreGateways.map(g => g.name);
} catch {
// If we can't read the config, treat as no gateways
}
if (existingGateways.length === 0) {
return {
valid: false,
error: "No gateways found. Create a gateway first with 'agentcore add gateway' before adding a gateway target.",
};
}
if (!existingGateways.includes(options.gateway)) {
return {
valid: false,
error: `Gateway "${options.gateway}" not found. Available gateways: ${existingGateways.join(', ')}`,
};
}
// API Gateway targets: validate early and return (skip outbound auth validation)
if (mappedType === 'apiGateway') {
if (!options.restApiId) {
return { valid: false, error: '--rest-api-id is required for api-gateway type' };
}
if (!options.stage) {
return { valid: false, error: '--stage is required for api-gateway type' };
}
if (options.endpoint) {
return { valid: false, error: '--endpoint is not applicable for api-gateway type' };
}
if (options.host) {
return { valid: false, error: '--host is not applicable for api-gateway type' };
}
if (options.language && options.language !== 'Other') {
return { valid: false, error: '--language is not applicable for api-gateway type' };
}
if (options.outboundAuthType) {
const apiGwAuth = TARGET_TYPE_AUTH_CONFIG.apiGateway;
const normalizedAuth = options.outboundAuthType.toUpperCase().replace('-', '_');
if (!apiGwAuth.validAuthTypes.includes(normalizedAuth as 'OAUTH' | 'API_KEY' | 'NONE')) {
return { valid: false, error: `${options.outboundAuthType} is not supported for api-gateway type` };
}
if (normalizedAuth === 'API_KEY' && !options.credentialName) {
return { valid: false, error: '--credential-name is required with --outbound-auth api-key' };
}
}
if (options.oauthClientId || options.oauthClientSecret || options.oauthDiscoveryUrl || options.oauthScopes) {
return { valid: false, error: 'OAuth options are not applicable for api-gateway type' };
}
if (options.lambdaArn) {
return { valid: false, error: '--lambda-arn is not applicable for api-gateway type' };
}
if (options.toolSchemaFile) {
return { valid: false, error: '--tool-schema-file is not applicable for api-gateway type' };
}
options.language = 'Other';
return { valid: true };
}
// Lambda Function ARN targets: validate early and return
if (mappedType === 'lambdaFunctionArn') {
if (!options.lambdaArn) {
return { valid: false, error: '--lambda-arn is required for lambda-function-arn type' };
}
if (!options.toolSchemaFile) {
return { valid: false, error: '--tool-schema-file is required for lambda-function-arn type' };
}
if (options.endpoint) {
return { valid: false, error: '--endpoint is not applicable for lambda-function-arn type' };
}
if (options.host) {
return { valid: false, error: '--host is not applicable for lambda-function-arn type' };
}
if (options.language && options.language !== 'Other') {
return { valid: false, error: '--language is not applicable for lambda-function-arn type' };
}
if (options.restApiId) {
return { valid: false, error: '--rest-api-id is not applicable for lambda-function-arn type' };
}
if (options.stage) {
return { valid: false, error: '--stage is not applicable for lambda-function-arn type' };
}
if (options.toolFilterPath) {
return { valid: false, error: '--tool-filter-path is not applicable for lambda-function-arn type' };
}
if (options.toolFilterMethods) {
return { valid: false, error: '--tool-filter-methods is not applicable for lambda-function-arn type' };
}
if (options.outboundAuthType) {
return { valid: false, error: '--outbound-auth is not applicable for lambda-function-arn type' };
}
if (options.credentialName) {
return { valid: false, error: '--credential-name is not applicable for lambda-function-arn type' };
}
if (options.oauthClientId || options.oauthClientSecret || options.oauthDiscoveryUrl || options.oauthScopes) {
return { valid: false, error: 'OAuth options are not applicable for lambda-function-arn type' };
}
const configRoot = findConfigRoot();
const projectRoot = configRoot ? dirname(configRoot) : process.cwd();
const resolvedPath = isAbsolute(options.toolSchemaFile)
? options.toolSchemaFile
: join(projectRoot, options.toolSchemaFile);
if (!existsSync(resolvedPath)) {
return { valid: false, error: `Tool schema file not found: ${options.toolSchemaFile}` };
}
let parsed: unknown;
try {
parsed = JSON.parse(readFileSync(resolvedPath, 'utf-8'));
} catch {
return { valid: false, error: `Tool schema file is not valid JSON: ${options.toolSchemaFile}` };
}
if (!Array.isArray(parsed)) {
return { valid: false, error: 'Tool schema file must contain a JSON array' };
}
if (parsed.length === 0) {
return { valid: false, error: 'Tool schema file must contain at least one tool definition' };
}
for (const [i, entry] of parsed.entries()) {
const item = entry as Record<string, unknown>;
if (typeof item.name !== 'string' || !item.name) {
return { valid: false, error: `Tool schema entry ${i} is missing a valid "name" field` };
}
if (typeof item.description !== 'string' || !item.description) {
return { valid: false, error: `Tool schema entry ${i} is missing a valid "description" field` };
}
}
options.language = 'Other';
return { valid: true };
}
// Validate outbound auth configuration
if (options.outboundAuthType && options.outboundAuthType !== 'NONE') {
const hasInlineOAuth = !!(options.oauthClientId ?? options.oauthClientSecret ?? options.oauthDiscoveryUrl);
// Reject inline OAuth fields with API_KEY auth type
if (options.outboundAuthType === 'API_KEY' && hasInlineOAuth) {
return {
valid: false,
error: 'Inline OAuth fields cannot be used with API_KEY outbound auth. Use --credential-name instead.',
};
}
if (!options.credentialName && !hasInlineOAuth) {
return {
valid: false,
error:
options.outboundAuthType === 'API_KEY'
? '--credential-name is required when outbound auth type is API_KEY'
: `--credential-name or inline OAuth fields (--oauth-client-id, --oauth-client-secret, --oauth-discovery-url) required when outbound auth type is ${options.outboundAuthType}`,
};
}
// Validate inline OAuth fields are complete
if (hasInlineOAuth) {
if (!options.oauthClientId)
return { valid: false, error: '--oauth-client-id is required for inline OAuth credential creation' };
if (!options.oauthClientSecret)
return { valid: false, error: '--oauth-client-secret is required for inline OAuth credential creation' };
if (!options.oauthDiscoveryUrl)
return { valid: false, error: '--oauth-discovery-url is required for inline OAuth credential creation' };
try {
new URL(options.oauthDiscoveryUrl);
} catch {
return { valid: false, error: '--oauth-discovery-url must be a valid URL' };
}
}
// Validate that referenced credential exists
if (options.credentialName) {
const credentialValidation = await validateCredentialExists(options.credentialName);
if (!credentialValidation.valid) {
return credentialValidation;
}
}
}
// Schema-based targets (OpenAPI / Smithy)
if (mappedType === 'openApiSchema' || mappedType === 'smithyModel') {
if (!options.schema) {
return { valid: false, error: '--schema is required for schema-based target types' };
}
if (options.endpoint) {
return { valid: false, error: `--endpoint is not applicable for ${mappedType} target type` };
}
if (options.host) {
return { valid: false, error: `--host is not applicable for ${mappedType} target type` };
}
// Auth validation from centralized config
const authConfig = TARGET_TYPE_AUTH_CONFIG[mappedType as keyof typeof TARGET_TYPE_AUTH_CONFIG];
const providedAuth = options.outboundAuthType ?? 'NONE';
if (authConfig.authRequired && providedAuth === 'NONE') {
return {
valid: false,
error: `${mappedType} targets require outbound auth (${authConfig.validAuthTypes.join(' or ')})`,
};
}
if (authConfig.validAuthTypes.length === 0 && providedAuth !== 'NONE') {
return {
valid: false,
error: `${mappedType} targets use IAM role auth; --outbound-auth is not applicable`,
};
}
const isS3 = options.schema.startsWith('s3://');
if (isS3) {
// Validate S3 URI format: s3://bucket/key
const s3Path = options.schema.slice(5); // strip 's3://'
if (!s3Path.includes('/') || s3Path.startsWith('/')) {
return { valid: false, error: 'Invalid S3 URI format. Expected: s3://bucket-name/key' };
}
} else {
// Local file validation — resolve relative to project root (parent of agentcore/)
const configRoot = findConfigRoot();
const projectRoot = configRoot ? dirname(configRoot) : undefined;
const resolvedPath = projectRoot ? join(projectRoot, options.schema) : resolve(options.schema);
if (!existsSync(resolvedPath)) {
return {
valid: false,
error: projectRoot
? `Schema file not found: ${options.schema} (resolved to ${resolvedPath}). Path should be relative to the project root.`
: `Schema file not found: ${options.schema}`,
};
}
const ext = extname(resolvedPath).toLowerCase();
if (ext !== '.json') {
return { valid: false, error: `Schema file must be a JSON file (.json), got: ${ext}` };
}
}
if (options.schemaS3Account && !isS3) {
return { valid: false, error: '--schema-s3-account is only valid with S3 URIs' };
}
options.language = 'Other';
return { valid: true };
}
if (mappedType === 'mcpServer') {
if (options.host) {
return { valid: false, error: '--host is not applicable for MCP server targets' };
}
if (!options.endpoint) {
return { valid: false, error: '--endpoint is required for mcp-server type' };
}
try {
const url = new URL(options.endpoint);
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
return { valid: false, error: 'Endpoint must use http:// or https:// protocol' };
}
} catch {
return { valid: false, error: 'Endpoint must be a valid URL (e.g. https://example.com/mcp)' };
}
if (options.lambdaArn) {
return { valid: false, error: '--lambda-arn is not applicable for mcp-server type' };
}
if (options.toolSchemaFile) {
return { valid: false, error: '--tool-schema-file is not applicable for mcp-server type' };
}
// Populate defaults for fields skipped by external endpoint flow
options.language ??= 'Other';
return { valid: true };
}
if (!options.language) {
return { valid: false, error: '--language is required' };
}
if (options.language !== 'Python' && options.language !== 'TypeScript' && options.language !== 'Other') {
return { valid: false, error: 'Invalid language. Valid options: Python, TypeScript, Other' };
}
return { valid: true };
}
// Memory validation (v2: top-level resource, no owner)
export function validateAddMemoryOptions(options: AddMemoryOptions): ValidationResult {
if (!options.name) {
return { valid: false, error: '--name is required' };
}
if (options.strategies) {
const strategies = options.strategies
.split(',')
.map(s => s.trim())
.filter(Boolean);
for (const strategy of strategies) {
if (!VALID_STRATEGIES.includes(strategy)) {
return { valid: false, error: `Invalid strategy: ${strategy}. Must be one of: ${VALID_STRATEGIES.join(', ')}` };
}
}
}
return { valid: true };
}
// Credential validation (v2: credential resource, no owner)
export function validateAddCredentialOptions(options: AddCredentialOptions): ValidationResult {
if (!options.name) {
return { valid: false, error: '--name is required' };
}
const identityType = options.type ?? 'api-key';
if (identityType === 'oauth') {
if (!options.discoveryUrl) {
return { valid: false, error: '--discovery-url is required for OAuth credentials' };
}
try {
new URL(options.discoveryUrl);
} catch {
return { valid: false, error: '--discovery-url must be a valid URL' };
}
if (!options.clientId) {
return { valid: false, error: '--client-id is required for OAuth credentials' };
}
if (!options.clientSecret) {
return { valid: false, error: '--client-secret is required for OAuth credentials' };
}
return { valid: true };
}
if (!options.apiKey) {
return { valid: false, error: '--api-key is required' };
}
return { valid: true };
}