-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.xml
2245 lines (1878 loc) · 77 KB
/
code.xml
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
This file is a merged representation of a subset of the codebase, containing specifically included files, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Only files matching these patterns are included: src/**/*, scripts/**/*, configs/**/*
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
<additional_info>
</additional_info>
</file_summary>
<directory_structure>
configs/
agent1.json
agent2.json
coordinator.json
scripts/
demo.py
src/
koi_mcp/
koi/
handlers/
personality_handlers.py
node/
agent.py
coordinator.py
personality/
models/
profile.py
trait.py
rid.py
server/
adapter/
mcp_adapter.py
agent/
agent_server.py
registry/
registry_server.py
utils/
async/
retry.py
logging/
setup.py
config.py
main.py
code.txt
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path="configs/agent1.json">
{
"agent": {
"name": "helpful-agent",
"version": "1.0",
"base_url": "http://localhost:8100/koi-net",
"mcp_port": 8101,
"traits": {
"mood": "helpful",
"style": "concise",
"interests": ["ai", "knowledge-graphs"],
"calculate": {
"description": "Performs simple calculations",
"is_callable": true
}
}
},
"network": {
"first_contact": "http://localhost:9000/koi-net"
}
}
</file>
<file path="configs/agent2.json">
{
"agent": {
"name": "creative-agent",
"version": "1.0",
"base_url": "http://localhost:8200/koi-net",
"mcp_port": 8102,
"traits": {
"mood": "creative",
"style": "elaborate",
"interests": ["storytelling", "art", "design"],
"generate_story": {
"description": "Generates a short story based on a prompt",
"is_callable": true
}
}
},
"network": {
"first_contact": "http://localhost:9000/koi-net"
}
}
</file>
<file path="configs/coordinator.json">
{
"coordinator": {
"name": "koi-mcp-coordinator",
"base_url": "http://localhost:9000/koi-net",
"mcp_registry_port": 9000
}
}
</file>
<file path="src/koi_mcp/koi/handlers/personality_handlers.py">
# Update file: koi_mcp/koi/handlers/personality_handlers.py
import logging
from typing import Optional
from pydantic import ValidationError
from rid_lib.ext.bundle import Bundle
from koi_net.processor import ProcessorInterface
from koi_net.processor.handler import HandlerType, STOP_CHAIN
from koi_net.processor.knowledge_object import KnowledgeObject, KnowledgeSource
from koi_net.protocol.event import EventType, Event
from koi_mcp.personality.rid import AgentPersonality
from koi_mcp.personality.models.profile import PersonalityProfile
logger = logging.getLogger(__name__)
def register_personality_handlers(processor: ProcessorInterface, mcp_adapter=None):
"""Register all personality-related handlers with a processor."""
@processor.register_handler(HandlerType.RID, rid_types=[AgentPersonality])
def personality_rid_handler(proc: ProcessorInterface, kobj: KnowledgeObject):
"""Validate agent personality RIDs."""
# Only block external updates to our own personality (if we have one)
if hasattr(proc, "personality_rid") and kobj.rid == proc.personality_rid and kobj.source == KnowledgeSource.External:
logger.warning(f"Blocked external update to our personality: {kobj.rid}")
return STOP_CHAIN
# For all other personality RIDs, allow processing
logger.info(f"Processing agent personality: {kobj.rid}")
# Important: Make sure normalized event type is set for external personalities
if kobj.source == KnowledgeSource.External and kobj.event_type in [EventType.NEW, EventType.UPDATE]:
prev_bundle = proc.cache.read(kobj.rid)
if prev_bundle:
kobj.normalized_event_type = EventType.UPDATE
else:
kobj.normalized_event_type = EventType.NEW
return kobj
@processor.register_handler(HandlerType.Bundle, rid_types=[AgentPersonality])
def personality_bundle_handler(proc: ProcessorInterface, kobj: KnowledgeObject):
"""Process agent personality bundles."""
try:
# Validate contents as PersonalityProfile
profile = PersonalityProfile.model_validate(kobj.contents)
# Set normalized event type based on cache status
prev_bundle = proc.cache.read(kobj.rid)
if prev_bundle:
kobj.normalized_event_type = EventType.UPDATE
logger.info(f"Updating existing agent personality: {kobj.rid}")
else:
kobj.normalized_event_type = EventType.NEW
logger.info(f"Adding new agent personality: {kobj.rid}")
# Register with MCP adapter if available
if mcp_adapter is not None:
mcp_adapter.register_agent(profile)
logger.info(f"Registered agent {profile.rid.name} with MCP adapter")
return kobj
except ValidationError as e:
logger.error(f"Invalid personality profile format: {kobj.rid} - {e}")
return STOP_CHAIN
@processor.register_handler(HandlerType.Network, rid_types=[AgentPersonality])
def personality_network_handler(proc: ProcessorInterface, kobj: KnowledgeObject):
"""Determine which nodes to broadcast personality updates to."""
# Get all neighbors interested in AgentPersonality
subscribers = proc.network.graph.get_neighbors(
direction="out",
allowed_type=AgentPersonality
)
# Add all subscribers as network targets
kobj.network_targets.update(subscribers)
# If this is our personality, always broadcast
if hasattr(proc, "personality_rid") and kobj.rid == proc.personality_rid:
logger.debug("Broadcasting our own personality to all neighbors")
kobj.network_targets.update(proc.network.graph.get_neighbors())
return kobj
</file>
<file path="src/koi_mcp/koi/node/agent.py">
import logging
from typing import Dict, Any, Optional
from rid_lib.ext.bundle import Bundle
from koi_net import NodeInterface
from koi_net.protocol.node import NodeProfile, NodeType, NodeProvides
from koi_net.protocol.event import EventType, Event
from koi_mcp.personality.rid import AgentPersonality
from koi_mcp.personality.models.profile import PersonalityProfile
from koi_mcp.personality.models.trait import PersonalityTrait
from koi_mcp.server.agent.agent_server import AgentPersonalityServer
logger = logging.getLogger(__name__)
class KoiAgentNode:
"""KOI node with agent personality capabilities."""
def __init__(self,
name: str,
version: str,
traits: Dict[str, Any],
base_url: str,
mcp_port: int,
first_contact: Optional[str] = None):
# Create personality RID
self.personality_rid = AgentPersonality(name, version)
# Convert traits dict to PersonalityTraits
self.traits = []
for key, value in traits.items():
# Check if value is a dict with trait metadata
if isinstance(value, dict) and "description" in value:
trait = PersonalityTrait(
name=key,
description=value.get("description", f"{key} trait for {name}"),
type=value.get("type", "object"),
value=value.get("value", None),
is_callable=value.get("is_callable", False)
)
else:
trait = PersonalityTrait.from_value(
name=key,
value=value,
description=f"{key} trait for {name}"
)
self.traits.append(trait)
# Initialize KOI node
self.node = NodeInterface(
name=name,
profile=NodeProfile(
base_url=base_url,
node_type=NodeType.FULL,
provides=NodeProvides(
event=[AgentPersonality],
state=[AgentPersonality]
)
),
use_kobj_processor_thread=True,
first_contact=first_contact
)
# Create personality profile
self.profile = PersonalityProfile(
rid=self.personality_rid,
node_rid=self.node.identity.rid,
base_url=base_url,
mcp_url=f"{base_url.rstrip('/')}/mcp",
traits=self.traits
)
# Initialize MCP server
self.mcp_server = AgentPersonalityServer(
port=mcp_port,
personality=self.profile
)
# Register handlers
self._register_handlers()
def _register_handlers(self):
"""Register knowledge handlers for the agent node."""
from koi_mcp.koi.handlers.personality_handlers import (
register_personality_handlers
)
register_personality_handlers(self.node.processor)
def update_traits(self, traits: Dict[str, Any]):
"""Update agent's traits and broadcast changes."""
# Update traits
for key, value in traits.items():
if self.profile.update_trait(key, value):
logger.info(f"Updated trait '{key}' to '{value}'")
else:
# Create new trait
trait = PersonalityTrait.from_value(
name=key,
value=value,
description=f"{key} trait for {self.profile.rid.name}"
)
self.profile.add_trait(trait)
logger.info(f"Added new trait '{key}' with value '{value}'")
# Create updated bundle
bundle = Bundle.generate(
rid=self.personality_rid,
contents=self.profile.model_dump()
)
# Process bundle internally to broadcast to network
self.node.processor.handle(bundle=bundle, event_type=EventType.UPDATE)
logger.info(f"Broadcast personality update for {self.personality_rid}")
def start(self):
"""Start the agent node."""
logger.info(f"Starting agent node {self.node.identity.rid}")
self.node.start()
# Broadcast initial personality directly to the coordinator's broadcast endpoint
bundle = Bundle.generate(
rid=self.personality_rid,
contents=self.profile.model_dump()
)
# Create a dedicated personality event
personality_event = Event.from_bundle(EventType.NEW, bundle)
# Find the coordinator in the first contact
first_contact_url = self.node.network.first_contact
if first_contact_url:
logger.info(f"Broadcasting personality directly to coordinator: {first_contact_url}")
try:
# Directly use the request handler to send just the personality event
self.node.network.request_handler.broadcast_events(
url=first_contact_url,
events=[personality_event] # Only send the personality event
)
logger.info(f"Successfully sent personality to coordinator")
except Exception as e:
logger.error(f"Failed to broadcast personality: {e}")
# Also process locally to ensure it's in our cache
self.node.processor.handle(bundle=bundle, event_type=EventType.NEW)
logger.info(f"Agent node started successfully")
</file>
<file path="src/koi_mcp/koi/node/coordinator.py">
# Update file: koi_mcp/koi/node/coordinator.py
import logging
import uvicorn
from fastapi import FastAPI
from rid_lib.types import KoiNetNode, KoiNetEdge
from koi_net import NodeInterface
from koi_net.protocol.node import NodeProfile, NodeType, NodeProvides
from koi_net.processor.knowledge_object import KnowledgeSource
from koi_net.protocol.api_models import *
from koi_net.protocol.consts import *
from koi_mcp.personality.rid import AgentPersonality
from koi_mcp.personality.models.profile import PersonalityProfile
from koi_mcp.server.adapter.mcp_adapter import MCPAdapter
from koi_mcp.server.registry.registry_server import AgentRegistryServer
logger = logging.getLogger(__name__)
class CoordinatorAdapterNode:
"""A specialized KOI node that integrates coordination functions with MCP adaptation."""
def __init__(self,
name: str,
base_url: str,
mcp_registry_port: int = 9000):
# Initialize KOI Coordinator Node
self.node = NodeInterface(
name=name,
profile=NodeProfile(
base_url=base_url,
node_type=NodeType.FULL,
provides=NodeProvides(
event=[KoiNetNode, KoiNetEdge, AgentPersonality],
state=[KoiNetNode, KoiNetEdge, AgentPersonality]
)
),
use_kobj_processor_thread=True
)
# Initialize MCP Adapter with Registry
self.mcp_adapter = MCPAdapter()
# Register handlers
self._register_handlers()
# Initialize MCP Registry Server
self.registry_server = AgentRegistryServer(
port=mcp_registry_port,
adapter=self.mcp_adapter,
root_path="/koi-net"
)
# Add KOI-net protocol endpoints to the app
self._add_koi_endpoints()
def _register_handlers(self):
"""Register knowledge handlers for the coordinator node."""
from koi_mcp.koi.handlers.personality_handlers import (
register_personality_handlers
)
register_personality_handlers(self.node.processor, self.mcp_adapter)
def _add_koi_endpoints(self):
"""Add KOI-net protocol endpoints to the FastAPI app."""
app = self.registry_server.app
# Add or modify the broadcast_events method in _add_koi_endpoints
@app.post(BROADCAST_EVENTS_PATH)
def broadcast_events(req: EventsPayload):
"""Handle events broadcast from other nodes."""
logger.info(f"Received {len(req.events)} events from broadcast")
for event in req.events:
# Log the incoming event in detail
logger.info(f"Processing event: {event.event_type} {event.rid}")
# Special handling for agent personalities
if isinstance(event.rid, AgentPersonality):
logger.info(f"Received agent personality event: {event.rid}")
# Create a bundle directly from the event
if event.manifest and event.contents:
bundle = Bundle(
manifest=event.manifest,
contents=event.contents
)
# Register with MCP adapter if it exists
try:
# Validate as personality profile
profile = PersonalityProfile.model_validate(event.contents)
self.mcp_adapter.register_agent(profile)
logger.info(f"Successfully registered agent {profile.rid.name} with MCP adapter")
# Cache the bundle
self.node.cache.write(bundle)
logger.info(f"Cached agent personality: {event.rid}")
except Exception as e:
logger.error(f"Failed to register personality: {e}")
else:
logger.warning(f"Agent personality event missing manifest or contents: {event.rid}")
# Pass to normal processing pipeline
self.node.processor.handle(event=event, source=KnowledgeSource.External)
return {}
@app.post(POLL_EVENTS_PATH)
def poll_events(req: PollEvents) -> EventsPayload:
"""Handle event polling from other nodes."""
events = self.node.network.flush_poll_queue(req.rid)
return EventsPayload(events=events)
@app.post(FETCH_RIDS_PATH)
def fetch_rids(req: FetchRids) -> RidsPayload:
"""Handle RID fetching from other nodes."""
return self.node.network.response_handler.fetch_rids(req)
@app.post(FETCH_MANIFESTS_PATH)
def fetch_manifests(req: FetchManifests) -> ManifestsPayload:
"""Handle manifest fetching from other nodes."""
return self.node.network.response_handler.fetch_manifests(req)
@app.post(FETCH_BUNDLES_PATH)
def fetch_bundles(req: FetchBundles) -> BundlesPayload:
"""Handle bundle fetching from other nodes."""
return self.node.network.response_handler.fetch_bundles(req)
def start(self):
"""Start the coordinator node."""
logger.info(f"Starting coordinator node {self.node.identity.rid}")
self.node.start()
logger.info("Coordinator node started successfully")
</file>
<file path="src/koi_mcp/personality/models/profile.py">
from typing import Any, List, Optional
from pydantic import BaseModel, Field
from rid_lib.types.koi_net_node import KoiNetNode
from koi_mcp.personality.rid import AgentPersonality
from koi_mcp.personality.models.trait import PersonalityTrait
class PersonalityProfile(BaseModel):
"""Model representing an agent's complete personality profile."""
rid: AgentPersonality
node_rid: KoiNetNode
base_url: Optional[str] = None
mcp_url: Optional[str] = None
traits: List[PersonalityTrait] = Field(default_factory=list)
def get_trait(self, name: str) -> Optional[PersonalityTrait]:
"""Get a trait by name."""
for trait in self.traits:
if trait.name == name:
return trait
return None
def update_trait(self, name: str, value: Any) -> bool:
"""Update a trait's value."""
for trait in self.traits:
if trait.name == name:
trait.value = value
return True
return False
def add_trait(self, trait: PersonalityTrait) -> None:
"""Add a new trait."""
self.traits.append(trait)
</file>
<file path="src/koi_mcp/personality/models/trait.py">
from typing import Any, Optional
from pydantic import BaseModel, Field
class PersonalityTrait(BaseModel):
"""Model representing a single personality trait."""
name: str
description: str = ""
type: str
value: Any
is_callable: bool = False
@classmethod
def from_value(cls, name: str, value: Any, description: str = "", is_callable: bool = False):
"""Create a trait from a value."""
return cls(
name=name,
description=description or f"{name} trait",
type=type(value).__name__,
value=value,
is_callable=is_callable
)
</file>
<file path="src/koi_mcp/personality/rid.py">
from rid_lib.core import ORN
class AgentPersonality(ORN):
namespace = "agent.personality"
def __init__(self, name, version):
self.name = name
self.version = version
@property
def reference(self):
return f"{self.name}/{self.version}"
@classmethod
def from_reference(cls, reference):
components = reference.split("/")
if len(components) == 2:
return cls(*components)
else:
raise ValueError(
"Agent Personality reference must contain: '<name>/<version>'"
)
</file>
<file path="src/koi_mcp/server/adapter/mcp_adapter.py">
import logging
from typing import Dict, List, Optional
from koi_mcp.personality.models.profile import PersonalityProfile
logger = logging.getLogger(__name__)
class MCPAdapter:
"""Adapts KOI personalities to MCP resources and tools."""
def __init__(self):
self.agents: Dict[str, PersonalityProfile] = {}
def register_agent(self, profile: PersonalityProfile):
"""Register an agent profile with the adapter."""
logger.info(f"Registering agent {profile.rid.name}")
self.agents[profile.rid.name] = profile
def get_agent(self, name: str) -> Optional[PersonalityProfile]:
"""Retrieve an agent profile by name."""
return self.agents.get(name)
def list_agents(self) -> List[Dict]:
"""Get list of all known agents as MCP resources."""
return [
{
"id": f"agent:{agent.rid.name}",
"type": "agent_profile",
"description": f"Agent {agent.rid.name} personality profile",
"url": agent.mcp_url
}
for agent in self.agents.values()
]
def get_tools_for_agent(self, agent_name: str) -> List[Dict]:
"""Get list of tools provided by a specific agent."""
agent = self.get_agent(agent_name)
if not agent:
return []
return [
{
"name": trait.name,
"description": trait.description,
"input_schema": {"type": "string"},
"url": f"{agent.mcp_url}/tools/call/{trait.name}"
}
for trait in agent.traits
if trait.is_callable
]
def get_all_tools(self) -> List[Dict]:
"""Get list of all tools from all agents."""
all_tools = []
for agent_name in self.agents:
tools = self.get_tools_for_agent(agent_name)
for tool in tools:
# Add agent name to tool name for uniqueness
tool["name"] = f"{agent_name}.{tool['name']}"
all_tools.append(tool)
return all_tools
</file>
<file path="src/koi_mcp/server/agent/agent_server.py">
import logging
from typing import Dict, Any
from fastapi import FastAPI, HTTPException
from koi_mcp.personality.models.profile import PersonalityProfile
logger = logging.getLogger(__name__)
class AgentPersonalityServer:
"""MCP-compatible server for a single agent's personality."""
def __init__(self, port: int, personality: PersonalityProfile):
self.port = port
self.personality = personality
self.app = FastAPI(
title=f"{personality.rid.name} MCP Server",
description=f"MCP-compatible server for {personality.rid.name} agent",
version="0.1.0"
)
# Set up routes
self._setup_routes()
def _setup_routes(self):
"""Set up API routes."""
@self.app.get("/resources/list")
def list_resources():
"""List agent personality as a resource."""
return {
"resources": [
{
"id": f"agent:{self.personality.rid.name}",
"type": "agent_profile",
"description": f"{self.personality.rid.name} agent personality",
"url": f"/resources/read/agent:{self.personality.rid.name}"
}
]
}
@self.app.get("/resources/read/agent:{agent_name}")
def read_resource(agent_name: str):
"""Read agent personality resource."""
if agent_name != self.personality.rid.name:
raise HTTPException(status_code=404, detail="Agent not found")
return {
"id": f"agent:{agent_name}",
"type": "agent_profile",
"content": self.personality.model_dump()
}
@self.app.get("/tools/list")
def list_tools():
"""List all callable traits as tools."""
tools = [
{
"name": trait.name,
"description": trait.description,
"input_schema": {"type": "string"},
"url": f"/tools/call/{trait.name}"
}
for trait in self.personality.traits
if trait.is_callable
]
return {"tools": tools}
@self.app.post("/tools/call/{trait_name}")
def call_tool(trait_name: str, input: Dict[str, Any] = {}):
"""Call a trait as a tool."""
trait = self.personality.get_trait(trait_name)
if not trait:
raise HTTPException(status_code=404, detail=f"Trait {trait_name} not found")
if not trait.is_callable:
raise HTTPException(status_code=400, detail=f"Trait {trait_name} is not callable")
# Return the trait value for this simple demo
# In a real implementation, this would call a function
return {
"result": f"Value of {trait_name}: {trait.value}"
}
</file>
<file path="src/koi_mcp/server/registry/registry_server.py">
import logging
from fastapi import FastAPI, HTTPException
from koi_mcp.server.adapter.mcp_adapter import MCPAdapter
logger = logging.getLogger(__name__)
class AgentRegistryServer:
"""MCP-compatible server that exposes agent registry."""
def __init__(self, port: int, adapter: MCPAdapter, root_path: str = ""):
self.port = port
self.adapter = adapter
self.app = FastAPI(
title="KOI-MCP Agent Registry",
description="MCP-compatible registry of agent personalities",
version="0.1.0",
root_path=root_path
)
# Set up routes
self._setup_routes()
def _setup_routes(self):
"""Set up API routes."""
@self.app.get("/resources/list")
def list_resources():
"""List all available agent resources."""
return {"resources": self.adapter.list_agents()}
@self.app.get("/resources/read/{resource_id}")
def read_resource(resource_id: str):
"""Read a specific agent resource."""
if not resource_id.startswith("agent:"):
raise HTTPException(status_code=404, detail="Resource not found")
agent_name = resource_id[6:] # Strip "agent:" prefix
agent = self.adapter.get_agent(agent_name)
if not agent:
raise HTTPException(status_code=404, detail="Agent not found")
return {
"id": resource_id,
"type": "agent_profile",
"content": agent.model_dump()
}
@self.app.get("/tools/list")
def list_tools():
"""List all available agent tools."""
return {"tools": self.adapter.get_all_tools()}
</file>
<file path="src/koi_mcp/utils/async/retry.py">
import asyncio
import logging
from typing import Callable, TypeVar, Any, Optional
T = TypeVar('T')
logger = logging.getLogger(__name__)
async def with_retry(
func: Callable[..., T],
*args: Any,
retries: int = 3,
delay: float = 1.0,
backoff: float = 2.0,
**kwargs: Any
) -> Optional[T]:
"""Retry an async function with exponential backoff."""
current_delay = delay
for i in range(retries):
try:
return await func(*args, **kwargs)
except Exception as e:
if i == retries - 1: # Last attempt
logger.error(f"Failed after {retries} attempts: {e}")
return None
logger.warning(f"Attempt {i+1} failed: {e}. Retrying in {current_delay:.1f}s")
await asyncio.sleep(current_delay)
current_delay *= backoff
</file>
<file path="src/koi_mcp/utils/logging/setup.py">
import logging
from rich.logging import RichHandler
def setup_logging(level=logging.INFO, koi_level=logging.DEBUG):
"""Set up logging with Rich handler."""
logging.basicConfig(
level=level,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
handlers=[RichHandler(rich_tracebacks=True)]
)
# Set KOI-net library logging level
logging.getLogger("koi_net").setLevel(koi_level)
# Return root logger
return logging.getLogger()
</file>
<file path="src/koi_mcp/config.py">
import json
import os
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
class AgentConfig(BaseModel):
name: str
version: str = "1.0"
base_url: str
mcp_port: int
traits: Dict[str, Any] = Field(default_factory=dict)
class NetworkConfig(BaseModel):
first_contact: Optional[str] = None
class CoordinatorConfig(BaseModel):
name: str
base_url: str
mcp_registry_port: int
class Config(BaseModel):
agent: Optional[AgentConfig] = None
coordinator: Optional[CoordinatorConfig] = None
network: NetworkConfig = Field(default_factory=NetworkConfig)
def _deep_update(target, source):
"""Deep update a nested dictionary."""
for key, value in source.items():
if key in target and isinstance(target[key], dict) and isinstance(value, dict):
_deep_update(target[key], value)
else:
target[key] = value
def load_config(config_path: Optional[str] = None) -> Config:
"""Load configuration from file or environment variables."""
config = {}
# Load from file if provided
if config_path and os.path.exists(config_path):
with open(config_path, 'r') as f:
config = json.load(f)
# Check environment variables
if os.getenv("KOI_MCP_CONFIG"):
try:
env_config = json.loads(os.getenv("KOI_MCP_CONFIG", "{}"))
# Merge with existing config
_deep_update(config, env_config)
except json.JSONDecodeError:
pass
# Individual environment variables take precedence
if os.getenv("KOI_MCP_AGENT_NAME"):
if "agent" not in config:
config["agent"] = {}
config["agent"]["name"] = os.getenv("KOI_MCP_AGENT_NAME")
if os.getenv("KOI_MCP_AGENT_BASE_URL"):
if "agent" not in config:
config["agent"] = {}
config["agent"]["base_url"] = os.getenv("KOI_MCP_AGENT_BASE_URL")
# More env vars can be added here
return Config.model_validate(config)
</file>
<file path="src/koi_mcp/main.py">
import os
import sys
import time
import argparse
import logging
import asyncio
import uvicorn
import multiprocessing
from koi_mcp.utils.logging.setup import setup_logging
from koi_mcp.config import load_config, Config
from koi_mcp.koi.node.coordinator import CoordinatorAdapterNode
from koi_mcp.koi.node.agent import KoiAgentNode
logger = setup_logging()
def run_coordinator(config_path: str = "configs/coordinator.json"):
"""Run the KOI-MCP Coordinator Node."""
config = load_config(config_path)
if not config.coordinator:
logger.error("Coordinator configuration not found in config file")
sys.exit(1)
logger.info(f"Starting coordinator node {config.coordinator.name}")
# Create Coordinator-Adapter node
coordinator = CoordinatorAdapterNode(
name=config.coordinator.name,
base_url=config.coordinator.base_url,
mcp_registry_port=config.coordinator.mcp_registry_port
)
# Start node
coordinator.start()
# Start MCP Registry Server
logger.info(f"Starting MCP registry server on port {config.coordinator.mcp_registry_port}")
uvicorn.run(
coordinator.registry_server.app,
host="0.0.0.0",
port=config.coordinator.mcp_registry_port
)
def run_agent(config_path: str = "configs/agent1.json"):
"""Run a KOI-MCP Agent Node."""
config = load_config(config_path)
if not config.agent:
logger.error("Agent configuration not found in config file")
sys.exit(1)
logger.info(f"Starting agent node {config.agent.name}")
# Create Agent node
agent = KoiAgentNode(
name=config.agent.name,
version=config.agent.version,
traits=config.agent.traits,
base_url=config.agent.base_url,
mcp_port=config.agent.mcp_port,
first_contact=config.network.first_contact
)
# Start node
agent.start()
# Start MCP Server
logger.info(f"Starting MCP agent server on port {config.agent.mcp_port}")
uvicorn.run(
agent.mcp_server.app,
host="0.0.0.0",
port=config.agent.mcp_port
)
def run_process(target, config_path=None):
"""Run a function in a separate process."""
kwargs = {}
if config_path:
kwargs["config_path"] = config_path
process = multiprocessing.Process(target=target, kwargs=kwargs)
process.start()
return process