-
Notifications
You must be signed in to change notification settings - Fork 615
Expand file tree
/
Copy patha2a_agent_db.py
More file actions
2040 lines (1725 loc) · 67.4 KB
/
a2a_agent_db.py
File metadata and controls
2040 lines (1725 loc) · 67.4 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
"""
Database operations for A2A agent management.
Includes external agent discovery, server agent registration, and task management.
"""
import json
import logging
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional
from uuid import uuid4
from database.db_models import (
A2AExternalAgent,
A2AExternalAgentRelation,
A2ANacosConfig,
A2AServerAgent,
A2ATask,
A2AMessage,
A2AArtifact,
)
# Import session factory - kept at function level to avoid triggering module-level import
# of db_models.client, which would cause circular dependency at import time.
def _get_db_session():
from database.client import get_db_session as _gds
return _gds()
logger = logging.getLogger("a2a_agent_db")
# Default cache TTL in seconds (24 hours)
DEFAULT_CACHE_TTL_HOURS = 24
def _extract_base_url(url: str) -> str:
"""Extract base URL (scheme + host + port) from a full URL.
Args:
url: Full URL, e.g., http://example.com/path/to/agent.json
Returns:
Base URL, e.g., http://example.com
"""
from urllib.parse import urlparse
parsed = urlparse(url)
if parsed.port:
return f"{parsed.scheme}://{parsed.hostname}:{parsed.port}"
return f"{parsed.scheme}://{parsed.hostname}"
# Standard human-readable protocol label
PROTOCOL_HTTP_JSON = "HTTP+JSON"
PROTOCOL_JSONRPC = "JSONRPC"
PROTOCOL_GRPC = "GRPC"
def _generate_task_id() -> str:
"""Generate a unique task ID."""
return f"task_{uuid4().hex}"
def _generate_message_id() -> str:
"""Generate a unique message ID."""
return f"msg_{uuid4().hex}"
def _generate_endpoint_id(agent_id: int) -> str:
"""Generate a unique endpoint ID for A2A Server agents."""
return f"a2a_{agent_id}_{uuid4().hex[:8]}"
def _extract_primary_interface(supported_interfaces: List[Dict[str, Any]]) -> tuple[str, str]:
"""Extract the primary interface (first one) from supported interfaces.
Args:
supported_interfaces: List of interface objects with protocolBinding, url, protocolVersion.
Returns:
Tuple of (agent_url, protocol_version).
Returns empty string for url if no interfaces found.
"""
if not supported_interfaces:
return "", "1.0"
# Return the first interface to ensure URL and protocol are from the same interface
first = supported_interfaces[0]
return (
first.get("url", ""),
first.get("protocolVersion", "1.0")
)
def _get_interface_by_protocol(
supported_interfaces: Optional[List[Dict[str, Any]]],
protocol_binding: str
) -> Optional[Dict[str, Any]]:
"""Get a specific interface by protocol binding.
Args:
supported_interfaces: List of interface objects.
protocol_binding: Protocol binding to find (e.g., 'http-json-rpc', 'rest', 'grpc').
Returns:
Interface dict or None if not found.
"""
if not supported_interfaces:
return None
for iface in supported_interfaces:
if iface.get("protocolBinding") == protocol_binding:
return iface
return None
# =============================================================================
# External Agent Operations (Client Role)
# =============================================================================
def _extract_protocol_type(supported_interfaces: Optional[List[Dict[str, Any]]]) -> str:
"""Extract protocol type from supportedInterfaces.
Args:
supported_interfaces: List of interface objects.
Returns:
Protocol type: JSONRPC, HTTP+JSON, or GRPC.
Defaults to JSONRPC if not found.
"""
if not supported_interfaces:
return PROTOCOL_JSONRPC
# Map protocol bindings to standard values
protocol_map = {
"http-json-rpc": PROTOCOL_JSONRPC,
"jsonrpc": PROTOCOL_JSONRPC,
"httpjsonrpc": PROTOCOL_JSONRPC,
"http+json": PROTOCOL_HTTP_JSON,
"httprest": PROTOCOL_HTTP_JSON,
"rest": PROTOCOL_HTTP_JSON,
"grpc": PROTOCOL_GRPC,
}
for iface in supported_interfaces:
protocol_binding = iface.get("protocolBinding", "").lower()
return protocol_map.get(protocol_binding, PROTOCOL_JSONRPC)
return PROTOCOL_JSONRPC
def create_external_agent_from_url(
source_url: str,
name: str,
description: Optional[str],
agent_url: str,
tenant_id: str,
user_id: str,
raw_card: Optional[Dict[str, Any]] = None,
version: Optional[str] = None,
streaming: bool = False,
supported_interfaces: Optional[List[Dict[str, Any]]] = None,
base_url: Optional[str] = None,
) -> Dict[str, Any]:
"""Create or update an external A2A agent discovered from URL.
Args:
source_url: Direct URL to the agent card (used as unique identifier).
name: Agent name.
description: Agent description.
agent_url: A2A endpoint URL for calling this agent (http-json-rpc by default).
tenant_id: Tenant ID for isolation.
user_id: User who discovered this agent.
raw_card: Full original Agent Card JSON.
version: Agent version from Agent Card.
streaming: Whether this agent supports SSE streaming.
supported_interfaces: All supported protocol interfaces.
base_url: Base URL for health checks (service root address).
Returns:
Created agent information dict.
"""
now = datetime.now(timezone.utc)
expires_at = now + timedelta(hours=DEFAULT_CACHE_TTL_HOURS)
protocol_type = _extract_protocol_type(supported_interfaces)
# Extract base_url from source_url if not provided
if not base_url and source_url:
base_url = _extract_base_url(source_url)
with _get_db_session() as session:
# Check if agent already exists by source_url
existing = session.query(A2AExternalAgent).filter(
A2AExternalAgent.source_url == source_url,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if existing:
# Update existing record
existing.name = name
existing.description = description
existing.version = version
existing.agent_url = agent_url
existing.protocol_type = protocol_type
existing.streaming = streaming
existing.supported_interfaces = supported_interfaces
existing.raw_card = raw_card
existing.cached_at = now
existing.cache_expires_at = expires_at
existing.updated_by = user_id
if base_url:
existing.base_url = base_url
agent = existing
else:
# Create new record
agent = A2AExternalAgent(
name=name,
description=description,
version=version,
agent_url=agent_url,
protocol_type=protocol_type,
streaming=streaming,
supported_interfaces=supported_interfaces,
source_type="url",
source_url=source_url,
tenant_id=tenant_id,
created_by=user_id,
updated_by=user_id,
raw_card=raw_card,
cached_at=now,
cache_expires_at=expires_at,
base_url=base_url,
delete_flag='N'
)
session.add(agent)
session.flush()
return {
"id": agent.id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"protocol_type": agent.protocol_type,
"streaming": agent.streaming,
"supported_interfaces": agent.supported_interfaces,
"source_type": agent.source_type,
"base_url": agent.base_url,
"is_available": agent.is_available,
"cached_at": agent.cached_at.isoformat() if agent.cached_at else None,
"cache_expires_at": agent.cache_expires_at.isoformat() if agent.cache_expires_at else None,
}
def create_external_agent_from_nacos(
name: str,
description: Optional[str],
agent_url: str,
nacos_config_id: str,
nacos_agent_name: str,
tenant_id: str,
user_id: str,
raw_card: Optional[Dict[str, Any]] = None,
version: Optional[str] = None,
streaming: bool = False,
supported_interfaces: Optional[List[Dict[str, Any]]] = None,
base_url: Optional[str] = None,
) -> Dict[str, Any]:
"""Create or update an external A2A agent discovered from Nacos.
Args:
name: Agent name.
description: Agent description.
agent_url: A2A endpoint URL for calling this agent (http-json-rpc by default).
nacos_config_id: Nacos config ID used for discovery.
nacos_agent_name: Original name used for Nacos query.
tenant_id: Tenant ID for isolation.
user_id: User who discovered this agent.
raw_card: Full original Agent Card JSON.
version: Agent version from Agent Card.
streaming: Whether this agent supports SSE streaming.
supported_interfaces: All supported protocol interfaces.
base_url: Base URL for health checks (service root address).
Returns:
Created agent information dict.
"""
now = datetime.now(timezone.utc)
expires_at = now + timedelta(hours=DEFAULT_CACHE_TTL_HOURS)
protocol_type = _extract_protocol_type(supported_interfaces)
# Extract base_url from agent_url if not provided
if not base_url and agent_url:
base_url = _extract_base_url(agent_url)
with _get_db_session() as session:
# Check if agent already exists by nacos_config_id + nacos_agent_name
existing = session.query(A2AExternalAgent).filter(
A2AExternalAgent.nacos_config_id == nacos_config_id,
A2AExternalAgent.nacos_agent_name == nacos_agent_name,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if existing:
existing.name = name
existing.description = description
existing.version = version
existing.agent_url = agent_url
existing.protocol_type = protocol_type
existing.streaming = streaming
existing.supported_interfaces = supported_interfaces
existing.raw_card = raw_card
existing.cached_at = now
existing.cache_expires_at = expires_at
existing.updated_by = user_id
if base_url:
existing.base_url = base_url
agent = existing
else:
agent = A2AExternalAgent(
name=name,
description=description,
version=version,
agent_url=agent_url,
protocol_type=protocol_type,
streaming=streaming,
supported_interfaces=supported_interfaces,
source_type="nacos",
nacos_config_id=nacos_config_id,
nacos_agent_name=nacos_agent_name,
tenant_id=tenant_id,
created_by=user_id,
updated_by=user_id,
raw_card=raw_card,
cached_at=now,
cache_expires_at=expires_at,
base_url=base_url,
delete_flag='N'
)
session.add(agent)
session.flush()
return {
"id": agent.id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"protocol_type": agent.protocol_type,
"streaming": agent.streaming,
"supported_interfaces": agent.supported_interfaces,
"source_type": agent.source_type,
"base_url": agent.base_url,
"is_available": agent.is_available,
"cached_at": agent.cached_at.isoformat() if agent.cached_at else None,
"cache_expires_at": agent.cache_expires_at.isoformat() if agent.cache_expires_at else None,
}
def get_external_agent_by_id(external_agent_id: int, tenant_id: str) -> Optional[Dict[str, Any]]:
"""Get an external agent by its id.
Args:
external_agent_id: The external agent database ID.
tenant_id: Tenant ID for isolation.
Returns:
Agent information dict or None if not found.
"""
with _get_db_session() as session:
agent = session.query(A2AExternalAgent).filter(
A2AExternalAgent.id == external_agent_id,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if not agent:
return None
return {
"id": agent.id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"streaming": agent.streaming,
"protocol_type": agent.protocol_type,
"supported_interfaces": agent.supported_interfaces,
"source_type": agent.source_type,
"source_url": agent.source_url,
"base_url": agent.base_url,
"nacos_config_id": agent.nacos_config_id,
"nacos_agent_name": agent.nacos_agent_name,
"raw_card": agent.raw_card,
"is_available": agent.is_available,
"last_check_at": agent.last_check_at.isoformat() if agent.last_check_at else None,
"last_check_result": agent.last_check_result,
"cached_at": agent.cached_at.isoformat() if agent.cached_at else None,
"cache_expires_at": agent.cache_expires_at.isoformat() if agent.cache_expires_at else None,
"create_time": agent.create_time.isoformat() if agent.create_time else None,
}
def list_external_agents(
tenant_id: str,
source_type: Optional[str] = None,
is_available: Optional[bool] = None,
limit: int = 50,
offset: int = 0
) -> List[Dict[str, Any]]:
"""List all external agents for a tenant.
Args:
tenant_id: Tenant ID for isolation.
source_type: Filter by source type (url or nacos).
is_available: Filter by availability status.
limit: Maximum number of results.
offset: Number of results to skip.
Returns:
List of agent information dicts.
"""
with _get_db_session() as session:
query = session.query(A2AExternalAgent).filter(
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
)
if source_type:
query = query.filter(A2AExternalAgent.source_type == source_type)
if is_available is not None:
query = query.filter(A2AExternalAgent.is_available == is_available)
agents = query.order_by(A2AExternalAgent.create_time.desc()).offset(offset).limit(limit).all()
return [
{
"id": agent.id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"streaming": agent.streaming,
"protocol_type": agent.protocol_type,
"supported_interfaces": agent.supported_interfaces,
"source_type": agent.source_type,
"source_url": agent.source_url,
"base_url": agent.base_url,
"is_available": agent.is_available,
"last_check_result": agent.last_check_result,
"create_time": agent.create_time.isoformat() if agent.create_time else None,
}
for agent in agents
]
def delete_external_agent(external_agent_id: int, tenant_id: str) -> bool:
"""Soft delete an external agent.
Args:
external_agent_id: The external agent database ID.
tenant_id: Tenant ID for isolation.
Returns:
True if deleted, False if not found.
"""
with _get_db_session() as session:
agent = session.query(A2AExternalAgent).filter(
A2AExternalAgent.id == external_agent_id,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if not agent:
return False
agent.delete_flag = 'Y'
return True
def _get_protocol_binding_mapping() -> Dict[str, List[str]]:
"""Get mapping of protocol type to protocol bindings.
Returns:
Dict mapping protocol type to list of possible bindings.
"""
return {
PROTOCOL_JSONRPC: ["http-json-rpc", "jsonrpc", "httpjsonrpc"],
PROTOCOL_HTTP_JSON: ["httprest", "rest", "http+json"],
PROTOCOL_GRPC: ["grpc"],
}
def _find_interface_by_protocol_type(
supported_interfaces: Optional[List[Dict[str, Any]]],
protocol_type: str
) -> Optional[Dict[str, Any]]:
"""Find an interface by protocol type.
Args:
supported_interfaces: List of interface objects.
protocol_type: Protocol type (JSONRPC, HTTP+JSON, or GRPC).
Returns:
Interface dict or None if not found.
"""
if not supported_interfaces:
return None
binding_mapping = _get_protocol_binding_mapping()
target_bindings = binding_mapping.get(protocol_type, [])
for iface in supported_interfaces:
binding = iface.get("protocolBinding", "").lower()
if binding in target_bindings:
return iface
return None
def update_external_agent_protocol(
external_agent_id: int,
tenant_id: str,
protocol_type: str,
) -> Optional[Dict[str, Any]]:
"""Update the protocol type for an external agent.
Args:
external_agent_id: The external agent database ID.
tenant_id: Tenant ID for isolation.
protocol_type: New protocol type (JSONRPC, HTTP+JSON, or GRPC).
Returns:
Updated agent information dict or None if not found.
"""
valid_protocols = [PROTOCOL_JSONRPC, PROTOCOL_HTTP_JSON, PROTOCOL_GRPC]
if protocol_type not in valid_protocols:
raise ValueError(f"Invalid protocol type: {protocol_type}. Must be one of {valid_protocols}")
with _get_db_session() as session:
agent = session.query(A2AExternalAgent).filter(
A2AExternalAgent.id == external_agent_id,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if not agent:
return None
agent.protocol_type = protocol_type
# Update agent_url based on the selected protocol
interface = _find_interface_by_protocol_type(
agent.supported_interfaces,
protocol_type
)
if interface:
agent.agent_url = interface.get("url", agent.agent_url)
agent.updated_time = datetime.now(timezone.utc)
return {
"id": agent.id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"protocol_type": agent.protocol_type,
"streaming": agent.streaming,
"supported_interfaces": agent.supported_interfaces,
"source_type": agent.source_type,
"source_url": agent.source_url,
"nacos_config_id": agent.nacos_config_id,
"nacos_agent_name": agent.nacos_agent_name,
"raw_card": agent.raw_card,
"is_available": agent.is_available,
"last_check_at": agent.last_check_at.isoformat() if agent.last_check_at else None,
"last_check_result": agent.last_check_result,
"cached_at": agent.cached_at.isoformat() if agent.cached_at else None,
"cache_expires_at": agent.cache_expires_at.isoformat() if agent.cache_expires_at else None,
"create_time": agent.create_time.isoformat() if agent.create_time else None,
"update_time": agent.update_time.isoformat() if agent.update_time else None,
}
def refresh_external_agent_cache(
external_agent_id: int,
tenant_id: str,
user_id: str,
new_raw_card: Optional[Dict[str, Any]] = None,
new_agent_url: Optional[str] = None,
new_name: Optional[str] = None,
new_description: Optional[str] = None,
new_version: Optional[str] = None,
new_streaming: Optional[bool] = None,
new_supported_interfaces: Optional[List[Dict[str, Any]]] = None,
new_protocol_type: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Refresh the cache for an external agent.
Args:
external_agent_id: The external agent database ID.
tenant_id: Tenant ID for isolation.
user_id: User who requested the refresh.
new_raw_card: Updated Agent Card JSON (if fetched).
new_agent_url: Updated A2A endpoint URL.
new_name: Updated agent name.
new_description: Updated agent description.
new_version: Updated agent version.
new_streaming: Updated streaming capability.
new_supported_interfaces: Updated supported interfaces.
new_protocol_type: Updated protocol type (JSONRPC, HTTP+JSON, or GRPC).
Returns:
Updated agent information dict or None if not found.
"""
now = datetime.now(timezone.utc)
expires_at = now + timedelta(hours=DEFAULT_CACHE_TTL_HOURS)
with _get_db_session() as session:
agent = session.query(A2AExternalAgent).filter(
A2AExternalAgent.id == external_agent_id,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if not agent:
return None
if new_raw_card is not None:
agent.raw_card = new_raw_card
if new_agent_url is not None:
agent.agent_url = new_agent_url
if new_name is not None:
agent.name = new_name
if new_description is not None:
agent.description = new_description
if new_version is not None:
agent.version = new_version
if new_streaming is not None:
agent.streaming = new_streaming
if new_supported_interfaces is not None:
agent.supported_interfaces = new_supported_interfaces
if new_protocol_type is not None:
agent.protocol_type = new_protocol_type
# Update agent_url based on the selected protocol type
interface = _find_interface_by_protocol_type(
agent.supported_interfaces,
new_protocol_type
)
if interface:
agent.agent_url = interface.get("url", agent.agent_url)
agent.cached_at = now
agent.cache_expires_at = expires_at
agent.updated_by = user_id
agent.last_check_at = now
session.flush()
return {
"id": agent.id,
"name": agent.name,
"agent_url": agent.agent_url,
"version": agent.version,
"streaming": agent.streaming,
"supported_interfaces": agent.supported_interfaces,
"cached_at": agent.cached_at.isoformat() if agent.cached_at else None,
"cache_expires_at": agent.cache_expires_at.isoformat() if agent.cache_expires_at else None,
}
def update_agent_availability(
external_agent_id: int,
tenant_id: str,
is_available: bool,
check_result: Optional[str] = None
) -> bool:
"""Update the availability status of an external agent.
Args:
external_agent_id: The external agent database ID.
tenant_id: Tenant ID for isolation.
is_available: New availability status.
check_result: Health check result (OK, ERROR, TIMEOUT).
Returns:
True if updated, False if not found.
"""
with _get_db_session() as session:
agent = session.query(A2AExternalAgent).filter(
A2AExternalAgent.id == external_agent_id,
A2AExternalAgent.tenant_id == tenant_id,
A2AExternalAgent.delete_flag != 'Y'
).first()
if not agent:
return False
agent.is_available = is_available
agent.last_check_at = datetime.now(timezone.utc)
if check_result:
agent.last_check_result = check_result
return True
# =============================================================================
# External Agent Relation Operations (Sub-agent)
# =============================================================================
def add_external_agent_relation(
local_agent_id: int,
external_agent_id: int,
tenant_id: str,
user_id: str
) -> Dict[str, Any]:
"""Add a relation between a local agent and an external A2A agent.
Args:
local_agent_id: Local parent agent ID.
external_agent_id: External A2A agent database ID.
tenant_id: Tenant ID for isolation.
user_id: User who created the relation.
Returns:
Created relation information dict.
Raises:
ValueError: If relation already exists.
"""
with _get_db_session() as session:
# Check if relation already exists (not soft-deleted)
existing = session.query(A2AExternalAgentRelation).filter(
A2AExternalAgentRelation.local_agent_id == local_agent_id,
A2AExternalAgentRelation.external_agent_id == external_agent_id,
A2AExternalAgentRelation.tenant_id == tenant_id,
A2AExternalAgentRelation.delete_flag != 'Y'
).first()
if existing:
raise ValueError("Relation already exists")
# Check if there's a soft-deleted record and restore it
deleted_record = session.query(A2AExternalAgentRelation).filter(
A2AExternalAgentRelation.local_agent_id == local_agent_id,
A2AExternalAgentRelation.external_agent_id == external_agent_id,
A2AExternalAgentRelation.tenant_id == tenant_id,
A2AExternalAgentRelation.delete_flag == 'Y'
).first()
if deleted_record:
# Restore the soft-deleted record
deleted_record.delete_flag = 'N'
deleted_record.is_enabled = True
deleted_record.updated_by = user_id
session.flush()
return {
"id": deleted_record.id,
"local_agent_id": deleted_record.local_agent_id,
"external_agent_id": deleted_record.external_agent_id,
"is_enabled": deleted_record.is_enabled,
}
relation = A2AExternalAgentRelation(
local_agent_id=local_agent_id,
external_agent_id=external_agent_id,
tenant_id=tenant_id,
created_by=user_id,
delete_flag='N'
)
session.add(relation)
session.flush()
return {
"id": relation.id,
"local_agent_id": relation.local_agent_id,
"external_agent_id": relation.external_agent_id,
"is_enabled": relation.is_enabled,
}
def remove_external_agent_relation(
local_agent_id: int,
external_agent_id: int,
tenant_id: str
) -> bool:
"""Remove a relation between a local agent and an external A2A agent.
Args:
local_agent_id: Local parent agent ID.
external_agent_id: External A2A agent database ID.
tenant_id: Tenant ID for isolation.
Returns:
True if removed, False if not found.
"""
with _get_db_session() as session:
relation = session.query(A2AExternalAgentRelation).filter(
A2AExternalAgentRelation.local_agent_id == local_agent_id,
A2AExternalAgentRelation.external_agent_id == external_agent_id,
A2AExternalAgentRelation.tenant_id == tenant_id,
A2AExternalAgentRelation.delete_flag != 'Y'
).first()
if not relation:
return False
relation.delete_flag = 'Y'
return True
def query_external_sub_agents(
local_agent_id: int,
tenant_id: str,
version_no: int = 0
) -> List[Dict[str, Any]]:
"""Query external A2A agents configured as sub-agents for a local agent.
Args:
local_agent_id: Local parent agent ID.
tenant_id: Tenant ID for isolation.
version_no: Version number (currently not used, relations are global).
Returns:
List of external agent details with relation metadata.
"""
with _get_db_session() as session:
results = session.query(
A2AExternalAgentRelation,
A2AExternalAgent
).join(
A2AExternalAgent,
A2AExternalAgent.id == A2AExternalAgentRelation.external_agent_id
).filter(
A2AExternalAgentRelation.local_agent_id == local_agent_id,
A2AExternalAgentRelation.tenant_id == tenant_id,
A2AExternalAgentRelation.delete_flag != 'Y',
A2AExternalAgentRelation.is_enabled == True,
A2AExternalAgent.delete_flag != 'Y',
A2AExternalAgent.is_available == True
).all()
return [
{
"id": agent.id,
"relation_id": relation.id,
"external_agent_id": agent.id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"protocol_type": agent.protocol_type,
"streaming": agent.streaming,
"supported_interfaces": agent.supported_interfaces,
"raw_card": agent.raw_card,
"is_enabled": relation.is_enabled,
}
for relation, agent in results
]
def list_external_relations_by_local_agent(
local_agent_id: int,
tenant_id: str
) -> List[Dict[str, Any]]:
"""List all external agent relations for a local agent.
Args:
local_agent_id: Local parent agent ID.
tenant_id: Tenant ID for isolation.
Returns:
List of relation information dicts.
"""
with _get_db_session() as session:
relations = session.query(
A2AExternalAgentRelation,
A2AExternalAgent
).join(
A2AExternalAgent,
A2AExternalAgent.id == A2AExternalAgentRelation.external_agent_id,
isouter=True
).filter(
A2AExternalAgentRelation.local_agent_id == local_agent_id,
A2AExternalAgentRelation.tenant_id == tenant_id,
A2AExternalAgentRelation.delete_flag != 'Y'
).all()
return [
{
"id": relation.id,
"local_agent_id": relation.local_agent_id,
"external_agent_id": relation.external_agent_id,
"is_enabled": relation.is_enabled,
"external_agent_name": agent.name if agent else None,
"external_agent_url": agent.agent_url if agent else None,
"protocol_type": agent.protocol_type if agent else None,
"create_time": relation.create_time.isoformat() if relation.create_time else None,
}
for relation, agent in relations
]
# =============================================================================
# A2A Server Agent Operations
# =============================================================================
def _make_default_interfaces(endpoint_id: str) -> List[Dict[str, Any]]:
"""Build default supportedInterfaces with correct A2A 1.0 format."""
return [
{"protocolBinding": PROTOCOL_JSONRPC, "url": f"/nb/a2a/{endpoint_id}/v1", "protocolVersion": "1.0"},
{"protocolBinding": PROTOCOL_HTTP_JSON, "url": f"/nb/a2a/{endpoint_id}", "protocolVersion": "1.0"},
]
def _apply_server_agent_fields(
agent,
name: Optional[str],
description: Optional[str],
version: Optional[str],
agent_url: Optional[str],
streaming: bool,
supported_interfaces: Optional[List[Dict[str, Any]]],
card_overrides: Optional[Dict[str, Any]],
) -> None:
"""Apply optional fields to an existing A2AServerAgent instance."""
if name is not None:
agent.name = name
if description is not None:
agent.description = description
if version is not None:
agent.version = version
if agent_url is not None:
agent.agent_url = agent_url
agent.streaming = streaming
if supported_interfaces is not None:
agent.supported_interfaces = supported_interfaces
if card_overrides is not None:
agent.card_overrides = card_overrides
def _serialize_server_agent(
agent,
include_unpublished: bool = False,
include_user_info: bool = False,
) -> Dict[str, Any]:
"""Serialize an A2AServerAgent model to dict."""
result = {
"id": agent.id,
"agent_id": agent.agent_id,
"endpoint_id": agent.endpoint_id,
"name": agent.name,
"description": agent.description,
"version": agent.version,
"agent_url": agent.agent_url,
"streaming": agent.streaming,
"supported_interfaces": agent.supported_interfaces,
"card_overrides": agent.card_overrides,
"is_enabled": agent.is_enabled,
"published_at": agent.published_at.isoformat() if agent.published_at else None,
}
if include_unpublished:
result["unpublished_at"] = agent.unpublished_at.isoformat() if agent.unpublished_at else None
if include_user_info:
result["user_id"] = agent.user_id
result["tenant_id"] = agent.tenant_id
return result
def create_server_agent(
agent_id: int,
user_id: str,
tenant_id: str,
name: str,
description: Optional[str] = None,
version: Optional[str] = None,
agent_url: Optional[str] = None,
streaming: bool = False,
supported_interfaces: Optional[List[Dict[str, Any]]] = None,
card_overrides: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create or update an A2A Server agent registration.
Args:
agent_id: Local agent ID.
user_id: Owner user ID.
tenant_id: Tenant ID.
name: Agent name exposed in Agent Card.
description: Agent description exposed in Agent Card.
version: Agent version exposed in Agent Card.
agent_url: Primary A2A endpoint URL.
streaming: Whether this agent supports SSE streaming.
supported_interfaces: All supported interfaces array. If None, will be auto-generated.
card_overrides: Optional Agent Card customizations.
Returns:
Created server agent information dict.
"""