forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagentcore.ts
More file actions
1086 lines (926 loc) · 34 KB
/
Copy pathagentcore.ts
File metadata and controls
1086 lines (926 loc) · 34 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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { parseJsonRpcResponse } from '../../lib/utils/json-rpc';
import { getCredentialProvider } from './account';
import {
BedrockAgentCoreClient,
EvaluateCommand,
type EvaluationReferenceInput,
InvokeAgentRuntimeCommand,
InvokeAgentRuntimeCommandCommand,
StopRuntimeSessionCommand,
} from '@aws-sdk/client-bedrock-agentcore';
import type { HttpRequest } from '@smithy/protocol-http';
import type { DocumentType } from '@smithy/types';
/**
* Create a BedrockAgentCoreClient with optional custom header injection middleware.
*/
function createAgentCoreClient(region: string, headers?: Record<string, string>): BedrockAgentCoreClient {
const client = new BedrockAgentCoreClient({
region,
credentials: getCredentialProvider(),
});
if (headers && Object.keys(headers).length > 0) {
client.middlewareStack.add(
next => async args => {
const request = args.request as HttpRequest;
for (const [name, value] of Object.entries(headers)) {
request.headers[name] = value;
}
return next(args);
},
{ step: 'build', name: 'addCustomHeaders' }
);
}
return client;
}
/** Logger interface for SSE events */
export interface SSELogger {
logSSEEvent(rawLine: string): void;
}
/** Default user ID sent with invocations. Container agents require this to obtain workload access tokens. */
export const DEFAULT_RUNTIME_USER_ID = 'default-user';
export interface InvokeAgentRuntimeOptions {
region: string;
runtimeArn: string;
payload: string;
sessionId?: string;
/** User ID for the runtime invocation. Defaults to 'default-user'. Required for Container agents using identity providers. */
userId?: string;
/** Optional logger for SSE event debugging */
logger?: SSELogger;
/** Custom headers to forward to the agent runtime */
headers?: Record<string, string>;
/** Bearer token for CUSTOM_JWT auth. When provided, uses raw HTTP with Authorization header instead of SigV4. */
bearerToken?: string;
}
export interface InvokeAgentRuntimeResult {
content: string;
sessionId?: string;
}
export interface StreamingInvokeResult {
stream: AsyncGenerator<string, void, unknown>;
sessionId: string | undefined;
}
export interface StopRuntimeSessionOptions {
region: string;
runtimeArn: string;
sessionId: string;
}
export interface StopRuntimeSessionResult {
sessionId: string | undefined;
statusCode: number | undefined;
}
/**
* Parse a single SSE data line and extract the content.
* Returns null if the line is not a data line or contains an error.
*/
export function parseSSELine(line: string): { content: string | null; error: string | null } {
if (!line.startsWith('data: ')) {
return { content: null, error: null };
}
const content = line.slice(6);
try {
const parsed: unknown = JSON.parse(content);
if (typeof parsed === 'string') {
return { content: parsed, error: null };
} else if (parsed && typeof parsed === 'object' && 'error' in parsed) {
return { content: null, error: String((parsed as { error: unknown }).error) };
}
} catch {
return { content, error: null };
}
return { content: null, error: null };
}
/**
* Parse SSE response into combined text.
*/
export function parseSSE(text: string): string {
const parts: string[] = [];
for (const line of text.split('\n')) {
const { content, error } = parseSSELine(line);
if (error) {
return `Error: ${error}`;
}
if (content) {
parts.push(content);
}
}
return parts.join('');
}
/**
* Extract result from a JSON response object.
* Handles both {"result": "..."} and plain text responses.
*/
export function extractResult(text: string): string {
try {
const parsed: unknown = JSON.parse(text);
if (parsed && typeof parsed === 'object' && 'result' in parsed) {
const result = (parsed as { result: unknown }).result;
return typeof result === 'string' ? result : JSON.stringify(result, null, 2);
}
return typeof parsed === 'string' ? parsed : JSON.stringify(parsed, null, 2);
} catch {
return text;
}
}
// ---------------------------------------------------------------------------
// Bearer token (CUSTOM_JWT) thin HTTP client
// ---------------------------------------------------------------------------
/**
* Build the invoke URL for a runtime ARN.
* Format: https://bedrock-agentcore.{REGION}.amazonaws.com/runtimes/{ESCAPED_ARN}/invocations?qualifier=DEFAULT
*/
function buildInvokeUrl(region: string, runtimeArn: string): string {
const escapedArn = encodeURIComponent(runtimeArn);
return `https://bedrock-agentcore.${region}.amazonaws.com/runtimes/${escapedArn}/invocations?qualifier=DEFAULT`;
}
/**
* Invoke an AgentCore Runtime using bearer token auth (raw HTTP, no SigV4).
* Used when the runtime has CUSTOM_JWT authorizer configured.
*/
async function invokeWithBearerTokenStreaming(options: InvokeAgentRuntimeOptions): Promise<StreamingInvokeResult> {
const url = buildInvokeUrl(options.region, options.runtimeArn);
const headers: Record<string, string> = {
Authorization: `Bearer ${options.bearerToken}`,
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
};
if (options.sessionId) {
headers['X-Amzn-Bedrock-AgentCore-Runtime-Session-Id'] = options.sessionId;
}
headers['X-Amzn-Bedrock-AgentCore-Runtime-User-Id'] = options.userId ?? DEFAULT_RUNTIME_USER_ID;
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ prompt: options.payload }),
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`Invoke failed (${res.status}): ${body || res.statusText}`);
}
const sessionId = res.headers.get('X-Amzn-Bedrock-AgentCore-Runtime-Session-Id') ?? undefined;
const bodyReader = res.body?.getReader();
if (!bodyReader) {
throw new Error('No response body from AgentCore Runtime');
}
// Assign to const after null check so TypeScript narrows the type inside the generator
const reader = bodyReader;
const decoder = new TextDecoder();
const { logger } = options;
async function* streamGenerator(): AsyncGenerator<string, void, unknown> {
let buffer = '';
let fullResponse = '';
let yieldedContent = false;
try {
while (true) {
const result = await reader.read();
if (result.done) break;
const decoded = decoder.decode(result.value as Uint8Array | undefined, { stream: true });
buffer += decoded;
fullResponse += decoded;
const lines = buffer.split('\n');
buffer = lines.pop() ?? '';
for (const line of lines) {
if (logger && line.trim()) {
logger.logSSEEvent(line);
}
const { content, error } = parseSSELine(line);
if (error) {
yield `Error: ${error}`;
return;
}
if (content) {
yield content;
yieldedContent = true;
}
}
}
if (buffer) {
if (logger && buffer.trim()) {
logger.logSSEEvent(buffer);
}
const { content, error } = parseSSELine(buffer);
if (error) {
yield `Error: ${error}`;
} else if (content) {
yield content;
yieldedContent = true;
}
}
if (!yieldedContent && fullResponse.trim()) {
yield extractResult(fullResponse.trim());
}
} finally {
reader.releaseLock();
}
}
return { stream: streamGenerator(), sessionId };
}
/**
* Invoke an AgentCore Runtime using bearer token auth (non-streaming).
*/
async function invokeWithBearerToken(options: InvokeAgentRuntimeOptions): Promise<InvokeAgentRuntimeResult> {
const url = buildInvokeUrl(options.region, options.runtimeArn);
const headers: Record<string, string> = {
Authorization: `Bearer ${options.bearerToken}`,
'Content-Type': 'application/json',
Accept: 'application/json',
};
if (options.sessionId) {
headers['X-Amzn-Bedrock-AgentCore-Runtime-Session-Id'] = options.sessionId;
}
headers['X-Amzn-Bedrock-AgentCore-Runtime-User-Id'] = options.userId ?? DEFAULT_RUNTIME_USER_ID;
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({ prompt: options.payload }),
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`Invoke failed (${res.status}): ${body || res.statusText}`);
}
const sessionId = res.headers.get('X-Amzn-Bedrock-AgentCore-Runtime-Session-Id') ?? undefined;
const text = await res.text();
const content = text.includes('data: ') ? parseSSE(text) : extractResult(text);
return { content, sessionId };
}
// ---------------------------------------------------------------------------
// SDK-based invoke (SigV4)
// ---------------------------------------------------------------------------
/**
* Invoke an AgentCore Runtime and stream the response chunks.
* Returns an object with the stream generator and session ID.
*/
export async function invokeAgentRuntimeStreaming(options: InvokeAgentRuntimeOptions): Promise<StreamingInvokeResult> {
if (options.bearerToken) {
return invokeWithBearerTokenStreaming(options);
}
const client = createAgentCoreClient(options.region, options.headers);
const command = new InvokeAgentRuntimeCommand({
agentRuntimeArn: options.runtimeArn,
payload: new TextEncoder().encode(JSON.stringify({ prompt: options.payload })),
contentType: 'application/json',
accept: 'application/json',
runtimeSessionId: options.sessionId,
runtimeUserId: options.userId ?? DEFAULT_RUNTIME_USER_ID,
});
const response = await client.send(command);
const sessionId = response.runtimeSessionId;
if (!response.response) {
throw new Error('No response from AgentCore Runtime');
}
const webStream = response.response.transformToWebStream();
const reader = webStream.getReader();
const decoder = new TextDecoder();
async function* streamGenerator(): AsyncGenerator<string, void, unknown> {
let buffer = '';
let fullResponse = '';
let yieldedContent = false;
const { logger } = options;
try {
while (true) {
const result = await reader.read();
if (result.done) break;
const decoded = decoder.decode(result.value as Uint8Array, { stream: true });
buffer += decoded;
fullResponse += decoded;
const lines = buffer.split('\n');
buffer = lines.pop() ?? '';
for (const line of lines) {
// Log raw SSE line if logger provided
if (logger && line.trim()) {
logger.logSSEEvent(line);
}
const { content, error } = parseSSELine(line);
if (error) {
yield `Error: ${error}`;
return;
}
if (content) {
yield content;
yieldedContent = true;
}
}
}
// Process any remaining content in the buffer
if (buffer) {
// Log raw SSE line if logger provided
if (logger && buffer.trim()) {
logger.logSSEEvent(buffer);
}
const { content, error } = parseSSELine(buffer);
if (error) {
yield `Error: ${error}`;
} else if (content) {
yield content;
yieldedContent = true;
}
}
// Fallback for plain JSON responses (non-SSE)
if (!yieldedContent && fullResponse.trim()) {
yield extractResult(fullResponse.trim());
}
} finally {
reader.releaseLock();
}
}
return {
stream: streamGenerator(),
sessionId,
};
}
/**
* Invoke an AgentCore Runtime and return the response.
*/
export async function invokeAgentRuntime(options: InvokeAgentRuntimeOptions): Promise<InvokeAgentRuntimeResult> {
if (options.bearerToken) {
return invokeWithBearerToken(options);
}
const client = createAgentCoreClient(options.region, options.headers);
const command = new InvokeAgentRuntimeCommand({
agentRuntimeArn: options.runtimeArn,
payload: new TextEncoder().encode(JSON.stringify({ prompt: options.payload })),
contentType: 'application/json',
accept: 'application/json',
runtimeSessionId: options.sessionId,
runtimeUserId: options.userId ?? DEFAULT_RUNTIME_USER_ID,
});
const response = await client.send(command);
if (!response.response) {
throw new Error('No response from AgentCore Runtime');
}
const bytes = await response.response.transformToByteArray();
const text = new TextDecoder().decode(bytes);
// Parse SSE format if present
const content = text.includes('data: ') ? parseSSE(text) : extractResult(text);
return {
content,
sessionId: response.runtimeSessionId,
};
}
// ============================================================================
// Evaluate
// ============================================================================
export interface EvaluateOptions {
region: string;
evaluatorId: string;
sessionSpans: DocumentType[];
targetSpanIds?: string[];
targetTraceIds?: string[];
evaluationReferenceInputs?: EvaluationReferenceInput[];
}
export interface EvaluationResultContext {
sessionId: string | undefined;
traceId: string | undefined;
spanId: string | undefined;
}
export interface EvaluationResultTokenUsage {
inputTokens: number;
outputTokens: number;
totalTokens: number;
}
export interface EvaluationResult {
evaluatorArn: string | undefined;
evaluatorId: string | undefined;
evaluatorName: string | undefined;
explanation: string | undefined;
value: number | undefined;
label: string | undefined;
errorMessage: string | undefined;
errorCode: string | undefined;
context: EvaluationResultContext | undefined;
tokenUsage: EvaluationResultTokenUsage | undefined;
}
export interface EvaluateResult {
evaluationResults: EvaluationResult[];
}
/**
* Run on-demand evaluation of agent traces using a specified evaluator.
*/
export async function evaluate(options: EvaluateOptions): Promise<EvaluateResult> {
const client = new BedrockAgentCoreClient({
region: options.region,
credentials: getCredentialProvider(),
});
const evaluationTarget = options.targetSpanIds
? { spanIds: options.targetSpanIds }
: options.targetTraceIds
? { traceIds: options.targetTraceIds }
: undefined;
const command = new EvaluateCommand({
evaluatorId: options.evaluatorId,
evaluationInput: {
sessionSpans: options.sessionSpans,
},
...(evaluationTarget ? { evaluationTarget } : {}),
...(options.evaluationReferenceInputs ? { evaluationReferenceInputs: options.evaluationReferenceInputs } : {}),
});
const response = await client.send(command);
if (!response.evaluationResults) {
throw new Error('No evaluation results returned');
}
return {
evaluationResults: response.evaluationResults.map(r => {
const spanContext = r.context && 'spanContext' in r.context ? r.context.spanContext : undefined;
return {
evaluatorArn: r.evaluatorArn,
evaluatorId: r.evaluatorId,
evaluatorName: r.evaluatorName,
explanation: r.explanation,
value: r.value,
label: r.label,
errorMessage: r.errorMessage,
errorCode: r.errorCode,
context: spanContext
? {
sessionId: spanContext.sessionId,
traceId: spanContext.traceId,
spanId: spanContext.spanId,
}
: undefined,
tokenUsage: r.tokenUsage
? {
inputTokens: r.tokenUsage.inputTokens ?? 0,
outputTokens: r.tokenUsage.outputTokens ?? 0,
totalTokens: r.tokenUsage.totalTokens ?? 0,
}
: undefined,
};
}),
};
}
// ---------------------------------------------------------------------------
// MCP: JSON-RPC over InvokeAgentRuntime
// ---------------------------------------------------------------------------
export interface McpInvokeOptions {
region: string;
runtimeArn: string;
userId?: string;
mcpSessionId?: string;
logger?: SSELogger;
/** Custom headers to forward to the agent runtime */
headers?: Record<string, string>;
/** Bearer token for CUSTOM_JWT auth. When provided, uses raw HTTP with Authorization header instead of SigV4. */
bearerToken?: string;
}
export interface McpToolDef {
name: string;
description?: string;
inputSchema?: Record<string, unknown>;
}
export interface McpListToolsResult {
tools: McpToolDef[];
mcpSessionId?: string;
}
let mcpRequestId = 1;
interface McpRpcResult {
result: Record<string, unknown>;
mcpSessionId?: string;
error?: { message?: string; code?: number };
}
const TRANSIENT_STATUS_CODES = new Set([429, 500, 502, 503, 504]);
const MAX_FETCH_RETRIES = 3;
const FETCH_RETRY_DELAY_MS = 1000;
/** Retry-aware fetch for transient failures (5xx, 429, network errors). */
async function fetchWithRetry(url: string, init: RequestInit, logger?: SSELogger): Promise<Response> {
for (let attempt = 0; attempt < MAX_FETCH_RETRIES; attempt++) {
try {
const res = await fetch(url, init);
if (res.ok || !TRANSIENT_STATUS_CODES.has(res.status) || attempt === MAX_FETCH_RETRIES - 1) {
return res;
}
logger?.logSSEEvent(`Transient failure (${res.status}), retrying (${attempt + 1}/${MAX_FETCH_RETRIES})...`);
} catch (err) {
if (attempt === MAX_FETCH_RETRIES - 1) throw err;
logger?.logSSEEvent(`Network error, retrying (${attempt + 1}/${MAX_FETCH_RETRIES})...`);
}
await new Promise(resolve => setTimeout(resolve, FETCH_RETRY_DELAY_MS));
}
throw new Error('fetchWithRetry: exhausted retries');
}
/** Build the common headers for MCP bearer-token HTTP requests. */
function buildMcpBearerHeaders(options: McpInvokeOptions): Record<string, string> {
const headers: Record<string, string> = {
Authorization: `Bearer ${options.bearerToken}`,
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
'Mcp-Protocol-Version': '2025-03-26',
'X-Amzn-Bedrock-AgentCore-Runtime-User-Id': options.userId ?? DEFAULT_RUNTIME_USER_ID,
};
if (options.mcpSessionId) {
headers['Mcp-Session-Id'] = options.mcpSessionId;
}
if (options.headers) {
for (const [name, value] of Object.entries(options.headers)) {
headers[name] = value;
}
}
return headers;
}
/** Send an MCP JSON-RPC call using bearer-token auth (raw HTTP, no SigV4). */
async function mcpRpcCallWithBearer(options: McpInvokeOptions, body: Record<string, unknown>): Promise<McpRpcResult> {
const url = buildInvokeUrl(options.region, options.runtimeArn);
const headers = buildMcpBearerHeaders(options);
options.logger?.logSSEEvent(`MCP request: ${JSON.stringify(body)}`);
const res = await fetchWithRetry(url, { method: 'POST', headers, body: JSON.stringify(body) }, options.logger);
if (!res.ok) {
const errBody = await res.text().catch(() => '');
throw new Error(`MCP call failed (${res.status}): ${errBody || res.statusText}`);
}
const text = await res.text();
options.logger?.logSSEEvent(`MCP response: ${text}`);
const parsed = parseJsonRpcResponse(text);
return {
result: (parsed.result as Record<string, unknown>) ?? {},
mcpSessionId: res.headers.get('Mcp-Session-Id') ?? undefined,
error: parsed.error as McpRpcResult['error'],
};
}
/** Send an MCP JSON-RPC notification using bearer-token auth (raw HTTP, no SigV4). */
async function mcpRpcNotifyWithBearer(options: McpInvokeOptions, body: Record<string, unknown>): Promise<void> {
const url = buildInvokeUrl(options.region, options.runtimeArn);
const headers = buildMcpBearerHeaders(options);
const res = await fetchWithRetry(url, { method: 'POST', headers, body: JSON.stringify(body) }, options.logger);
if (!res.ok) {
const errBody = await res.text().catch(() => '');
throw new Error(`MCP notification failed (${res.status}): ${errBody || res.statusText}`);
}
}
/** Send a JSON-RPC payload through InvokeAgentRuntime and return the parsed response. */
async function mcpRpcCall(options: McpInvokeOptions, body: Record<string, unknown>): Promise<McpRpcResult> {
// TODO: Consider unified transport refactor (Option B) when a third auth method or A2A CUSTOM_JWT is needed.
if (options.bearerToken) {
return mcpRpcCallWithBearer(options, body);
}
const client = createAgentCoreClient(options.region, options.headers);
options.logger?.logSSEEvent(`MCP request: ${JSON.stringify(body)}`);
const command = new InvokeAgentRuntimeCommand({
agentRuntimeArn: options.runtimeArn,
payload: new TextEncoder().encode(JSON.stringify(body)),
contentType: 'application/json',
accept: 'application/json, text/event-stream',
mcpSessionId: options.mcpSessionId,
mcpProtocolVersion: '2025-03-26',
runtimeUserId: options.userId ?? DEFAULT_RUNTIME_USER_ID,
});
const response = await client.send(command);
if (!response.response) {
throw new Error('No response from AgentCore Runtime');
}
const bytes = await response.response.transformToByteArray();
const text = new TextDecoder().decode(bytes);
options.logger?.logSSEEvent(`MCP response: ${text}`);
const parsed = parseJsonRpcResponse(text);
return {
result: (parsed.result as Record<string, unknown>) ?? {},
mcpSessionId: response.mcpSessionId,
error: parsed.error as McpRpcResult['error'],
};
}
/** Call mcpRpcCall and throw on JSON-RPC errors. Use mcpRpcCall directly when errors should be tolerated. */
async function mcpRpcCallStrict(options: McpInvokeOptions, body: Record<string, unknown>): Promise<McpRpcResult> {
const result = await mcpRpcCall(options, body);
if (result.error) {
throw new Error(result.error.message ?? `MCP error (code ${result.error.code})`);
}
return result;
}
/** Send a JSON-RPC notification (no id, no response expected). */
async function mcpRpcNotify(options: McpInvokeOptions, body: Record<string, unknown>): Promise<void> {
if (options.bearerToken) {
return mcpRpcNotifyWithBearer(options, body);
}
const client = createAgentCoreClient(options.region, options.headers);
const command = new InvokeAgentRuntimeCommand({
agentRuntimeArn: options.runtimeArn,
payload: new TextEncoder().encode(JSON.stringify(body)),
contentType: 'application/json',
accept: 'application/json, text/event-stream',
mcpSessionId: options.mcpSessionId,
mcpProtocolVersion: '2025-03-26',
runtimeUserId: options.userId ?? DEFAULT_RUNTIME_USER_ID,
});
await client.send(command);
}
/**
* Initialize MCP session and list available tools via InvokeAgentRuntime.
* Retries on cold-start initialization timeouts.
*/
export async function mcpListTools(options: McpInvokeOptions): Promise<McpListToolsResult> {
const maxRetries = 3;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await mcpListToolsOnce(options);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
const isColdStart = msg.includes('initialization time exceeded') || msg.includes('initialization');
if (isColdStart && attempt < maxRetries - 1) {
options.logger?.logSSEEvent(`MCP cold start (attempt ${attempt + 1}/${maxRetries}), retrying...`);
await new Promise(resolve => setTimeout(resolve, 2000));
continue;
}
throw err;
}
}
throw new Error('Failed to list MCP tools after retries');
}
async function mcpListToolsOnce(options: McpInvokeOptions): Promise<McpListToolsResult> {
// 1. Initialize — tolerate JSON-RPC errors (stateless servers may reject initialize but still return a session ID)
const initResult = await mcpRpcCall(options, {
jsonrpc: '2.0',
id: mcpRequestId++,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agentcore-cli', version: '1.0.0' },
},
});
if (initResult.error) {
options.logger?.logSSEEvent(
`MCP initialize returned error (expected for stateless servers): ${initResult.error.message}`
);
}
const sessionId = initResult.mcpSessionId;
const optionsWithSession = { ...options, mcpSessionId: sessionId };
// 2. Send initialized notification
await mcpRpcNotify(optionsWithSession, {
jsonrpc: '2.0',
method: 'notifications/initialized',
});
// 3. List tools
const listResult = await mcpRpcCallStrict(optionsWithSession, {
jsonrpc: '2.0',
id: mcpRequestId++,
method: 'tools/list',
params: {},
});
const tools = (listResult.result as { tools?: McpToolDef[] }).tools ?? [];
return {
tools: tools.map(t => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
mcpSessionId: sessionId,
};
}
/**
* Initialize an MCP session (without listing tools).
* Returns just the session ID needed for subsequent tool calls.
*/
export async function mcpInitSession(options: McpInvokeOptions): Promise<string | undefined> {
const initResult = await mcpRpcCall(options, {
jsonrpc: '2.0',
id: mcpRequestId++,
method: 'initialize',
params: {
protocolVersion: '2025-03-26',
capabilities: {},
clientInfo: { name: 'agentcore-cli', version: '1.0.0' },
},
});
const sessionId = initResult.mcpSessionId;
const optionsWithSession = { ...options, mcpSessionId: sessionId };
await mcpRpcNotify(optionsWithSession, {
jsonrpc: '2.0',
method: 'notifications/initialized',
});
return sessionId;
}
/**
* Call an MCP tool via InvokeAgentRuntime.
* Retries on cold-start initialization timeouts.
*/
export async function mcpCallTool(
options: McpInvokeOptions,
toolName: string,
args: Record<string, unknown>
): Promise<string> {
const maxRetries = 3;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const { result } = await mcpRpcCallStrict(options, {
jsonrpc: '2.0',
id: mcpRequestId++,
method: 'tools/call',
params: { name: toolName, arguments: args },
});
const content = (result as { content?: { type?: string; text?: string }[] }).content;
if (content) {
const texts: string[] = [];
for (const item of content) {
if (item.text !== undefined) {
texts.push(item.text);
}
}
if (texts.length > 0) return texts.join('');
}
return JSON.stringify(result, null, 2);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
const isColdStart = msg.includes('initialization time exceeded') || msg.includes('initialization');
if (isColdStart && attempt < maxRetries - 1) {
options.logger?.logSSEEvent(`MCP cold start (attempt ${attempt + 1}/${maxRetries}), retrying...`);
await new Promise(resolve => setTimeout(resolve, 2000));
continue;
}
throw err;
}
}
throw new Error('Failed to call MCP tool after retries');
}
// ---------------------------------------------------------------------------
// A2A: JSON-RPC message/send over InvokeAgentRuntime
// ---------------------------------------------------------------------------
export interface A2AInvokeOptions {
region: string;
runtimeArn: string;
userId?: string;
sessionId?: string;
logger?: SSELogger;
/** Custom headers to forward to the agent runtime */
headers?: Record<string, string>;
}
let a2aRequestId = 1;
/**
* Invoke a deployed A2A agent via InvokeAgentRuntime with JSON-RPC message/send.
* Streams text parts from the response artifacts.
*/
export async function invokeA2ARuntime(options: A2AInvokeOptions, message: string): Promise<StreamingInvokeResult> {
const client = createAgentCoreClient(options.region, options.headers);
const body = {
jsonrpc: '2.0',
id: a2aRequestId++,
method: 'message/send',
params: {
message: {
role: 'user',
parts: [{ kind: 'text', text: message }],
messageId: `msg-${Date.now()}`,
},
},
};
options.logger?.logSSEEvent(`A2A request: ${JSON.stringify(body)}`);
const command = new InvokeAgentRuntimeCommand({
agentRuntimeArn: options.runtimeArn,
payload: new TextEncoder().encode(JSON.stringify(body)),
contentType: 'application/json',
accept: 'application/json, text/event-stream',
runtimeUserId: options.userId ?? DEFAULT_RUNTIME_USER_ID,
...(options.sessionId && { runtimeSessionId: options.sessionId }),
});
const response = await client.send(command);
if (!response.response) {
throw new Error('No response from AgentCore Runtime');
}
const bytes = await response.response.transformToByteArray();
const text = new TextDecoder().decode(bytes);
options.logger?.logSSEEvent(`A2A response: ${text}`);
const parsed = parseA2AResponse(text);
return {
stream: singleValueStream(parsed),
sessionId: undefined,
};
}
/** Wrap a single string value as an AsyncGenerator for StreamingInvokeResult compatibility. */
// eslint-disable-next-line @typescript-eslint/require-await
async function* singleValueStream(value: string): AsyncGenerator<string, void, unknown> {
yield value;
}
/** Extract text content from A2A JSON-RPC response. Supports both kind:'text' and type:'text' part formats. */
export function parseA2AResponse(text: string): string {
try {
const parsed: unknown = JSON.parse(text);
if (!parsed || typeof parsed !== 'object') return text;
const obj = parsed as Record<string, unknown>;
// Check for JSON-RPC error
if (obj.error && typeof obj.error === 'object') {
const err = obj.error as { message?: string };
return `Error: ${err.message ?? JSON.stringify(obj.error)}`;
}
// Extract text from result.artifacts[].parts[].text
const result = obj.result as Record<string, unknown> | undefined;
if (!result) return text;
const artifacts = result.artifacts as { parts?: { kind?: string; type?: string; text?: string }[] }[] | undefined;
if (artifacts) {
const texts: string[] = [];
for (const artifact of artifacts) {
if (artifact.parts) {
for (const part of artifact.parts) {
if ((part.kind === 'text' || part.type === 'text') && part.text !== undefined) {
texts.push(part.text);
}
}
}
}
if (texts.length > 0) return texts.join('');
}
// Fallback: check history for the last assistant message
const history = result.history as
| { role?: string; parts?: { kind?: string; type?: string; text?: string }[] }[]
| undefined;
if (history) {
for (let i = history.length - 1; i >= 0; i--) {
const msg = history[i];
if (msg?.role === 'agent' && msg.parts) {
const agentTexts = msg.parts
.filter(p => (p.kind === 'text' || p.type === 'text') && p.text !== undefined)
.map(p => p.text!);
if (agentTexts.length > 0) return agentTexts.join('');
}
}
}
return JSON.stringify(result, null, 2);
} catch {
return text;
}
}
/**
* Stop a runtime session.
*/
export async function stopRuntimeSession(options: StopRuntimeSessionOptions): Promise<StopRuntimeSessionResult> {
const client = new BedrockAgentCoreClient({
region: options.region,
credentials: getCredentialProvider(),
});
const command = new StopRuntimeSessionCommand({
agentRuntimeArn: options.runtimeArn,
runtimeSessionId: options.sessionId,
});
const response = await client.send(command);
return {
sessionId: response.runtimeSessionId,
statusCode: response.statusCode,
};
}