code.xml•78.8 kB
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
def run_demo():
"""Run a demonstration with coordinator and two agent nodes."""
logger.info("Starting KOI-MCP demonstration")
# Start coordinator
logger.info("Starting coordinator node")
coordinator_process = run_process(run_coordinator, "configs/coordinator.json")
# Give coordinator time to start
time.sleep(5)
# Start first agent
logger.info("Starting agent 1")
agent1_process = run_process(run_agent, "configs/agent1.json")
# Start second agent
logger.info("Starting agent 2")
agent2_process = run_process(run_agent, "configs/agent2.json")
try:
# Keep main process running
while True:
time.sleep(1)
except KeyboardInterrupt:
logger.info("Stopping demo")
finally:
# Terminate processes
for process in [coordinator_process, agent1_process, agent2_process]:
if process.is_alive():
process.terminate()
process.join(timeout=5)
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="KOI-MCP Integration")
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Coordinator command
coordinator_parser = subparsers.add_parser("coordinator", help="Run coordinator node")
coordinator_parser.add_argument("--config", default="configs/coordinator.json", help="Path to config file")
# Agent command
agent_parser = subparsers.add_parser("agent", help="Run agent node")
agent_parser.add_argument("--config", default="configs/agent1.json", help="Path to config file")
# Demo command
subparsers.add_parser("demo", help="Run demonstration with coordinator and two agents")
args = parser.parse_args()
if args.command == "coordinator":
run_coordinator(args.config)
elif args.command == "agent":
run_agent(args.config)
elif args.command == "demo":
run_demo()
else:
parser.print_help()
if __name__ == "__main__":
main()
</file>
<file path="src/code.txt">
This file is a merged representation of a subset of the codebase, containing specifically included files and files not matching ignore patterns, 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: **/*.py
- Files matching these patterns are excluded: **/__init__.py
- 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>
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
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path="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="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="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="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="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="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="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="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="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="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="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="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="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
def run_demo():
"""Run a demonstration with coordinator and two agent nodes."""
logger.info("Starting KOI-MCP demonstration")
# Start coordinator
logger.info("Starting coordinator node")
coordinator_process = run_process(run_coordinator, "configs/coordinator.json")
# Give coordinator time to start
time.sleep(5)
# Start first agent
logger.info("Starting agent 1")
agent1_process = run_process(run_agent, "configs/agent1.json")
# Start second agent
logger.info("Starting agent 2")
agent2_process = run_process(run_agent, "configs/agent2.json")
try:
# Keep main process running
while True:
time.sleep(1)
except KeyboardInterrupt:
logger.info("Stopping demo")
finally:
# Terminate processes
for process in [coordinator_process, agent1_process, agent2_process]:
if process.is_alive():
process.terminate()
process.join(timeout=5)
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description="KOI-MCP Integration")
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Coordinator command
coordinator_parser = subparsers.add_parser("coordinator", help="Run coordinator node")
coordinator_parser.add_argument("--config", default="configs/coordinator.json", help="Path to config file")
# Agent command
agent_parser = subparsers.add_parser("agent", help="Run agent node")
agent_parser.add_argument("--config", default="configs/agent1.json", help="Path to config file")
# Demo command
subparsers.add_parser("demo", help="Run demonstration with coordinator and two agents")
args = parser.parse_args()
if args.command == "coordinator":
run_coordinator(args.config)
elif args.command == "agent":
run_agent(args.config)
elif args.command == "demo":
run_demo()
else:
parser.print_help()
if __name__ == "__main__":
main()
</file>
</files>
</file>
<file path="scripts/demo.py">
#!/usr/bin/env python3
"""
demo_full.py
A full‑blown KOI‑MCP integration demo that:
1. Starts Coordinator, Agent 1, Agent 2 (streaming logs via rich)
2. Waits for each /resources/list and /tools/list to respond
3. Prints KOI resources and MCP tools in tables
4. Invokes a sample trait on each agent via POST
5. Examines the KOI cache directory
6. Cleans up on Ctrl+C
"""
import subprocess, threading, time, signal, sys, os, urllib.parse
import httpx
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.live import Live
from rich.spinner import Spinner
console = Console()
# ——— CONFIGURATION ———
COORD_CMD = ["python", "-m", "koi_mcp.main", "coordinator", "--config", "configs/coordinator.json"]
AGENT1_CMD = ["python", "-m", "koi_mcp.main", "agent", "--config", "configs/agent1.json"]
AGENT2_CMD = ["python", "-m", "koi_mcp.main", "agent", "--config", "configs/agent2.json"]
COORD_URL = "http://localhost:9000"
AGENT1_URL = "http://localhost:8101"
AGENT2_URL = "http://localhost:8102"
# ——— LOG STREAMING ———
def _stream(name, stream, style):
for line in iter(stream.readline, ""):
if not line:
break
console.print(f"[{style}][{name}][/] {line.rstrip()}")
def start(name, cmd, style):
console.print(f"[bold]{name}[/bold] → {' '.join(cmd)}")
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=1,
env={**os.environ, "PYTHONUNBUFFERED":"1", "LOG_LEVEL":"DEBUG"}
)
threading.Thread(target=_stream, args=(name, proc.stdout, style), daemon=True).start()
threading.Thread(target=_stream, args=(name+" ERR", proc.stderr, style), daemon=True).start()
return proc
# ——— WAIT FOR ENDPOINT ———
def wait_for(url, path, timeout=30):
client = httpx.Client(timeout=2)
spinner = Spinner("dots", text=f"Waiting for {url}{path}")
with Live(spinner, console=console, refresh_per_second=10):
for _ in range(timeout*10):
try:
r = client.get(f"{url}{path}")
if r.status_code == 200:
console.log(f"[green]✔[/green] {url}{path}")
return True
except Exception:
pass
time.sleep(0.1)
console.log(f"[red]✖[/red] {url}{path} timed out")
return False
# ——— DISPLAY RESOURCES & TOOLS ———
def show_resources(url):
r = httpx.get(f"{url}/resources/list")
data = r.json().get("resources", [])
table = Table(title=f"Resources @ {url}")
table.add_column("ID", style="cyan", no_wrap=True)
table.add_column("Type", style="magenta")
table.add_column("Desc", style="green")
for res in data:
table.add_row(res["id"], res["type"], res.get("description",""))
console.print(table)
return data
def show_tools(url):
r = httpx.get(f"{url}/tools/list")
data = r.json().get("tools", [])
table = Table(title=f"Tools @ {url}")
table.add_column("Name", style="cyan")
table.add_column("URL", style="blue")
for tool in data:
table.add_row(tool["name"], tool["url"])
console.print(table)
return data
# ——— INVOKE TRAIT ———
def invoke_trait(base_url, tool):
"""
tool: { "name": "...", "url": "..." }
we POST {} to the full URL
"""
raw = tool["url"]
# resolve relative URLs
full = raw if raw.startswith("http") else urllib.parse.urljoin(base_url, raw)
console.print(Panel(f"Calling [bold]{tool['name']}[/bold] → {full}", style="yellow"))
try:
r = httpx.post(full, json={}) # empty JSON or {"expr":"2+2"} etc
console.print(f"[green]200[/green] {r.text}")
except Exception as e:
console.print(f"[red]ERROR[/red] {e}")
# ——— EXAMINE CACHE ———
def examine_cache(dirpath="rid_cache"):
console.print(Panel(f"Inspecting cache: {dirpath}", style="blue"))
if not os.path.isdir(dirpath):
console.print("[red]No cache directory found[/red]")
return
files = sorted(os.listdir(dirpath))
tbl = Table(title="Cache Files")
tbl.add_column("File", style="cyan")
tbl.add_column("Size", style="green", justify="right")
for fn in files:
tbl.add_row(fn, str(os.path.getsize(os.path.join(dirpath, fn))))
console.print(tbl)
# ——— CLEANUP ———
def shutdown(procs):
console.print("\n[bold yellow]Stopping services…[/bold yellow]")
for p in procs:
p.terminate()
try: p.wait(3)
except: p.kill()
console.print("[bold green]Shutdown complete[/bold green]")
# ——— MAIN ———
def main():
procs = []
signal.signal(signal.SIGINT, lambda s,f: (shutdown(procs), sys.exit(0)))
# 1) Start Coordinator & Agents
procs.append(start("Coordinator", COORD_CMD, "blue"))
assert wait_for(COORD_URL, "/resources/list")
procs.append(start("Agent 1", AGENT1_CMD, "green"))
assert wait_for(AGENT1_URL, "/resources/list")
procs.append(start("Agent 2", AGENT2_CMD, "magenta"))
assert wait_for(AGENT2_URL, "/resources/list")
# 2) Show network state
show_resources(COORD_URL)
show_tools(COORD_URL)
show_resources(AGENT1_URL)
show_tools(AGENT1_URL)
show_resources(AGENT2_URL)
show_tools(AGENT2_URL)
# 3) Call one trait per agent
tools1 = show_tools(AGENT1_URL)
if tools1:
invoke_trait(AGENT1_URL, tools1[0])
tools2 = show_tools(AGENT2_URL)
if tools2:
invoke_trait(AGENT2_URL, tools2[0])
# 4) Inspect cache
examine_cache()
console.print("\n[bold yellow]Demo running. Ctrl+C to exit.[/bold yellow]")
while True:
time.sleep(1)
if __name__ == "__main__":
main()
</file>
</files>