@mastra/client-js 0.0.0-vector-sources-20250516175436 → 0.0.0-vector-query-tool-provider-options-20250828222356

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.
Files changed (91) hide show
  1. package/.turbo/turbo-build.log +18 -0
  2. package/CHANGELOG.md +1318 -2
  3. package/LICENSE.md +11 -42
  4. package/README.md +2 -1
  5. package/dist/adapters/agui.d.ts +23 -0
  6. package/dist/adapters/agui.d.ts.map +1 -0
  7. package/dist/client.d.ts +274 -0
  8. package/dist/client.d.ts.map +1 -0
  9. package/dist/example.d.ts +2 -0
  10. package/dist/example.d.ts.map +1 -0
  11. package/dist/index.cjs +1801 -137
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +4 -883
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +1803 -139
  16. package/dist/index.js.map +1 -0
  17. package/dist/resources/a2a.d.ts +41 -0
  18. package/dist/resources/a2a.d.ts.map +1 -0
  19. package/dist/resources/agent.d.ts +130 -0
  20. package/dist/resources/agent.d.ts.map +1 -0
  21. package/dist/resources/base.d.ts +13 -0
  22. package/dist/resources/base.d.ts.map +1 -0
  23. package/dist/resources/index.d.ts +12 -0
  24. package/dist/resources/index.d.ts.map +1 -0
  25. package/dist/resources/legacy-workflow.d.ts +87 -0
  26. package/dist/resources/legacy-workflow.d.ts.map +1 -0
  27. package/dist/resources/mcp-tool.d.ts +27 -0
  28. package/dist/resources/mcp-tool.d.ts.map +1 -0
  29. package/dist/resources/memory-thread.d.ts +53 -0
  30. package/dist/resources/memory-thread.d.ts.map +1 -0
  31. package/dist/resources/network-memory-thread.d.ts +47 -0
  32. package/dist/resources/network-memory-thread.d.ts.map +1 -0
  33. package/dist/resources/network.d.ts +30 -0
  34. package/dist/resources/network.d.ts.map +1 -0
  35. package/dist/resources/observability.d.ts +19 -0
  36. package/dist/resources/observability.d.ts.map +1 -0
  37. package/dist/resources/tool.d.ts +23 -0
  38. package/dist/resources/tool.d.ts.map +1 -0
  39. package/dist/resources/vNextNetwork.d.ts +42 -0
  40. package/dist/resources/vNextNetwork.d.ts.map +1 -0
  41. package/dist/resources/vector.d.ts +48 -0
  42. package/dist/resources/vector.d.ts.map +1 -0
  43. package/dist/resources/workflow.d.ts +154 -0
  44. package/dist/resources/workflow.d.ts.map +1 -0
  45. package/dist/types.d.ts +449 -0
  46. package/dist/types.d.ts.map +1 -0
  47. package/dist/utils/index.d.ts +3 -0
  48. package/dist/utils/index.d.ts.map +1 -0
  49. package/dist/utils/process-client-tools.d.ts +3 -0
  50. package/dist/utils/process-client-tools.d.ts.map +1 -0
  51. package/dist/utils/process-mastra-stream.d.ts +7 -0
  52. package/dist/utils/process-mastra-stream.d.ts.map +1 -0
  53. package/dist/utils/zod-to-json-schema.d.ts +3 -0
  54. package/dist/utils/zod-to-json-schema.d.ts.map +1 -0
  55. package/eslint.config.js +6 -1
  56. package/integration-tests/agui-adapter.test.ts +122 -0
  57. package/integration-tests/package.json +18 -0
  58. package/integration-tests/src/mastra/index.ts +35 -0
  59. package/integration-tests/vitest.config.ts +9 -0
  60. package/package.json +32 -19
  61. package/src/adapters/agui.test.ts +116 -3
  62. package/src/adapters/agui.ts +30 -12
  63. package/src/client.ts +333 -24
  64. package/src/example.ts +46 -15
  65. package/src/index.test.ts +429 -6
  66. package/src/index.ts +1 -0
  67. package/src/resources/a2a.ts +35 -25
  68. package/src/resources/agent.ts +1284 -20
  69. package/src/resources/base.ts +8 -1
  70. package/src/resources/index.ts +3 -2
  71. package/src/resources/{vnext-workflow.ts → legacy-workflow.ts} +124 -143
  72. package/src/resources/memory-thread.test.ts +285 -0
  73. package/src/resources/memory-thread.ts +37 -1
  74. package/src/resources/network-memory-thread.test.ts +269 -0
  75. package/src/resources/network-memory-thread.ts +81 -0
  76. package/src/resources/network.ts +7 -7
  77. package/src/resources/observability.ts +53 -0
  78. package/src/resources/tool.ts +4 -3
  79. package/src/resources/vNextNetwork.ts +194 -0
  80. package/src/resources/workflow.ts +255 -96
  81. package/src/types.ts +262 -36
  82. package/src/utils/index.ts +11 -0
  83. package/src/utils/process-client-tools.ts +32 -0
  84. package/src/utils/process-mastra-stream.test.ts +353 -0
  85. package/src/utils/process-mastra-stream.ts +49 -0
  86. package/src/utils/zod-to-json-schema.ts +23 -3
  87. package/src/v2-messages.test.ts +180 -0
  88. package/tsconfig.build.json +9 -0
  89. package/tsconfig.json +2 -2
  90. package/tsup.config.ts +17 -0
  91. package/dist/index.d.cts +0 -883
package/src/index.test.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import type { ServerDetailInfo } from '@mastra/core/mcp';
2
+ import type { ScoringEntityType, ScoringSource } from '@mastra/core/scores';
1
3
  import { describe, expect, beforeEach, it, vi } from 'vitest';
2
4
  import { MastraClient } from './client';
3
- import type { McpServerListResponse, ServerDetailInfo } from './types';
5
+ import type { McpServerListResponse } from './types';
4
6
 
5
7
  // Mock fetch globally
6
8
  global.fetch = vi.fn();
@@ -27,7 +29,13 @@ describe('MastraClient Resources', () => {
27
29
  } else {
28
30
  responseBody = new ReadableStream({
29
31
  start(controller) {
30
- controller.enqueue(new TextEncoder().encode(JSON.stringify(data)));
32
+ if (typeof data === 'string') {
33
+ controller.enqueue(new TextEncoder().encode(data));
34
+ } else if (typeof data === 'object' && data !== null) {
35
+ controller.enqueue(new TextEncoder().encode(JSON.stringify(data)));
36
+ } else {
37
+ controller.enqueue(new TextEncoder().encode(String(data)));
38
+ }
31
39
  controller.close();
32
40
  },
33
41
  });
@@ -279,7 +287,7 @@ describe('MastraClient Resources', () => {
279
287
  });
280
288
 
281
289
  it('should stream responses', async () => {
282
- const mockChunk = { content: 'test response' };
290
+ const mockChunk = `0:"test response"\n`;
283
291
  mockFetchResponse(mockChunk, { isStream: true });
284
292
 
285
293
  const response = await agent.stream({
@@ -298,10 +306,119 @@ describe('MastraClient Resources', () => {
298
306
  if (reader) {
299
307
  const { value, done } = await reader.read();
300
308
  expect(done).toBe(false);
301
- expect(new TextDecoder().decode(value)).toBe(JSON.stringify(mockChunk));
309
+ expect(new TextDecoder().decode(value)).toBe(mockChunk);
302
310
  }
303
311
  });
304
312
 
313
+ it('should stream responses with tool calls', async () => {
314
+ const firstMockChunk = `0:"test "
315
+ 0:"response"
316
+ 9:{"toolCallId":"tool1","toolName":"testTool","args":{"arg1":"value1"}}
317
+ e:{"finishReason":"tool-calls","usage":{"promptTokens":1,"completionTokens":1},"isContinued":false}
318
+ d:{"finishReason":"tool-calls","usage":{"promptTokens":2,"completionTokens":2}}
319
+ `;
320
+
321
+ const secondMockChunk = `0:"final response"
322
+ e:{"finishReason":"stop","usage":{"promptTokens":2,"completionTokens":2},"isContinued":false}
323
+ d:{"finishReason":"stop","usage":{"promptTokens":2,"completionTokens":2}}
324
+ `;
325
+
326
+ const firstResponseBody = new ReadableStream({
327
+ start(controller) {
328
+ controller.enqueue(new TextEncoder().encode(firstMockChunk));
329
+ controller.close();
330
+ },
331
+ });
332
+
333
+ const secondResponseBody = new ReadableStream({
334
+ start(controller) {
335
+ controller.enqueue(new TextEncoder().encode(secondMockChunk));
336
+ controller.close();
337
+ },
338
+ });
339
+
340
+ (global.fetch as any)
341
+ .mockResolvedValueOnce(
342
+ new Response(firstResponseBody, {
343
+ status: 200,
344
+ headers: new Headers({ 'Content-Type': 'text/event-stream' }),
345
+ }),
346
+ )
347
+ .mockResolvedValueOnce(
348
+ new Response(secondResponseBody, {
349
+ status: 200,
350
+ headers: new Headers({ 'Content-Type': 'text/event-stream' }),
351
+ }),
352
+ );
353
+
354
+ const response = await agent.stream({
355
+ messages: [
356
+ {
357
+ role: 'user',
358
+ content: 'test',
359
+ },
360
+ ],
361
+ clientTools: {
362
+ testTool: {
363
+ id: 'testTool',
364
+ description: 'Test Tool',
365
+ inputSchema: {
366
+ type: 'object',
367
+ properties: {
368
+ arg1: { type: 'string' },
369
+ },
370
+ },
371
+ execute: async () => {
372
+ return 'test result';
373
+ },
374
+ },
375
+ },
376
+ });
377
+
378
+ expect(response.body).toBeInstanceOf(ReadableStream);
379
+ const reader = response?.body?.getReader();
380
+ expect(reader).toBeDefined();
381
+
382
+ let output = '';
383
+ if (reader) {
384
+ while (true) {
385
+ const { value, done } = await reader.read();
386
+ if (done) break;
387
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
388
+ output += new TextDecoder().decode(value);
389
+ }
390
+ }
391
+
392
+ expect(global.fetch).toHaveBeenCalledTimes(2);
393
+
394
+ const [secondUrl, secondConfig] = (global.fetch as any).mock.calls[1];
395
+ expect(secondUrl).toBe(`${clientOptions.baseUrl}/api/agents/test-agent/stream`);
396
+
397
+ const secondRequestBody = JSON.parse(secondConfig.body);
398
+ expect(secondRequestBody.messages).toHaveLength(2);
399
+ expect(secondRequestBody.messages[0].content).toBe('test');
400
+ expect(secondRequestBody.messages[1].content).toBe('test response');
401
+ expect(secondRequestBody.messages[1].parts).toEqual([
402
+ {
403
+ type: 'text',
404
+ text: 'test response',
405
+ },
406
+ {
407
+ type: 'tool-invocation',
408
+ toolInvocation: {
409
+ state: 'result',
410
+ step: 0,
411
+ toolCallId: 'tool1',
412
+ toolName: 'testTool',
413
+ args: {
414
+ arg1: 'value1',
415
+ },
416
+ result: 'test result',
417
+ },
418
+ },
419
+ ]);
420
+ });
421
+
305
422
  it('should get agent tool', async () => {
306
423
  const mockResponse = {
307
424
  id: 'tool1',
@@ -582,6 +699,48 @@ describe('MastraClient Resources', () => {
582
699
  }),
583
700
  );
584
701
  });
702
+
703
+ it('should get paginated thread messages', async () => {
704
+ const mockResponse = {
705
+ messages: [
706
+ {
707
+ id: '1',
708
+ content: 'test message',
709
+ threadId,
710
+ role: 'user',
711
+ type: 'text',
712
+ resourceId: 'test-resource',
713
+ createdAt: new Date(),
714
+ },
715
+ ],
716
+ total: 5,
717
+ page: 1,
718
+ perPage: 2,
719
+ hasMore: true,
720
+ };
721
+ mockFetchResponse(mockResponse);
722
+
723
+ const selectBy = {
724
+ pagination: {
725
+ page: 1,
726
+ perPage: 2,
727
+ },
728
+ };
729
+
730
+ const result = await memoryThread.getMessagesPaginated({
731
+ resourceId: 'test-resource',
732
+ format: 'v2',
733
+ selectBy,
734
+ });
735
+
736
+ expect(result).toEqual(mockResponse);
737
+ expect(global.fetch).toHaveBeenCalledWith(
738
+ `${clientOptions.baseUrl}/api/memory/threads/${threadId}/messages/paginated?resourceId=test-resource&format=v2&selectBy=${encodeURIComponent(JSON.stringify(selectBy))}`,
739
+ expect.objectContaining({
740
+ headers: expect.objectContaining(clientOptions.headers),
741
+ }),
742
+ );
743
+ });
585
744
  });
586
745
 
587
746
  describe('Tool Resource', () => {
@@ -662,14 +821,14 @@ describe('MastraClient Resources', () => {
662
821
  };
663
822
  mockFetchResponse(mockResponse);
664
823
 
665
- const result = await workflow.startAsync({ triggerData: { test: 'test' } });
824
+ const result = await workflow.startAsync({ inputData: { test: 'test' } });
666
825
  expect(result).toEqual(mockResponse);
667
826
  expect(global.fetch).toHaveBeenCalledWith(
668
827
  `${clientOptions.baseUrl}/api/workflows/test-workflow/start-async?`,
669
828
  expect.objectContaining({
670
829
  method: 'POST',
671
830
  headers: expect.objectContaining(clientOptions.headers),
672
- body: JSON.stringify({ test: 'test' }),
831
+ body: JSON.stringify({ inputData: { test: 'test' } }),
673
832
  }),
674
833
  );
675
834
  });
@@ -711,11 +870,19 @@ describe('MastraClient Resources', () => {
711
870
  backoffMs: 100,
712
871
  maxBackoffMs: 1000,
713
872
  headers: { 'Custom-Header': 'value' },
873
+ credentials: 'same-origin',
714
874
  });
715
875
 
716
876
  (global.fetch as any)
717
877
  .mockRejectedValueOnce(new Error('Network error'))
718
878
  .mockRejectedValueOnce(new Error('Network error'))
879
+ .mockResolvedValueOnce({
880
+ ok: true,
881
+ headers: {
882
+ get: () => 'application/json',
883
+ },
884
+ json: async () => ({ success: true }),
885
+ })
719
886
  .mockResolvedValueOnce({
720
887
  ok: true,
721
888
  headers: {
@@ -733,6 +900,24 @@ describe('MastraClient Resources', () => {
733
900
  headers: expect.objectContaining({
734
901
  'Custom-Header': 'value',
735
902
  }),
903
+ credentials: 'same-origin',
904
+ }),
905
+ );
906
+
907
+ // ensure custom headers and credentials are overridable per request
908
+ const result2 = await customClient.request('/test', {
909
+ headers: { 'Custom-Header': 'new-value' },
910
+ credentials: 'include',
911
+ });
912
+ expect(result2).toEqual({ success: true });
913
+ expect(global.fetch).toHaveBeenCalledTimes(4);
914
+ expect(global.fetch).toHaveBeenCalledWith(
915
+ 'http://localhost:4111/test',
916
+ expect.objectContaining({
917
+ headers: expect.objectContaining({
918
+ 'Custom-Header': 'new-value',
919
+ }),
920
+ credentials: 'include',
736
921
  }),
737
922
  );
738
923
  });
@@ -827,4 +1012,242 @@ describe('MastraClient Resources', () => {
827
1012
  });
828
1013
  });
829
1014
  });
1015
+
1016
+ describe('Scores Methods', () => {
1017
+ describe('getScorers()', () => {
1018
+ it('should fetch all available scorers', async () => {
1019
+ const mockResponse = {
1020
+ scorers: [
1021
+ { id: 'scorer-1', name: 'Test Scorer 1', description: 'A test scorer' },
1022
+ { id: 'scorer-2', name: 'Test Scorer 2', description: 'Another test scorer' },
1023
+ ],
1024
+ };
1025
+ mockFetchResponse(mockResponse);
1026
+
1027
+ const result = await client.getScorers();
1028
+ expect(result).toEqual(mockResponse);
1029
+ expect(global.fetch).toHaveBeenCalledWith(
1030
+ `${clientOptions.baseUrl}/api/scores/scorers`,
1031
+ expect.objectContaining({
1032
+ headers: expect.objectContaining(clientOptions.headers),
1033
+ }),
1034
+ );
1035
+ });
1036
+ });
1037
+
1038
+ describe('getScoresByRunId()', () => {
1039
+ it('should fetch scores by run ID without pagination', async () => {
1040
+ const mockResponse = {
1041
+ pagination: {
1042
+ total: 10,
1043
+ page: 0,
1044
+ perPage: 10,
1045
+ hasMore: false,
1046
+ },
1047
+ scores: [
1048
+ {
1049
+ id: 'score-1',
1050
+ runId: 'run-123',
1051
+ scorer: { name: 'test-scorer' },
1052
+ result: { score: 0.8 },
1053
+ input: { messages: [] },
1054
+ output: { response: 'test' },
1055
+ source: 'LIVE',
1056
+ createdAt: new Date(),
1057
+ updatedAt: new Date(),
1058
+ },
1059
+ ],
1060
+ };
1061
+
1062
+ mockFetchResponse({
1063
+ ...mockResponse,
1064
+ scores: mockResponse.scores.map(score => ({
1065
+ ...score,
1066
+ createdAt: score.createdAt.toISOString(),
1067
+ updatedAt: score.updatedAt.toISOString(),
1068
+ })),
1069
+ });
1070
+
1071
+ const result = await client.getScoresByRunId({ runId: 'run-123' });
1072
+
1073
+ expect(result).toEqual({
1074
+ ...mockResponse,
1075
+ scores: mockResponse.scores.map(score => ({
1076
+ ...score,
1077
+ createdAt: score.createdAt.toISOString(),
1078
+ updatedAt: score.updatedAt.toISOString(),
1079
+ })),
1080
+ });
1081
+
1082
+ expect(global.fetch).toHaveBeenCalledWith(
1083
+ `${clientOptions.baseUrl}/api/scores/run/run-123`,
1084
+ expect.objectContaining({
1085
+ headers: expect.objectContaining(clientOptions.headers),
1086
+ }),
1087
+ );
1088
+ });
1089
+
1090
+ it('should fetch scores by run ID with pagination', async () => {
1091
+ const mockResponse = {
1092
+ pagination: {
1093
+ total: 20,
1094
+ page: 1,
1095
+ perPage: 5,
1096
+ hasMore: true,
1097
+ },
1098
+ scores: [],
1099
+ };
1100
+ mockFetchResponse(mockResponse);
1101
+
1102
+ const result = await client.getScoresByRunId({
1103
+ runId: 'run-123',
1104
+ page: 1,
1105
+ perPage: 5,
1106
+ });
1107
+ expect(result).toEqual(mockResponse);
1108
+ expect(global.fetch).toHaveBeenCalledWith(
1109
+ `${clientOptions.baseUrl}/api/scores/run/run-123?page=1&perPage=5`,
1110
+ expect.objectContaining({
1111
+ headers: expect.objectContaining(clientOptions.headers),
1112
+ }),
1113
+ );
1114
+ });
1115
+ });
1116
+
1117
+ describe('getScoresByEntityId()', () => {
1118
+ it('should fetch scores by entity ID and type without pagination', async () => {
1119
+ const mockResponse = {
1120
+ pagination: {
1121
+ total: 5,
1122
+ page: 0,
1123
+ perPage: 10,
1124
+ hasMore: false,
1125
+ },
1126
+ scores: [
1127
+ {
1128
+ id: 'score-1',
1129
+ runId: 'run-123',
1130
+ entityId: 'agent-456',
1131
+ entityType: 'AGENT',
1132
+ scorer: { name: 'test-scorer' },
1133
+ result: { score: 0.9 },
1134
+ input: { messages: [] },
1135
+ output: { response: 'test' },
1136
+ source: 'LIVE',
1137
+ createdAt: new Date(),
1138
+ updatedAt: new Date(),
1139
+ },
1140
+ ],
1141
+ };
1142
+
1143
+ const mockResponseWithDates = mockResponse.scores.map(score => ({
1144
+ ...score,
1145
+ createdAt: score.createdAt.toISOString(),
1146
+ updatedAt: score.updatedAt.toISOString(),
1147
+ }));
1148
+
1149
+ mockFetchResponse({
1150
+ ...mockResponse,
1151
+ scores: mockResponseWithDates,
1152
+ });
1153
+
1154
+ const result = await client.getScoresByEntityId({
1155
+ entityId: 'agent-456',
1156
+ entityType: 'AGENT',
1157
+ });
1158
+
1159
+ expect(result).toEqual({
1160
+ ...mockResponse,
1161
+ scores: mockResponseWithDates,
1162
+ });
1163
+
1164
+ expect(global.fetch).toHaveBeenCalledWith(
1165
+ `${clientOptions.baseUrl}/api/scores/entity/AGENT/agent-456`,
1166
+ expect.objectContaining({
1167
+ headers: expect.objectContaining(clientOptions.headers),
1168
+ }),
1169
+ );
1170
+ });
1171
+
1172
+ it('should fetch scores by entity ID and type with pagination', async () => {
1173
+ const mockResponse = {
1174
+ pagination: {
1175
+ total: 15,
1176
+ page: 2,
1177
+ perPage: 5,
1178
+ hasMore: true,
1179
+ },
1180
+ scores: [],
1181
+ };
1182
+ mockFetchResponse(mockResponse);
1183
+
1184
+ const result = await client.getScoresByEntityId({
1185
+ entityId: 'workflow-789',
1186
+ entityType: 'WORKFLOW',
1187
+ page: 2,
1188
+ perPage: 5,
1189
+ });
1190
+ expect(result).toEqual(mockResponse);
1191
+ expect(global.fetch).toHaveBeenCalledWith(
1192
+ `${clientOptions.baseUrl}/api/scores/entity/WORKFLOW/workflow-789?page=2&perPage=5`,
1193
+ expect.objectContaining({
1194
+ body: undefined,
1195
+ headers: expect.objectContaining(clientOptions.headers),
1196
+ signal: undefined,
1197
+ }),
1198
+ );
1199
+ });
1200
+ });
1201
+
1202
+ describe('saveScore()', () => {
1203
+ it('should save a score', async () => {
1204
+ const scoreData = {
1205
+ id: 'score-1',
1206
+ scorerId: 'test-scorer',
1207
+ runId: 'run-123',
1208
+ scorer: { name: 'test-scorer' },
1209
+ score: 0.85,
1210
+ input: [],
1211
+ output: { response: 'test response' },
1212
+ source: 'LIVE' as ScoringSource,
1213
+ entityId: 'agent-456',
1214
+ entityType: 'AGENT' as ScoringEntityType,
1215
+ entity: { id: 'agent-456', name: 'test-agent' },
1216
+ createdAt: new Date(),
1217
+ updatedAt: new Date(),
1218
+ runtimeContext: {
1219
+ model: {
1220
+ name: 'test-model',
1221
+ version: '1.0.0',
1222
+ },
1223
+ },
1224
+ };
1225
+ const mockResponse = {
1226
+ score: {
1227
+ ...scoreData,
1228
+ createdAt: scoreData.createdAt.toISOString(),
1229
+ updatedAt: scoreData.updatedAt.toISOString(),
1230
+ },
1231
+ };
1232
+ mockFetchResponse(mockResponse);
1233
+
1234
+ const result = await client.saveScore({ score: scoreData });
1235
+ expect(result).toEqual({
1236
+ score: {
1237
+ ...scoreData,
1238
+ createdAt: scoreData.createdAt.toISOString(),
1239
+ updatedAt: scoreData.updatedAt.toISOString(),
1240
+ },
1241
+ });
1242
+ expect(global.fetch).toHaveBeenCalledWith(
1243
+ `${clientOptions.baseUrl}/api/scores`,
1244
+ expect.objectContaining({
1245
+ method: 'POST',
1246
+ headers: expect.objectContaining(clientOptions.headers),
1247
+ body: JSON.stringify({ score: scoreData }),
1248
+ }),
1249
+ );
1250
+ });
1251
+ });
1252
+ });
830
1253
  });
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './client';
2
2
  export * from './types';
3
+ export type { UIMessageWithMetadata } from '@mastra/core/agent';
@@ -1,4 +1,12 @@
1
- import type { TaskSendParams, TaskQueryParams, TaskIdParams, Task, AgentCard, JSONRPCResponse } from '@mastra/core/a2a';
1
+ import type {
2
+ AgentCard,
3
+ GetTaskResponse,
4
+ MessageSendParams,
5
+ SendMessageResponse,
6
+ SendStreamingMessageResponse,
7
+ Task,
8
+ TaskQueryParams,
9
+ } from '@mastra/core/a2a';
2
10
  import type { ClientOptions } from '../types';
3
11
  import { BaseResource } from './base';
4
12
 
@@ -18,71 +26,73 @@ export class A2A extends BaseResource {
18
26
  * @returns Promise containing the agent card information
19
27
  */
20
28
  async getCard(): Promise<AgentCard> {
21
- return this.request(`/.well-known/${this.agentId}/agent.json`);
29
+ return this.request(`/.well-known/${this.agentId}/agent-card.json`);
22
30
  }
23
31
 
24
32
  /**
25
- * Send a message to the agent and get a response
33
+ * Send a message to the agent and gets a message or task response
26
34
  * @param params - Parameters for the task
27
- * @returns Promise containing the task response
35
+ * @returns Promise containing the response
28
36
  */
29
- async sendMessage(params: TaskSendParams): Promise<{ task: Task }> {
30
- const response = await this.request<JSONRPCResponse<Task>>(`/a2a/${this.agentId}`, {
37
+ async sendMessage(params: MessageSendParams): Promise<SendMessageResponse> {
38
+ const response = await this.request<SendMessageResponse>(`/a2a/${this.agentId}`, {
31
39
  method: 'POST',
32
40
  body: {
33
- method: 'tasks/send',
41
+ method: 'message/send',
34
42
  params,
35
43
  },
36
44
  });
37
45
 
38
- return { task: response.result! };
46
+ return response;
39
47
  }
40
48
 
41
49
  /**
42
- * Get the status and result of a task
43
- * @param params - Parameters for querying the task
44
- * @returns Promise containing the task response
50
+ * Sends a message to an agent to initiate/continue a task and subscribes
51
+ * the client to real-time updates for that task via Server-Sent Events (SSE).
52
+ * @param params - Parameters for the task
53
+ * @returns A stream of Server-Sent Events. Each SSE `data` field contains a `SendStreamingMessageResponse`
45
54
  */
46
- async getTask(params: TaskQueryParams): Promise<Task> {
47
- const response = await this.request<JSONRPCResponse<Task>>(`/a2a/${this.agentId}`, {
55
+ async sendStreamingMessage(params: MessageSendParams): Promise<AsyncIterable<SendStreamingMessageResponse>> {
56
+ const response = await this.request<AsyncIterable<SendStreamingMessageResponse>>(`/a2a/${this.agentId}`, {
48
57
  method: 'POST',
49
58
  body: {
50
- method: 'tasks/get',
59
+ method: 'message/stream',
51
60
  params,
52
61
  },
53
62
  });
54
63
 
55
- return response.result!;
64
+ return response;
56
65
  }
57
66
 
58
67
  /**
59
- * Cancel a running task
60
- * @param params - Parameters identifying the task to cancel
68
+ * Get the status and result of a task
69
+ * @param params - Parameters for querying the task
61
70
  * @returns Promise containing the task response
62
71
  */
63
- async cancelTask(params: TaskIdParams): Promise<{ task: Task }> {
64
- return this.request(`/a2a/${this.agentId}`, {
72
+ async getTask(params: TaskQueryParams): Promise<GetTaskResponse> {
73
+ const response = await this.request<GetTaskResponse>(`/a2a/${this.agentId}`, {
65
74
  method: 'POST',
66
75
  body: {
67
- method: 'tasks/cancel',
76
+ method: 'tasks/get',
68
77
  params,
69
78
  },
70
79
  });
80
+
81
+ return response;
71
82
  }
72
83
 
73
84
  /**
74
- * Send a message and subscribe to streaming updates (not fully implemented)
75
- * @param params - Parameters for the task
85
+ * Cancel a running task
86
+ * @param params - Parameters identifying the task to cancel
76
87
  * @returns Promise containing the task response
77
88
  */
78
- async sendAndSubscribe(params: TaskSendParams): Promise<Response> {
89
+ async cancelTask(params: TaskQueryParams): Promise<Task> {
79
90
  return this.request(`/a2a/${this.agentId}`, {
80
91
  method: 'POST',
81
92
  body: {
82
- method: 'tasks/sendSubscribe',
93
+ method: 'tasks/cancel',
83
94
  params,
84
95
  },
85
- stream: true,
86
96
  });
87
97
  }
88
98
  }