This commit is contained in:
6
.gitignore
vendored
6
.gitignore
vendored
@@ -23,7 +23,8 @@ agent_coordinator-*.tar
|
||||
/tmp/
|
||||
|
||||
# IDE and Editor files
|
||||
.vscode/
|
||||
/.vscode/
|
||||
!/.vscode/mcp.json
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
@@ -98,3 +99,6 @@ coverage/
|
||||
/erl_crash.dump
|
||||
/_build
|
||||
/test_env
|
||||
/docs
|
||||
|
||||
!/.vscode/mcp.json
|
||||
|
||||
16
.vscode/mcp.json
vendored
Normal file
16
.vscode/mcp.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"servers": {
|
||||
"coordinator": {
|
||||
"command": "/home/user/agent_coordinator/scripts/mcp_launcher.sh",
|
||||
"args": [],
|
||||
"env": {
|
||||
"MIX_ENV": "dev",
|
||||
"NATS_HOST": "127.0.0.1",
|
||||
"NATS_PORT": "4222",
|
||||
"MCP_CONFIG_FILE": "/home/user/agent_coordinator/mcp_servers.json"
|
||||
},
|
||||
"type": "stdio"
|
||||
}
|
||||
},
|
||||
"inputs": []
|
||||
}
|
||||
@@ -117,7 +117,7 @@ Choose one of these installation methods:
|
||||
--max_file_store=10Gb
|
||||
```
|
||||
|
||||
Then add this configuration to your VS Code `mcp.json` configuration file via `ctrl + shift + p` → `MCP: Open User Configuration` or `MCP: Open Remote User Configuration` if running on a remote server:
|
||||
Then add this configuration to your VS Code `mcp.json` configuration file inside of your workspace's `./.vscode/mcp.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -252,7 +252,7 @@ Choose one of these installation methods:
|
||||
|
||||
### Run via VS Code or similar tools
|
||||
|
||||
Add this to your `mcp.json` or `mcp_servers.json` depending on your tool:
|
||||
Add this to your workspace's `./.vscode/mcp.json` (vscode copilot) or `mcp_servers.json` depending on your tool:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -263,7 +263,9 @@ Choose one of these installation methods:
|
||||
"env": {
|
||||
"MIX_ENV": "prod",
|
||||
"NATS_HOST": "localhost",
|
||||
"NATS_PORT": "4222"
|
||||
"NATS_PORT": "4222",
|
||||
"MCP_CONFIG_FILE": "/path/to/mcp_servers.json",
|
||||
"PWD": "${workspaceFolder}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,333 +0,0 @@
|
||||
# Unified MCP Server with Auto-Heartbeat System Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
The Agent Coordinator now operates as a **unified MCP server** that internally manages all external MCP servers (Context7, Figma, Filesystem, Firebase, Memory, Sequential Thinking, etc.) while providing automatic task tracking and heartbeat coverage for every tool operation. GitHub Copilot sees only a single MCP server, but gets access to all tools with automatic coordination.
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. Unified MCP Server Architecture
|
||||
- **Single interface**: GitHub Copilot connects to only the Agent Coordinator
|
||||
- **Internal server management**: Automatically starts and manages all external MCP servers
|
||||
- **Unified tool registry**: Aggregates tools from all servers into one comprehensive list
|
||||
- **Automatic task tracking**: Every tool call automatically creates/updates agent tasks
|
||||
|
||||
### 2. Automatic Task Tracking
|
||||
- **Transparent operation**: Any tool usage automatically becomes a tracked task
|
||||
- **No explicit coordination needed**: Agents don't need to call `create_task` manually
|
||||
- **Real-time activity monitoring**: See what each agent is working on in real-time
|
||||
- **Smart task titles**: Automatically generated based on tool usage and context
|
||||
|
||||
### 3. Enhanced Heartbeat Coverage
|
||||
- **Universal coverage**: Every tool call from any server includes heartbeat management
|
||||
- **Agent session tracking**: Automatic agent registration for GitHub Copilot
|
||||
- **Activity-based heartbeats**: Heartbeats sent before/after each tool operation
|
||||
- **Session metadata**: Enhanced task board shows real activity and tool usage
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
GitHub Copilot
|
||||
↓
|
||||
Agent Coordinator (Single Visible MCP Server)
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Unified MCP Server │
|
||||
│ • Aggregates all tools into single interface │
|
||||
│ • Automatic task tracking for every operation │
|
||||
│ • Agent coordination tools (create_task, etc.) │
|
||||
│ • Universal heartbeat coverage │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ MCP Server Manager │
|
||||
│ • Starts & manages external servers internally │
|
||||
│ • Health monitoring & auto-restart │
|
||||
│ • Tool aggregation & routing │
|
||||
│ • Auto-task creation for any tool usage │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
↓
|
||||
┌──────────┬──────────┬───────────┬──────────┬─────────────┐
|
||||
│ Context7 │ Figma │Filesystem │ Firebase │ Memory + │
|
||||
│ Server │ Server │ Server │ Server │ Sequential │
|
||||
└──────────┴──────────┴───────────┴──────────┴─────────────┘
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### GitHub Copilot Experience
|
||||
|
||||
From GitHub Copilot's perspective, there's only one MCP server with all tools available:
|
||||
|
||||
```javascript
|
||||
// All these tools are available from the single Agent Coordinator server:
|
||||
|
||||
// Agent coordination tools
|
||||
register_agent, create_task, get_next_task, complete_task, get_task_board, heartbeat
|
||||
|
||||
// Context7 tools
|
||||
mcp_context7_get-library-docs, mcp_context7_resolve-library-id
|
||||
|
||||
// Figma tools
|
||||
mcp_figma_get_code, mcp_figma_get_image, mcp_figma_get_variable_defs
|
||||
|
||||
// Filesystem tools
|
||||
mcp_filesystem_read_file, mcp_filesystem_write_file, mcp_filesystem_list_directory
|
||||
|
||||
// Firebase tools
|
||||
mcp_firebase_firestore_get_documents, mcp_firebase_auth_get_user
|
||||
|
||||
// Memory tools
|
||||
mcp_memory_search_nodes, mcp_memory_create_entities
|
||||
|
||||
// Sequential thinking tools
|
||||
mcp_sequentialthi_sequentialthinking
|
||||
|
||||
// Plus any other configured MCP servers...
|
||||
```
|
||||
|
||||
### Automatic Task Tracking
|
||||
|
||||
Every tool usage automatically creates or updates an agent's current task:
|
||||
|
||||
```elixir
|
||||
# When GitHub Copilot calls any tool, it automatically:
|
||||
# 1. Sends pre-operation heartbeat
|
||||
# 2. Creates/updates current task based on tool usage
|
||||
# 3. Routes to appropriate external server
|
||||
# 4. Sends post-operation heartbeat
|
||||
# 5. Updates task activity log
|
||||
|
||||
# Example: Reading a file automatically creates a task
|
||||
Tool Call: mcp_filesystem_read_file(%{"path" => "/project/src/main.rs"})
|
||||
Auto-Created Task: "Reading file: main.rs"
|
||||
Description: "Reading and analyzing file content from /project/src/main.rs"
|
||||
|
||||
# Example: Figma code generation automatically creates a task
|
||||
Tool Call: mcp_figma_get_code(%{"nodeId" => "123:456"})
|
||||
Auto-Created Task: "Generating Figma code: 123:456"
|
||||
Description: "Generating code for Figma component 123:456"
|
||||
|
||||
# Example: Library research automatically creates a task
|
||||
Tool Call: mcp_context7_get-library-docs(%{"context7CompatibleLibraryID" => "/vercel/next.js"})
|
||||
Auto-Created Task: "Researching: /vercel/next.js"
|
||||
Description: "Researching documentation for /vercel/next.js library"
|
||||
```
|
||||
|
||||
### Task Board with Real Activity
|
||||
|
||||
```elixir
|
||||
# Get enhanced task board showing real agent activity
|
||||
{:ok, board} = get_task_board()
|
||||
|
||||
# Returns:
|
||||
%{
|
||||
agents: [
|
||||
%{
|
||||
agent_id: "github_copilot_session",
|
||||
name: "GitHub Copilot",
|
||||
status: :working,
|
||||
current_task: %{
|
||||
title: "Reading file: database.ex",
|
||||
description: "Reading and analyzing file content from /project/lib/database.ex",
|
||||
auto_generated: true,
|
||||
tool_name: "mcp_filesystem_read_file",
|
||||
created_at: ~U[2025-08-23 10:30:00Z]
|
||||
},
|
||||
last_heartbeat: ~U[2025-08-23 10:30:05Z],
|
||||
online: true
|
||||
}
|
||||
],
|
||||
pending_tasks: [],
|
||||
total_agents: 1,
|
||||
active_tasks: 1,
|
||||
pending_count: 0
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
### MCP Server Configuration
|
||||
|
||||
External servers are configured in `mcp_servers.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"servers": {
|
||||
"mcp_context7": {
|
||||
"type": "stdio",
|
||||
"command": "uvx",
|
||||
"args": ["mcp-server-context7"],
|
||||
"auto_restart": true,
|
||||
"description": "Context7 library documentation server"
|
||||
},
|
||||
"mcp_figma": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@figma/mcp-server-figma"],
|
||||
"auto_restart": true,
|
||||
"description": "Figma design integration server"
|
||||
},
|
||||
"mcp_filesystem": {
|
||||
"type": "stdio",
|
||||
"command": "npx",
|
||||
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/ra"],
|
||||
"auto_restart": true,
|
||||
"description": "Filesystem operations with auto-task tracking"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"startup_timeout": 30000,
|
||||
"heartbeat_interval": 10000,
|
||||
"auto_restart_delay": 1000,
|
||||
"max_restart_attempts": 3
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### VS Code Settings
|
||||
|
||||
Update your VS Code MCP settings to point to the unified server:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp.servers": {
|
||||
"agent-coordinator": {
|
||||
"command": "/home/ra/agent_coordinator/scripts/mcp_launcher.sh",
|
||||
"args": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
### 1. Simplified Configuration
|
||||
- **One server**: GitHub Copilot only needs to connect to Agent Coordinator
|
||||
- **No manual setup**: External servers are managed automatically
|
||||
- **Unified tools**: All tools appear in one comprehensive list
|
||||
|
||||
### 2. Automatic Coordination
|
||||
- **Zero-effort tracking**: Every tool usage automatically tracked as tasks
|
||||
- **Real-time visibility**: See exactly what agents are working on
|
||||
- **Smart task creation**: Descriptive task titles based on actual tool usage
|
||||
- **Universal heartbeats**: Every operation maintains agent liveness
|
||||
|
||||
### 3. Enhanced Collaboration
|
||||
- **Agent communication**: Coordination tools still available for planning
|
||||
- **Multi-agent workflows**: Agents can create tasks for each other
|
||||
- **Activity awareness**: Agents can see what others are working on
|
||||
- **File conflict prevention**: Automatic file locking across operations
|
||||
|
||||
### 4. Operational Excellence
|
||||
- **Auto-restart**: Failed external servers automatically restarted
|
||||
- **Health monitoring**: Real-time status of all managed servers
|
||||
- **Error handling**: Graceful degradation when servers unavailable
|
||||
- **Performance**: Direct routing without external proxy overhead
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### From Individual MCP Servers
|
||||
|
||||
**Before:**
|
||||
```json
|
||||
// VS Code settings with multiple servers
|
||||
{
|
||||
"mcp.servers": {
|
||||
"context7": {"command": "uvx", "args": ["mcp-server-context7"]},
|
||||
"figma": {"command": "npx", "args": ["-y", "@figma/mcp-server-figma"]},
|
||||
"filesystem": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"]},
|
||||
"agent-coordinator": {"command": "/path/to/mcp_launcher.sh"}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**After:**
|
||||
```json
|
||||
// VS Code settings with single unified server
|
||||
{
|
||||
"mcp.servers": {
|
||||
"agent-coordinator": {
|
||||
"command": "/home/ra/agent_coordinator/scripts/mcp_launcher.sh",
|
||||
"args": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Migration
|
||||
|
||||
1. **Remove individual MCP servers** from VS Code settings
|
||||
2. **Add external servers** to `mcp_servers.json` configuration
|
||||
3. **Update launcher script** path if needed
|
||||
4. **Restart VS Code** to apply changes
|
||||
|
||||
## Startup and Testing
|
||||
|
||||
### Starting the Unified Server
|
||||
|
||||
```bash
|
||||
# From the project directory
|
||||
./scripts/mcp_launcher.sh
|
||||
```
|
||||
|
||||
### Testing Tool Aggregation
|
||||
|
||||
```bash
|
||||
# Test that all tools are available
|
||||
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | ./scripts/mcp_launcher.sh
|
||||
|
||||
# Should return tools from Agent Coordinator + all external servers
|
||||
```
|
||||
|
||||
### Testing Automatic Task Tracking
|
||||
|
||||
```bash
|
||||
# Use any tool - it should automatically create a task
|
||||
echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"mcp_filesystem_read_file","arguments":{"path":"/home/ra/test.txt"}}}' | ./scripts/mcp_launcher.sh
|
||||
|
||||
# Check task board to see auto-created task
|
||||
echo '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"get_task_board","arguments":{}}}' | ./scripts/mcp_launcher.sh
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### External Server Issues
|
||||
|
||||
1. **Server won't start**
|
||||
- Check command path in `mcp_servers.json`
|
||||
- Verify dependencies are installed (`npm install -g @modelcontextprotocol/server-*`)
|
||||
- Check logs for startup errors
|
||||
|
||||
2. **Tools not appearing**
|
||||
- Verify server started successfully
|
||||
- Check server health: use `get_server_status` tool
|
||||
- Restart specific servers if needed
|
||||
|
||||
3. **Auto-restart not working**
|
||||
- Check `auto_restart: true` in server config
|
||||
- Verify process monitoring is active
|
||||
- Check restart attempt limits
|
||||
|
||||
### Task Tracking Issues
|
||||
|
||||
1. **Tasks not auto-creating**
|
||||
- Verify agent session is active
|
||||
- Check that GitHub Copilot is registered as agent
|
||||
- Ensure heartbeat system is working
|
||||
|
||||
2. **Incorrect task titles**
|
||||
- Task titles are generated based on tool name and arguments
|
||||
- Can be customized in `generate_task_title/2` function
|
||||
- File-based operations use file paths in titles
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Planned improvements:
|
||||
|
||||
1. **Dynamic server discovery** - Auto-detect and add new MCP servers
|
||||
2. **Load balancing** - Distribute tool calls across multiple server instances
|
||||
3. **Tool versioning** - Support multiple versions of the same tool
|
||||
4. **Custom task templates** - Configurable task generation based on tool patterns
|
||||
5. **Inter-agent messaging** - Direct communication channels between agents
|
||||
6. **Workflow orchestration** - Multi-step task coordination across agents
|
||||
@@ -1,107 +0,0 @@
|
||||
# Dynamic Tool Discovery Implementation Summary
|
||||
|
||||
## What We Accomplished
|
||||
|
||||
The Agent Coordinator has been successfully refactored to implement **fully dynamic tool discovery** following the MCP protocol specification, eliminating all hardcoded tool lists **and ensuring shared MCP server instances across all agents**.
|
||||
|
||||
## Key Changes Made
|
||||
|
||||
### 1. Removed Hardcoded Tool Lists
|
||||
**Before**:
|
||||
```elixir
|
||||
coordinator_native = ~w[register_agent create_task get_next_task complete_task get_task_board heartbeat]
|
||||
```
|
||||
|
||||
**After**:
|
||||
```elixir
|
||||
# Tools discovered dynamically by checking actual tool definitions
|
||||
coordinator_tools = get_coordinator_tools()
|
||||
if Enum.any?(coordinator_tools, fn tool -> tool["name"] == tool_name end) do
|
||||
{:coordinator, tool_name}
|
||||
end
|
||||
```
|
||||
|
||||
### 2. Made VS Code Tools Conditional
|
||||
**Before**: Always included VS Code tools even if not available
|
||||
|
||||
**After**:
|
||||
```elixir
|
||||
vscode_tools = try do
|
||||
if Code.ensure_loaded?(AgentCoordinator.VSCodeToolProvider) do
|
||||
AgentCoordinator.VSCodeToolProvider.get_tools()
|
||||
else
|
||||
[]
|
||||
end
|
||||
rescue
|
||||
_ -> []
|
||||
end
|
||||
```
|
||||
|
||||
### 3. Added Shared MCP Server Management
|
||||
**MAJOR FIX**: MCPServerManager is now part of the application supervision tree
|
||||
|
||||
**Before**: Each agent/test started its own MCP servers
|
||||
- Multiple server instances for the same functionality
|
||||
- Resource waste and potential conflicts
|
||||
- Different OS PIDs per agent
|
||||
|
||||
**After**: Single shared MCP server instance
|
||||
- Added to `application.ex` supervision tree
|
||||
- All agents use the same MCP server processes
|
||||
- Perfect resource sharing
|
||||
|
||||
### 4. Added Dynamic Tool Refresh
|
||||
**New function**: `refresh_tools/0`
|
||||
- Re-discovers tools from all running MCP servers
|
||||
- Updates tool registry in real-time
|
||||
- Handles both PID and Port server types properly
|
||||
|
||||
### 5. Enhanced Tool Routing
|
||||
**Before**: Used hardcoded tool name lists for routing decisions
|
||||
|
||||
**After**: Checks actual tool definitions to determine routing## Test Results
|
||||
|
||||
✅ All tests passing with dynamic discovery:
|
||||
```
|
||||
Found 44 total tools:
|
||||
• Coordinator tools: 6
|
||||
• External MCP tools: 26+ (context7, filesystem, memory, sequential thinking)
|
||||
• VS Code tools: 12 (when available)
|
||||
```
|
||||
|
||||
**External servers discovered**:
|
||||
- Context7: 2 tools (resolve-library-id, get-library-docs)
|
||||
- Filesystem: 14 tools (read_file, write_file, edit_file, etc.)
|
||||
- Memory: 9 tools (search_nodes, create_entities, etc.)
|
||||
- Sequential Thinking: 1 tool (sequentialthinking)
|
||||
|
||||
## Benefits Achieved
|
||||
|
||||
1. **Perfect MCP Protocol Compliance**: No hardcoded assumptions, everything discovered via `tools/list`
|
||||
2. **Shared Server Architecture**: Single MCP server instance shared by all agents (massive resource savings)
|
||||
3. **Flexibility**: New MCP servers can be added via configuration without code changes
|
||||
4. **Reliability**: Tools automatically re-discovered when servers restart
|
||||
5. **Performance**: Only available tools included in routing decisions + shared server processes
|
||||
6. **Maintainability**: No need to manually sync tool lists with server implementations
|
||||
7. **Resource Efficiency**: No duplicate server processes per agent/session
|
||||
8. **Debugging**: Clear visibility into which tools are available from which servers
|
||||
|
||||
## Files Modified
|
||||
|
||||
1. **`lib/agent_coordinator/mcp_server_manager.ex`**:
|
||||
- Removed `get_coordinator_tool_names/0` function
|
||||
- Modified `find_tool_server/2` to use dynamic discovery
|
||||
- Added conditional VS Code tool loading
|
||||
- Added `refresh_tools/0` and `rediscover_all_tools/1`
|
||||
- Fixed Port vs PID handling for server aliveness checks
|
||||
|
||||
2. **Tests**:
|
||||
- Added `test/dynamic_tool_discovery_test.exs`
|
||||
- All existing tests still pass
|
||||
- New tests verify dynamic discovery works correctly
|
||||
|
||||
## Impact
|
||||
|
||||
This refactoring makes the Agent Coordinator a true MCP-compliant aggregation server that follows the protocol specification exactly, rather than making assumptions about what tools servers provide. It's now much more flexible and maintainable while being more reliable in dynamic environments where servers may come and go.
|
||||
|
||||
The system now perfectly implements the user's original request: **"all tools will reply with what tools are available"** via the MCP protocol's `tools/list` method.
|
||||
@@ -1,253 +0,0 @@
|
||||
# MCP Compliance Enhancement Summary
|
||||
|
||||
## Overview
|
||||
This document summarizes the enhanced Model Context Protocol (MCP) compliance features implemented in the Agent Coordinator system, focusing on session management, security, and real-time streaming capabilities.
|
||||
|
||||
## Implemented Features
|
||||
|
||||
### 1. 🔐 Enhanced Session Management
|
||||
|
||||
#### Session Token Authentication
|
||||
- **Implementation**: Modified `register_agent` to return cryptographically secure session tokens
|
||||
- **Token Format**: 32-byte secure random tokens, Base64 encoded
|
||||
- **Expiry**: 60-minute session timeout with automatic cleanup
|
||||
- **Headers**: Support for `Mcp-Session-Id` header (MCP compliant) and `X-Session-Id` (legacy)
|
||||
|
||||
#### Session Validation Flow
|
||||
```
|
||||
Client Server
|
||||
| |
|
||||
|-- POST /mcp/request ---->|
|
||||
| register_agent |
|
||||
| |
|
||||
|<-- session_token --------|
|
||||
| expires_at |
|
||||
| |
|
||||
|-- Subsequent requests -->|
|
||||
| Mcp-Session-Id: token |
|
||||
| |
|
||||
|<-- Authenticated resp ---|
|
||||
```
|
||||
|
||||
#### Key Components
|
||||
- **SessionManager GenServer**: Manages token lifecycle and validation
|
||||
- **Secure token generation**: Uses `:crypto.strong_rand_bytes/1`
|
||||
- **Automatic cleanup**: Periodic removal of expired sessions
|
||||
- **Backward compatibility**: Supports legacy X-Session-Id headers
|
||||
|
||||
### 2. 📋 MCP Protocol Version Compliance
|
||||
|
||||
#### Protocol Headers
|
||||
- **MCP-Protocol-Version**: `2025-06-18` (current specification)
|
||||
- **Server**: `AgentCoordinator/1.0` identification
|
||||
- **Applied to**: All JSON responses via enhanced `send_json_response/3`
|
||||
|
||||
#### CORS Enhancement
|
||||
- **Session Headers**: Added `mcp-session-id`, `mcp-protocol-version` to allowed headers
|
||||
- **Exposed Headers**: Protocol version and server headers exposed to clients
|
||||
- **Security**: Enhanced origin validation with localhost and HTTPS preference
|
||||
|
||||
### 3. 🔒 Security Enhancements
|
||||
|
||||
#### Origin Validation
|
||||
```elixir
|
||||
defp validate_origin(origin) do
|
||||
case URI.parse(origin) do
|
||||
%URI{host: host} when host in ["localhost", "127.0.0.1", "::1"] -> origin
|
||||
%URI{host: host} when is_binary(host) ->
|
||||
if String.starts_with?(origin, "https://") or
|
||||
String.contains?(host, ["localhost", "127.0.0.1", "dev", "local"]) do
|
||||
origin
|
||||
else
|
||||
Logger.warning("Potentially unsafe origin: #{origin}")
|
||||
"*"
|
||||
end
|
||||
_ -> "*"
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
#### Authenticated Method Protection
|
||||
Protected methods requiring valid session tokens:
|
||||
- `agents/register` ✓
|
||||
- `agents/unregister` ✓
|
||||
- `agents/heartbeat` ✓
|
||||
- `tasks/create` ✓
|
||||
- `tasks/complete` ✓
|
||||
- `codebase/register` ✓
|
||||
- `stream/subscribe` ✓
|
||||
|
||||
### 4. 📡 Server-Sent Events (SSE) Support
|
||||
|
||||
#### Real-time Streaming Endpoint
|
||||
- **Endpoint**: `GET /mcp/stream`
|
||||
- **Transport**: Streamable HTTP (MCP specification)
|
||||
- **Authentication**: Requires valid session token
|
||||
- **Content-Type**: `text/event-stream`
|
||||
|
||||
#### SSE Event Format
|
||||
```
|
||||
event: connected
|
||||
data: {"session_id":"agent_123","protocol_version":"2025-06-18","timestamp":"2025-01-11T..."}
|
||||
|
||||
event: heartbeat
|
||||
data: {"timestamp":"2025-01-11T...","session_id":"agent_123"}
|
||||
```
|
||||
|
||||
#### Features
|
||||
- **Connection establishment**: Sends initial `connected` event
|
||||
- **Heartbeat**: Periodic keepalive events
|
||||
- **Session tracking**: Events include session context
|
||||
- **Graceful disconnection**: Handles client disconnects
|
||||
|
||||
## Technical Implementation Details
|
||||
|
||||
### File Structure
|
||||
```
|
||||
lib/agent_coordinator/
|
||||
├── session_manager.ex # Session token management
|
||||
├── mcp_server.ex # Enhanced register_agent
|
||||
├── http_interface.ex # HTTP/SSE endpoints + security
|
||||
└── application.ex # Supervision tree
|
||||
```
|
||||
|
||||
### Session Manager API
|
||||
```elixir
|
||||
# Create new session
|
||||
{:ok, session_info} = SessionManager.create_session(agent_id, capabilities)
|
||||
|
||||
# Validate existing session
|
||||
{:ok, session_info} = SessionManager.validate_session(token)
|
||||
{:error, :expired} = SessionManager.validate_session(old_token)
|
||||
|
||||
# Manual cleanup (automatic via timer)
|
||||
SessionManager.cleanup_expired_sessions()
|
||||
```
|
||||
|
||||
### HTTP Interface Enhancements
|
||||
```elixir
|
||||
# Session validation middleware
|
||||
case validate_session_for_method(method, conn, context) do
|
||||
{:ok, session_info} -> # Process request
|
||||
{:error, auth_error} -> # Return 401 Unauthorized
|
||||
end
|
||||
|
||||
# MCP headers on all responses
|
||||
defp put_mcp_headers(conn) do
|
||||
conn
|
||||
|> put_resp_header("mcp-protocol-version", "2025-06-18")
|
||||
|> put_resp_header("server", "AgentCoordinator/1.0")
|
||||
end
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### 1. Agent Registration with Session Token
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/mcp/request \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "1",
|
||||
"method": "agents/register",
|
||||
"params": {
|
||||
"name": "My Agent Blue Koala",
|
||||
"capabilities": ["coding", "testing"],
|
||||
"codebase_id": "my_project"
|
||||
}
|
||||
}'
|
||||
|
||||
# Response:
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "1",
|
||||
"result": {
|
||||
"agent_id": "My Agent Blue Koala",
|
||||
"session_token": "abc123...",
|
||||
"expires_at": "2025-01-11T15:30:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Authenticated Tool Call
|
||||
```bash
|
||||
curl -X POST http://localhost:4000/mcp/request \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Mcp-Session-Id: abc123..." \
|
||||
-d '{
|
||||
"jsonrpc": "2.0",
|
||||
"id": "2",
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "get_task_board",
|
||||
"arguments": {"agent_id": "My Agent Blue Koala"}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
### 3. Server-Sent Events Stream
|
||||
```javascript
|
||||
const eventSource = new EventSource('/mcp/stream', {
|
||||
headers: {
|
||||
'Mcp-Session-Id': 'abc123...'
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.onmessage = function(event) {
|
||||
const data = JSON.parse(event.data);
|
||||
console.log('Received:', data);
|
||||
};
|
||||
```
|
||||
|
||||
## Testing and Verification
|
||||
|
||||
### Automated Test Script
|
||||
- **File**: `test_session_management.exs`
|
||||
- **Coverage**: Registration flow, session validation, protocol headers
|
||||
- **Usage**: `elixir test_session_management.exs`
|
||||
|
||||
### Manual Testing
|
||||
1. Start server: `mix phx.server`
|
||||
2. Register agent via `/mcp/request`
|
||||
3. Use returned session token for authenticated calls
|
||||
4. Verify MCP headers in responses
|
||||
5. Test SSE stream endpoint
|
||||
|
||||
## Benefits
|
||||
|
||||
### 🔐 Security
|
||||
- **Token-based authentication**: Prevents unauthorized access
|
||||
- **Session expiry**: Limits exposure of compromised tokens
|
||||
- **Origin validation**: Mitigates CSRF and unauthorized origins
|
||||
- **Method-level protection**: Granular access control
|
||||
|
||||
### 📋 MCP Compliance
|
||||
- **Official protocol version**: Headers indicate MCP 2025-06-18 support
|
||||
- **Streamable HTTP**: Real-time capabilities via SSE
|
||||
- **Proper error handling**: Standard JSON-RPC error responses
|
||||
- **Session context**: Request metadata for debugging
|
||||
|
||||
### 🚀 Developer Experience
|
||||
- **Backward compatibility**: Legacy headers still supported
|
||||
- **Clear error messages**: Detailed authentication failure reasons
|
||||
- **Real-time updates**: Live agent status via SSE
|
||||
- **Easy testing**: Comprehensive test utilities
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Planned Features
|
||||
- **PubSub integration**: Event-driven SSE updates
|
||||
- **Session persistence**: Redis/database backing
|
||||
- **Rate limiting**: Per-session request throttling
|
||||
- **Audit logging**: Session activity tracking
|
||||
- **WebSocket upgrade**: Bidirectional real-time communication
|
||||
|
||||
### Configuration Options
|
||||
- **Session timeout**: Configurable expiry duration
|
||||
- **Security levels**: Strict/permissive origin validation
|
||||
- **Token rotation**: Automatic refresh mechanisms
|
||||
- **Multi-tenancy**: Workspace-scoped sessions
|
||||
|
||||
---
|
||||
|
||||
*This implementation provides a solid foundation for MCP-compliant session management while maintaining the flexibility to extend with additional features as requirements evolve.*
|
||||
@@ -1,279 +0,0 @@
|
||||
# Agent Coordinator Multi-Interface MCP Server
|
||||
|
||||
The Agent Coordinator now supports multiple interface modes to accommodate different client types and use cases, from local VSCode integration to remote web applications.
|
||||
|
||||
## Interface Modes
|
||||
|
||||
### 1. STDIO Mode (Default)
|
||||
Traditional MCP over stdin/stdout for local clients like VSCode.
|
||||
|
||||
**Features:**
|
||||
- Full tool access (filesystem, VSCode, terminal tools)
|
||||
- Local security context (trusted)
|
||||
- Backward compatible with existing MCP clients
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh stdio
|
||||
# or
|
||||
./scripts/mcp_launcher.sh # original launcher
|
||||
```
|
||||
|
||||
### 2. HTTP Mode
|
||||
REST API interface for remote clients and web applications.
|
||||
|
||||
**Features:**
|
||||
- HTTP endpoints for MCP operations
|
||||
- Tool filtering (removes local-only tools)
|
||||
- CORS support for web clients
|
||||
- Remote security context (sandboxed)
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh http 8080
|
||||
```
|
||||
|
||||
**Endpoints:**
|
||||
- `GET /health` - Health check
|
||||
- `GET /mcp/capabilities` - Server capabilities and filtered tools
|
||||
- `GET /mcp/tools` - List available tools (filtered by context)
|
||||
- `POST /mcp/tools/:tool_name` - Execute specific tool
|
||||
- `POST /mcp/request` - Full MCP JSON-RPC request
|
||||
- `GET /agents` - Agent status (requires authorization)
|
||||
|
||||
### 3. WebSocket Mode
|
||||
Real-time interface for web clients requiring live updates.
|
||||
|
||||
**Features:**
|
||||
- Real-time MCP JSON-RPC over WebSocket
|
||||
- Tool filtering for remote clients
|
||||
- Session management and heartbeat
|
||||
- Automatic cleanup on disconnect
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh websocket 8081
|
||||
```
|
||||
|
||||
**Endpoint:**
|
||||
- `ws://localhost:8081/mcp/ws` - WebSocket connection
|
||||
|
||||
### 4. Remote Mode
|
||||
Both HTTP and WebSocket on the same port for complete remote access.
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh remote 8080
|
||||
```
|
||||
|
||||
### 5. All Mode
|
||||
All interface modes simultaneously for maximum compatibility.
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh all 8080
|
||||
```
|
||||
|
||||
## Tool Filtering
|
||||
|
||||
The system intelligently filters available tools based on client context:
|
||||
|
||||
### Local Clients (STDIO)
|
||||
- **Context**: Trusted, local machine
|
||||
- **Tools**: All tools available
|
||||
- **Use case**: VSCode extension, local development
|
||||
|
||||
### Remote Clients (HTTP/WebSocket)
|
||||
- **Context**: Sandboxed, remote access
|
||||
- **Tools**: Filtered to exclude local-only operations
|
||||
- **Use case**: Web applications, CI/CD, remote dashboards
|
||||
|
||||
### Tool Categories
|
||||
|
||||
**Always Available (All Contexts):**
|
||||
- Agent coordination: `register_agent`, `create_task`, `get_task_board`, `heartbeat`
|
||||
- Memory/Knowledge: `create_entities`, `read_graph`, `search_nodes`
|
||||
- Documentation: `get-library-docs`, `resolve-library-id`
|
||||
- Reasoning: `sequentialthinking`
|
||||
|
||||
**Local Only (Filtered for Remote):**
|
||||
- Filesystem: `read_file`, `write_file`, `create_file`, `delete_file`
|
||||
- VSCode: `vscode_*` tools
|
||||
- Terminal: `run_in_terminal`, `get_terminal_output`
|
||||
- System: Local file operations
|
||||
|
||||
## Configuration
|
||||
|
||||
Configuration is managed through environment variables and config files:
|
||||
|
||||
### Environment Variables
|
||||
- `MCP_INTERFACE_MODE`: Interface mode (`stdio`, `http`, `websocket`, `remote`, `all`)
|
||||
- `MCP_HTTP_PORT`: HTTP server port (default: 8080)
|
||||
- `MCP_WS_PORT`: WebSocket port (default: 8081)
|
||||
|
||||
### Configuration File
|
||||
See `mcp_interfaces_config.json` for detailed configuration options.
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Local Context (STDIO)
|
||||
- Full filesystem access
|
||||
- Trusted environment
|
||||
- No network exposure
|
||||
|
||||
### Remote Context (HTTP/WebSocket)
|
||||
- Sandboxed environment
|
||||
- Tool filtering active
|
||||
- CORS protection
|
||||
- No local file access
|
||||
|
||||
### Tool Filtering Rules
|
||||
1. **Allowlist approach**: Safe tools are explicitly allowed for remote clients
|
||||
2. **Pattern matching**: Local-only tools identified by name patterns
|
||||
3. **Schema analysis**: Tools with local-only parameters are filtered
|
||||
4. **Context-aware**: Different tool sets per connection type
|
||||
|
||||
## Client Examples
|
||||
|
||||
### HTTP Client (Python)
|
||||
```python
|
||||
import requests
|
||||
|
||||
# Get available tools
|
||||
response = requests.get("http://localhost:8080/mcp/tools")
|
||||
tools = response.json()
|
||||
|
||||
# Register an agent
|
||||
agent_data = {
|
||||
"arguments": {
|
||||
"name": "Remote Agent",
|
||||
"capabilities": ["analysis", "coordination"]
|
||||
}
|
||||
}
|
||||
response = requests.post("http://localhost:8080/mcp/tools/register_agent",
|
||||
json=agent_data)
|
||||
```
|
||||
|
||||
### WebSocket Client (JavaScript)
|
||||
```javascript
|
||||
const ws = new WebSocket('ws://localhost:8080/mcp/ws');
|
||||
|
||||
ws.onopen = () => {
|
||||
// Initialize connection
|
||||
ws.send(JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: {
|
||||
protocolVersion: "2024-11-05",
|
||||
clientInfo: { name: "web-client", version: "1.0.0" }
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
const response = JSON.parse(event.data);
|
||||
console.log('MCP Response:', response);
|
||||
};
|
||||
```
|
||||
|
||||
### VSCode MCP (Traditional)
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"agent-coordinator": {
|
||||
"command": "./scripts/mcp_launcher_multi.sh",
|
||||
"args": ["stdio"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
Run the test suite to verify all interface modes:
|
||||
|
||||
```bash
|
||||
# Start the server in remote mode
|
||||
./scripts/mcp_launcher_multi.sh remote 8080 &
|
||||
|
||||
# Run tests
|
||||
python3 scripts/test_multi_interface.py
|
||||
|
||||
# Stop the server
|
||||
kill %1
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
### VSCode Extension Development
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh stdio
|
||||
```
|
||||
Full local tool access for development workflows.
|
||||
|
||||
### Web Dashboard
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh remote 8080
|
||||
```
|
||||
Remote access with HTTP API and WebSocket for real-time updates.
|
||||
|
||||
### CI/CD Integration
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh http 8080
|
||||
```
|
||||
REST API access for automated workflows.
|
||||
|
||||
### Development/Testing
|
||||
```bash
|
||||
./scripts/mcp_launcher_multi.sh all 8080
|
||||
```
|
||||
All interfaces available for comprehensive testing.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ STDIO Client │ │ HTTP Client │ │ WebSocket Client│
|
||||
│ (VSCode) │ │ (Web/API) │ │ (Web/Real-time)│
|
||||
└─────────┬───────┘ └─────────┬───────┘ └─────────┬───────┘
|
||||
│ │ │
|
||||
│ Full Tools │ Filtered Tools │ Filtered Tools
|
||||
│ │ │
|
||||
v v v
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Interface Manager │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ STDIO │ │ HTTP │ │ WebSocket │ │
|
||||
│ │ Interface │ │ Interface │ │ Interface │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
└─────────────────────┬───────────────────────────────────────────────┘
|
||||
│
|
||||
v
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ Tool Filter │
|
||||
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
|
||||
│ │ Local Context │ │ Remote Context │ │ Web Context │ │
|
||||
│ │ (Full Access) │ │ (Sandboxed) │ │ (Restricted) │ │
|
||||
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
|
||||
└─────────────────────┬───────────────────────────────────────────────┘
|
||||
│
|
||||
v
|
||||
┌─────────────────────────────────────────────────────────────────────┐
|
||||
│ MCP Server │
|
||||
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
|
||||
│ │ Agent Registry │ │ Task Manager │ │ External MCPs │ │
|
||||
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Flexible Deployment**: Choose the right interface for your use case
|
||||
2. **Security**: Automatic tool filtering prevents unauthorized local access
|
||||
3. **Scalability**: HTTP/WebSocket interfaces support multiple concurrent clients
|
||||
4. **Backward Compatibility**: STDIO mode maintains compatibility with existing tools
|
||||
5. **Real-time Capability**: WebSocket enables live updates and notifications
|
||||
6. **Developer Experience**: Consistent MCP protocol across all interfaces
|
||||
|
||||
The multi-interface system allows the Agent Coordinator to serve both local development workflows and remote/web applications while maintaining security and appropriate tool access levels.
|
||||
@@ -1,121 +0,0 @@
|
||||
# Agent Coordinator - Project Cleanup Summary
|
||||
|
||||
## 🎯 Mission Accomplished
|
||||
|
||||
The Agent Coordinator project has been successfully tidied up and made much more presentable for GitHub! Here's what was accomplished:
|
||||
|
||||
## ✅ Completed Tasks
|
||||
|
||||
### 1. **Updated README.md** ✨
|
||||
- **Before**: Outdated README that didn't accurately describe the project
|
||||
- **After**: Comprehensive, clear README that properly explains:
|
||||
- What Agent Coordinator actually does (MCP server for multi-agent coordination)
|
||||
- Key features and benefits
|
||||
- Quick start guide with practical examples
|
||||
- Clear architecture diagram
|
||||
- Proper project structure documentation
|
||||
- Alternative language implementation recommendations
|
||||
|
||||
### 2. **Cleaned Up Outdated Files** 🗑️
|
||||
- **Removed**: `test_enhanced.exs`, `test_multi_codebase.exs`, `test_timeout_fix.exs`
|
||||
- **Removed**: `README_old.md` (outdated version)
|
||||
- **Removed**: Development artifacts (`erl_crash.dump`, `firebase-debug.log`)
|
||||
- **Updated**: `.gitignore` to prevent future development artifacts
|
||||
|
||||
### 3. **Organized Documentation Structure** 📚
|
||||
- **Created**: `docs/` directory for technical documentation
|
||||
- **Moved**: Technical deep-dive documents to `docs/`
|
||||
- `AUTO_HEARTBEAT.md` - Unified MCP server architecture
|
||||
- `VSCODE_TOOL_INTEGRATION.md` - VS Code integration details
|
||||
- `SEARCH_FILES_TIMEOUT_FIX.md` - Technical timeout solutions
|
||||
- `DYNAMIC_TOOL_DISCOVERY.md` - Dynamic tool discovery system
|
||||
- **Created**: `docs/README.md` - Documentation index and navigation
|
||||
- **Result**: Clean root directory with organized technical docs
|
||||
|
||||
### 4. **Improved Project Structure** 🏗️
|
||||
- **Updated**: Main `AgentCoordinator` module to reflect actual functionality
|
||||
- **Before**: Just a placeholder "hello world" function
|
||||
- **After**: Comprehensive module with:
|
||||
- Proper documentation explaining the system
|
||||
- Practical API functions (`register_agent`, `create_task`, `get_task_board`)
|
||||
- Version and status information
|
||||
- Real examples and usage patterns
|
||||
|
||||
### 5. **Created Language Implementation Guide** 🚀
|
||||
- **New Document**: `docs/LANGUAGE_IMPLEMENTATIONS.md`
|
||||
- **Comprehensive guide** for implementing Agent Coordinator in more accessible languages:
|
||||
- **Go** (highest priority) - Single binary deployment, excellent concurrency
|
||||
- **Python** (second priority) - Huge AI/ML community, familiar ecosystem
|
||||
- **Rust** (third priority) - Maximum performance, memory safety
|
||||
- **Node.js** (fourth priority) - Event-driven, web developer familiarity
|
||||
- **Detailed implementation strategies** with code examples
|
||||
- **Migration guides** for moving from Elixir to other languages
|
||||
- **Performance comparisons** and adoption recommendations
|
||||
|
||||
## 🎨 Project Before vs After
|
||||
|
||||
### Before Cleanup
|
||||
- ❌ Confusing README that didn't explain the actual purpose
|
||||
- ❌ Development artifacts scattered in root directory
|
||||
- ❌ Technical documentation mixed with main docs
|
||||
- ❌ Main module was just a placeholder
|
||||
- ❌ No guidance for developers wanting to use other languages
|
||||
|
||||
### After Cleanup
|
||||
- ✅ Clear, comprehensive README explaining the MCP coordination system
|
||||
- ✅ Clean root directory with organized structure
|
||||
- ✅ Technical docs properly organized in `docs/` directory
|
||||
- ✅ Main module reflects actual project functionality
|
||||
- ✅ Detailed guides for implementing in Go, Python, Rust, Node.js
|
||||
- ✅ Professional presentation suitable for open source
|
||||
|
||||
## 🌟 Key Improvements for GitHub Presentation
|
||||
|
||||
1. **Clear Value Proposition**: README immediately explains what the project does and why it's valuable
|
||||
2. **Easy Getting Started**: Quick start section gets users running in minutes
|
||||
3. **Professional Structure**: Well-organized directories and documentation
|
||||
4. **Multiple Language Options**: Guidance for teams that prefer Go, Python, Rust, or Node.js
|
||||
5. **Technical Deep-Dives**: Detailed docs for developers who want to understand the internals
|
||||
6. **Real Examples**: Working code examples and practical usage patterns
|
||||
|
||||
## 🚀 Recommendations for Broader Adoption
|
||||
|
||||
Based on the cleanup analysis, here are the top recommendations:
|
||||
|
||||
### 1. **Implement Go Version First** (Highest Impact)
|
||||
- **Why**: Single binary deployment, familiar to most developers, excellent performance
|
||||
- **Effort**: 2-3 weeks development time
|
||||
- **Impact**: Would significantly increase adoption
|
||||
|
||||
### 2. **Python Version Second** (AI/ML Community)
|
||||
- **Why**: Huge ecosystem in AI space, very familiar to ML engineers
|
||||
- **Effort**: 3-4 weeks development time
|
||||
- **Impact**: Perfect for AI agent development teams
|
||||
|
||||
### 3. **Create Video Demos**
|
||||
- **What**: Screen recordings showing agent coordination in action
|
||||
- **Why**: Much easier to understand the value than reading docs
|
||||
- **Effort**: 1-2 days
|
||||
- **Impact**: Increases GitHub star rate and adoption
|
||||
|
||||
### 4. **Docker Compose Quick Start**
|
||||
- **What**: Single `docker-compose up` command to get everything running
|
||||
- **Why**: Eliminates setup friction for trying the project
|
||||
- **Effort**: 1 day
|
||||
- **Impact**: Lower barrier to entry
|
||||
|
||||
## 🎯 Current State
|
||||
|
||||
The Agent Coordinator project is now:
|
||||
|
||||
- ✅ **Professional**: Clean, well-organized, and properly documented
|
||||
- ✅ **Accessible**: Clear explanations for what it does and how to use it
|
||||
- ✅ **Extensible**: Guidance for implementing in other languages
|
||||
- ✅ **Developer-Friendly**: Good project structure and documentation organization
|
||||
- ✅ **GitHub-Ready**: Perfect for open source presentation and community adoption
|
||||
|
||||
The Elixir implementation remains the reference implementation with all advanced features, while the documentation now provides clear paths for teams to implement the same concepts in their preferred languages.
|
||||
|
||||
---
|
||||
|
||||
**Result**: The Agent Coordinator project is now much more approachable and ready for the world to enjoy! 🌍
|
||||
@@ -1,77 +0,0 @@
|
||||
# Agent Coordinator Documentation
|
||||
|
||||
This directory contains detailed technical documentation for the Agent Coordinator project.
|
||||
|
||||
## 📚 Documentation Index
|
||||
|
||||
### Core Documentation
|
||||
- [Main README](../README.md) - Project overview, setup, and basic usage
|
||||
- [CHANGELOG](../CHANGELOG.md) - Version history and changes
|
||||
- [CONTRIBUTING](../CONTRIBUTING.md) - How to contribute to the project
|
||||
|
||||
### Technical Deep Dives
|
||||
|
||||
#### Architecture & Design
|
||||
- [AUTO_HEARTBEAT.md](AUTO_HEARTBEAT.md) - Unified MCP server with automatic task tracking and heartbeat system
|
||||
- [VSCODE_TOOL_INTEGRATION.md](VSCODE_TOOL_INTEGRATION.md) - VS Code tool integration and dynamic tool discovery
|
||||
- [DYNAMIC_TOOL_DISCOVERY.md](DYNAMIC_TOOL_DISCOVERY.md) - How the system dynamically discovers and manages MCP tools
|
||||
|
||||
#### Implementation Details
|
||||
- [SEARCH_FILES_TIMEOUT_FIX.md](SEARCH_FILES_TIMEOUT_FIX.md) - Technical details on timeout handling and GenServer call optimization
|
||||
|
||||
## 🎯 Key Concepts
|
||||
|
||||
### Agent Coordination
|
||||
The Agent Coordinator is an MCP server that enables multiple AI agents to work together without conflicts by:
|
||||
|
||||
- **Task Distribution**: Automatically assigns tasks based on agent capabilities
|
||||
- **Heartbeat Management**: Tracks agent liveness and activity
|
||||
- **Cross-Codebase Support**: Coordinates work across multiple repositories
|
||||
- **Tool Unification**: Provides a single interface to multiple external MCP servers
|
||||
|
||||
### Unified MCP Server
|
||||
The system acts as a unified MCP server that internally manages external MCP servers while providing:
|
||||
|
||||
- **Automatic Task Tracking**: Every tool usage becomes a tracked task
|
||||
- **Universal Heartbeat Coverage**: All operations maintain agent liveness
|
||||
- **Dynamic Tool Discovery**: Automatically discovers tools from external servers
|
||||
- **Seamless Integration**: Single interface for all MCP-compatible tools
|
||||
|
||||
### VS Code Integration
|
||||
Advanced integration with VS Code through:
|
||||
|
||||
- **Native Tool Provider**: Direct access to VS Code Extension API
|
||||
- **Permission System**: Granular security controls for VS Code operations
|
||||
- **Multi-Agent Support**: Safe concurrent access to VS Code features
|
||||
- **Workflow Integration**: VS Code tools participate in task coordination
|
||||
|
||||
## 🚀 Getting Started with Documentation
|
||||
|
||||
1. **New Users**: Start with the [Main README](../README.md)
|
||||
2. **Developers**: Read [CONTRIBUTING](../CONTRIBUTING.md) and [AUTO_HEARTBEAT.md](AUTO_HEARTBEAT.md)
|
||||
3. **VS Code Users**: Check out [VSCODE_TOOL_INTEGRATION.md](VSCODE_TOOL_INTEGRATION.md)
|
||||
4. **Troubleshooting**: See [SEARCH_FILES_TIMEOUT_FIX.md](SEARCH_FILES_TIMEOUT_FIX.md) for common issues
|
||||
|
||||
## 📖 Documentation Standards
|
||||
|
||||
All documentation in this project follows these standards:
|
||||
|
||||
- **Clear Structure**: Hierarchical headings with descriptive titles
|
||||
- **Code Examples**: Practical examples with expected outputs
|
||||
- **Troubleshooting**: Common issues and their solutions
|
||||
- **Implementation Details**: Technical specifics for developers
|
||||
- **User Perspective**: Both end-user and developer viewpoints
|
||||
|
||||
## 🤝 Contributing to Documentation
|
||||
|
||||
When adding new documentation:
|
||||
|
||||
1. Place technical deep-dives in this `docs/` directory
|
||||
2. Update this index file to reference new documents
|
||||
3. Keep the main README focused on getting started
|
||||
4. Include practical examples and troubleshooting sections
|
||||
5. Use clear, descriptive headings and consistent formatting
|
||||
|
||||
---
|
||||
|
||||
📝 **Last Updated**: August 25, 2025
|
||||
@@ -1,89 +0,0 @@
|
||||
# Search Files Timeout Fix
|
||||
|
||||
## Problem Description
|
||||
|
||||
The `search_files` tool (from the filesystem MCP server) was causing the agent-coordinator to exit with code 1 due to timeout issues. The error showed:
|
||||
|
||||
```
|
||||
** (EXIT from #PID<0.95.0>) exited in: GenServer.call(AgentCoordinator.UnifiedMCPServer, {:handle_request, ...}, 5000)
|
||||
** (EXIT) time out
|
||||
```
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
The issue was a timeout mismatch in the GenServer call chain:
|
||||
|
||||
1. **External tool calls** (like `search_files`) can take longer than 5 seconds to complete
|
||||
2. **TaskRegistry and Inbox modules** were using default 5-second GenServer timeouts
|
||||
3. During tool execution, **heartbeat operations** are called via `TaskRegistry.heartbeat_agent/1`
|
||||
4. When the external tool took longer than 5 seconds, the heartbeat call would timeout
|
||||
5. This caused the entire tool call to fail with exit code 1
|
||||
|
||||
## Call Chain Analysis
|
||||
|
||||
```
|
||||
External MCP Tool Call (search_files)
|
||||
↓
|
||||
UnifiedMCPServer.handle_mcp_request (60s timeout) ✓
|
||||
↓
|
||||
MCPServerManager.route_tool_call (60s timeout) ✓
|
||||
↓
|
||||
call_external_tool
|
||||
↓
|
||||
TaskRegistry.heartbeat_agent (5s timeout) ❌ ← TIMEOUT HERE
|
||||
```
|
||||
|
||||
## Solution Applied
|
||||
|
||||
Updated GenServer call timeouts in the following modules:
|
||||
|
||||
### TaskRegistry Module
|
||||
- `register_agent/1`: 5s → 30s
|
||||
- `heartbeat_agent/1`: 5s → 30s ← **Most Critical Fix**
|
||||
- `update_task_activity/3`: 5s → 30s
|
||||
- `assign_task/1`: 5s → 30s
|
||||
- `create_task/3`: 5s → 30s
|
||||
- `complete_task/1`: 5s → 30s
|
||||
- `get_agent_current_task/1`: 5s → 15s
|
||||
|
||||
### Inbox Module
|
||||
- `add_task/2`: 5s → 30s
|
||||
- `complete_current_task/1`: 5s → 30s
|
||||
- `get_next_task/1`: 5s → 15s
|
||||
- `get_status/1`: 5s → 15s
|
||||
- `list_tasks/1`: 5s → 15s
|
||||
- `get_current_task/1`: 5s → 15s
|
||||
|
||||
## Timeout Strategy
|
||||
|
||||
- **Long operations** (registration, task creation, heartbeat): **30 seconds**
|
||||
- **Read operations** (status, get tasks, list): **15 seconds**
|
||||
- **External tool routing**: **60 seconds** (already correct)
|
||||
|
||||
## Impact
|
||||
|
||||
This fix ensures that:
|
||||
|
||||
1. ✅ `search_files` and other long-running external tools won't cause timeouts
|
||||
2. ✅ Agent heartbeat operations can complete successfully during tool execution
|
||||
3. ✅ The agent-coordinator won't exit with code 1 due to timeout issues
|
||||
4. ✅ All automatic task tracking continues to work properly
|
||||
|
||||
## Files Modified
|
||||
|
||||
- `/lib/agent_coordinator/task_registry.ex` - Updated GenServer call timeouts
|
||||
- `/lib/agent_coordinator/inbox.ex` - Updated GenServer call timeouts
|
||||
|
||||
## Verification
|
||||
|
||||
The fix can be verified by:
|
||||
|
||||
1. Running the agent-coordinator with external MCP servers
|
||||
2. Executing `search_files` or other filesystem tools on large directories
|
||||
3. Confirming no timeout errors occur and exit code remains 0
|
||||
|
||||
## Future Considerations
|
||||
|
||||
- Consider making timeouts configurable via application config
|
||||
- Monitor for any other GenServer calls that might need timeout adjustments
|
||||
- Add timeout logging to help identify future timeout issues
|
||||
@@ -1,441 +0,0 @@
|
||||
# VS Code Tool Integration with Agent Coordinator
|
||||
|
||||
## 🎉 Latest Update: Dynamic Tool Discovery (COMPLETED)
|
||||
|
||||
**Date**: August 23, 2025
|
||||
**Status**: ✅ **COMPLETED** - Full dynamic tool discovery implementation
|
||||
|
||||
### What Changed
|
||||
The Agent Coordinator has been refactored to eliminate all hardcoded tool lists and implement **fully dynamic tool discovery** following the MCP protocol specification.
|
||||
|
||||
**Key Improvements**:
|
||||
- ✅ **No hardcoded tools**: All external server tools discovered via MCP `tools/list`
|
||||
- ✅ **Conditional VS Code tools**: Only included when VS Code functionality is available
|
||||
- ✅ **Real-time refresh**: `refresh_tools()` function to rediscover tools on demand
|
||||
- ✅ **Perfect MCP compliance**: Follows protocol specification exactly
|
||||
- ✅ **Better error handling**: Proper handling of both PIDs and Ports for server monitoring
|
||||
|
||||
**Example Tool Discovery Results**:
|
||||
```
|
||||
Found 44 total tools:
|
||||
• Coordinator tools: 6 (register_agent, create_task, etc.)
|
||||
• External MCP tools: 26+ (context7, filesystem, memory, sequential thinking)
|
||||
• VS Code tools: 12 (when available)
|
||||
```
|
||||
|
||||
### Benefits
|
||||
1. **MCP Protocol Compliance**: Perfect adherence to MCP specification
|
||||
2. **Flexibility**: New MCP servers can be added without code changes
|
||||
3. **Reliability**: Tools automatically discovered when servers restart
|
||||
4. **Performance**: Only available tools are included in routing
|
||||
5. **Debugging**: Clear visibility into which tools are available
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
This document outlines the implementation of VS Code's built-in tools as MCP (Model Context Protocol) tools within the Agent Coordinator system. This integration allows agents to access VS Code's native capabilities alongside external MCP servers through a unified coordination interface.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Current State
|
||||
- Agent Coordinator acts as a unified MCP server
|
||||
- Proxies tools from external MCP servers (Context7, filesystem, memory, sequential thinking, etc.)
|
||||
- Manages task coordination, agent assignment, and cross-codebase workflows
|
||||
|
||||
### Proposed Enhancement
|
||||
- Add VS Code Extension API tools as native MCP tools
|
||||
- Integrate with existing tool routing and coordination system
|
||||
- Maintain security and permission controls
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
### Phase 1: Core VS Code Tool Provider
|
||||
|
||||
#### 1.1 Create VSCodeToolProvider Module
|
||||
**File**: `lib/agent_coordinator/vscode_tool_provider.ex`
|
||||
|
||||
**Core Tools to Implement**:
|
||||
- `vscode_read_file` - Read file contents using VS Code API
|
||||
- `vscode_write_file` - Write file contents
|
||||
- `vscode_create_file` - Create new files
|
||||
- `vscode_delete_file` - Delete files
|
||||
- `vscode_list_directory` - List directory contents
|
||||
- `vscode_get_workspace_folders` - Get workspace information
|
||||
- `vscode_run_command` - Execute VS Code commands
|
||||
- `vscode_get_active_editor` - Get current editor state
|
||||
- `vscode_set_editor_content` - Modify editor content
|
||||
- `vscode_get_selection` - Get current text selection
|
||||
- `vscode_set_selection` - Set text selection
|
||||
- `vscode_show_message` - Display messages to user
|
||||
|
||||
#### 1.2 Tool Definitions
|
||||
Each tool will have:
|
||||
- MCP-compliant schema definition
|
||||
- Input validation
|
||||
- Error handling
|
||||
- Audit logging
|
||||
- Permission checking
|
||||
|
||||
### Phase 2: Advanced Editor Operations
|
||||
|
||||
#### 2.1 Language Services Integration
|
||||
- `vscode_get_diagnostics` - Get language server diagnostics
|
||||
- `vscode_format_document` - Format current document
|
||||
- `vscode_format_selection` - Format selected text
|
||||
- `vscode_find_references` - Find symbol references
|
||||
- `vscode_go_to_definition` - Navigate to definition
|
||||
- `vscode_rename_symbol` - Rename symbols
|
||||
- `vscode_code_actions` - Get available code actions
|
||||
|
||||
#### 2.2 Search and Navigation
|
||||
- `vscode_find_in_files` - Search across workspace
|
||||
- `vscode_find_symbols` - Find symbols in workspace
|
||||
- `vscode_goto_line` - Navigate to specific line
|
||||
- `vscode_reveal_in_explorer` - Show file in explorer
|
||||
|
||||
### Phase 3: Terminal and Process Management
|
||||
|
||||
#### 3.1 Terminal Operations
|
||||
- `vscode_create_terminal` - Create new terminal
|
||||
- `vscode_send_to_terminal` - Send commands to terminal
|
||||
- `vscode_get_terminal_output` - Get terminal output (if possible)
|
||||
- `vscode_close_terminal` - Close terminal instances
|
||||
|
||||
#### 3.2 Task and Process Management
|
||||
- `vscode_run_task` - Execute VS Code tasks
|
||||
- `vscode_get_tasks` - List available tasks
|
||||
- `vscode_debug_start` - Start debugging session
|
||||
- `vscode_debug_stop` - Stop debugging
|
||||
|
||||
### Phase 4: Git and Version Control
|
||||
|
||||
#### 4.1 Git Operations
|
||||
- `vscode_git_status` - Get git status
|
||||
- `vscode_git_commit` - Create commits
|
||||
- `vscode_git_push` - Push changes
|
||||
- `vscode_git_pull` - Pull changes
|
||||
- `vscode_git_branch` - Branch operations
|
||||
- `vscode_git_diff` - Get file differences
|
||||
|
||||
### Phase 5: Extension and Settings Management
|
||||
|
||||
#### 5.1 Configuration
|
||||
- `vscode_get_settings` - Get VS Code settings
|
||||
- `vscode_update_settings` - Update settings
|
||||
- `vscode_get_extensions` - List installed extensions
|
||||
- `vscode_install_extension` - Install extensions (if permitted)
|
||||
|
||||
## Security and Safety
|
||||
|
||||
### Permission Model
|
||||
```elixir
|
||||
defmodule AgentCoordinator.VSCodePermissions do
|
||||
@moduledoc """
|
||||
Manages permissions for VS Code tool access.
|
||||
"""
|
||||
|
||||
# Permission levels:
|
||||
# :read_only - File reading, workspace inspection
|
||||
# :editor - Text editing, selections
|
||||
# :filesystem - File creation/deletion
|
||||
# :terminal - Terminal access
|
||||
# :git - Version control operations
|
||||
# :admin - Settings, extensions, system commands
|
||||
end
|
||||
```
|
||||
|
||||
### Sandboxing
|
||||
- Restrict file operations to workspace folders only
|
||||
- Prevent access to system files outside workspace
|
||||
- Rate limiting for expensive operations
|
||||
- Command whitelist for `vscode_run_command`
|
||||
|
||||
### Audit Logging
|
||||
- Log all VS Code tool calls with:
|
||||
- Timestamp
|
||||
- Agent ID
|
||||
- Tool name and parameters
|
||||
- Result summary
|
||||
- Permission level used
|
||||
|
||||
## Integration Points
|
||||
|
||||
### 1. UnifiedMCPServer Enhancement
|
||||
**File**: `lib/agent_coordinator/unified_mcp_server.ex`
|
||||
|
||||
Add VS Code tools to the tool discovery and routing:
|
||||
|
||||
```elixir
|
||||
defp get_all_tools(state) do
|
||||
# Existing external MCP server tools
|
||||
external_tools = get_external_tools(state)
|
||||
|
||||
# New VS Code tools
|
||||
vscode_tools = VSCodeToolProvider.get_tools()
|
||||
|
||||
external_tools ++ vscode_tools
|
||||
end
|
||||
|
||||
defp route_tool_call(tool_name, args, context, state) do
|
||||
case tool_name do
|
||||
"vscode_" <> _rest ->
|
||||
VSCodeToolProvider.handle_tool_call(tool_name, args, context)
|
||||
_ ->
|
||||
# Route to external MCP servers
|
||||
route_to_external_server(tool_name, args, context, state)
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
### 2. Task Coordination
|
||||
VS Code tools will participate in the same task coordination system:
|
||||
- Task creation and assignment
|
||||
- File locking (prevent conflicts)
|
||||
- Cross-agent coordination
|
||||
- Priority management
|
||||
|
||||
### 3. Agent Capabilities
|
||||
Agents can declare VS Code tool capabilities:
|
||||
```elixir
|
||||
capabilities: [
|
||||
"coding",
|
||||
"analysis",
|
||||
"vscode_editing",
|
||||
"vscode_terminal",
|
||||
"vscode_git"
|
||||
]
|
||||
```
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Example 1: File Analysis and Editing
|
||||
```json
|
||||
{
|
||||
"tool": "vscode_read_file",
|
||||
"args": {"path": "src/main.rs"}
|
||||
}
|
||||
// Agent reads file, analyzes it
|
||||
|
||||
{
|
||||
"tool": "vscode_get_diagnostics",
|
||||
"args": {"file": "src/main.rs"}
|
||||
}
|
||||
// Agent gets compiler errors
|
||||
|
||||
{
|
||||
"tool": "vscode_set_editor_content",
|
||||
"args": {
|
||||
"file": "src/main.rs",
|
||||
"content": "// Fixed code here",
|
||||
"range": {"start": 10, "end": 15}
|
||||
}
|
||||
}
|
||||
// Agent fixes the issues
|
||||
```
|
||||
|
||||
### Example 2: Cross-Tool Workflow
|
||||
```json
|
||||
// 1. Agent searches documentation using Context7
|
||||
{"tool": "mcp_context7_get-library-docs", "args": {"libraryID": "/rust/std"}}
|
||||
|
||||
// 2. Agent analyzes current code using VS Code
|
||||
{"tool": "vscode_get_active_editor", "args": {}}
|
||||
|
||||
// 3. Agent applies documentation insights to code
|
||||
{"tool": "vscode_format_document", "args": {}}
|
||||
{"tool": "vscode_set_editor_content", "args": {...}}
|
||||
|
||||
// 4. Agent commits changes using VS Code Git
|
||||
{"tool": "vscode_git_commit", "args": {"message": "Applied best practices from docs"}}
|
||||
```
|
||||
|
||||
## Benefits
|
||||
|
||||
1. **Unified Tool Access**: Agents access both external services and VS Code features through same interface
|
||||
2. **Enhanced Capabilities**: Complex workflows combining external data with direct IDE manipulation
|
||||
3. **Consistent Coordination**: Same task management for all tool types
|
||||
4. **Security**: Controlled access to powerful VS Code features
|
||||
5. **Extensibility**: Easy to add new VS Code capabilities as needs arise
|
||||
|
||||
## Implementation Status & Updated Roadmap
|
||||
|
||||
### ✅ **COMPLETED - Phase 1: Core VS Code Tool Provider (August 23, 2025)**
|
||||
|
||||
**Successfully Implemented & Tested:**
|
||||
|
||||
- ✅ VSCodeToolProvider module with 12 core tools
|
||||
- ✅ VSCodePermissions system with 6 permission levels
|
||||
- ✅ Integration with UnifiedMCPServer tool discovery and routing
|
||||
- ✅ Security controls: path sandboxing, command whitelisting, audit logging
|
||||
- ✅ Agent coordination integration (tasks, assignments, coordination)
|
||||
|
||||
**Working Tools:**
|
||||
|
||||
- ✅ File Operations: `vscode_read_file`, `vscode_write_file`, `vscode_create_file`, `vscode_delete_file`, `vscode_list_directory`
|
||||
- ✅ Editor Operations: `vscode_get_active_editor`, `vscode_set_editor_content`, `vscode_get_selection`, `vscode_set_selection`
|
||||
- ✅ Commands: `vscode_run_command`, `vscode_show_message`
|
||||
- ✅ Workspace: `vscode_get_workspace_folders`
|
||||
|
||||
**Key Achievement:** VS Code tools now work seamlessly alongside external MCP servers through unified agent coordination!
|
||||
|
||||
### 🔄 **CURRENT PRIORITY - Phase 1.5: VS Code Extension API Bridge**
|
||||
|
||||
**Status:** Tools currently return placeholder data. Need to implement actual VS Code Extension API calls.
|
||||
|
||||
**Implementation Steps:**
|
||||
|
||||
1. **JavaScript Bridge Module** - Create communication layer between Elixir and VS Code Extension API
|
||||
2. **Real API Integration** - Replace placeholder responses with actual VS Code API calls
|
||||
3. **Error Handling** - Robust error handling for VS Code API failures
|
||||
4. **Testing** - Verify all tools work with real VS Code operations
|
||||
|
||||
**Target Completion:** Next 2-3 days
|
||||
|
||||
### 📅 **UPDATED IMPLEMENTATION TIMELINE**
|
||||
|
||||
#### **Phase 2: Language Services & Advanced Editor Operations (Priority: High)**
|
||||
|
||||
**Target:** Week of August 26, 2025
|
||||
|
||||
**Tools to Implement:**
|
||||
|
||||
- `vscode_get_diagnostics` - Get language server diagnostics
|
||||
- `vscode_format_document` - Format current document
|
||||
- `vscode_format_selection` - Format selected text
|
||||
- `vscode_find_references` - Find symbol references
|
||||
- `vscode_go_to_definition` - Navigate to definition
|
||||
- `vscode_rename_symbol` - Rename symbols across workspace
|
||||
- `vscode_code_actions` - Get available code actions
|
||||
- `vscode_apply_code_action` - Apply specific code action
|
||||
|
||||
**Value:** Enables agents to perform intelligent code analysis and refactoring
|
||||
|
||||
#### **Phase 3: Search, Navigation & Workspace Management (Priority: Medium)**
|
||||
|
||||
**Target:** Week of September 2, 2025
|
||||
|
||||
**Tools to Implement:**
|
||||
|
||||
- `vscode_find_in_files` - Search across workspace with regex support
|
||||
- `vscode_find_symbols` - Find symbols in workspace
|
||||
- `vscode_goto_line` - Navigate to specific line/column
|
||||
- `vscode_reveal_in_explorer` - Show file in explorer
|
||||
- `vscode_open_folder` - Open workspace folder
|
||||
- `vscode_close_folder` - Close workspace folder
|
||||
- `vscode_switch_editor_tab` - Switch between open files
|
||||
|
||||
**Value:** Enables agents to navigate and understand large codebases
|
||||
|
||||
#### **Phase 4: Terminal & Process Management (Priority: Medium)**
|
||||
|
||||
**Target:** Week of September 9, 2025
|
||||
|
||||
**Tools to Implement:**
|
||||
|
||||
- `vscode_create_terminal` - Create new terminal instance
|
||||
- `vscode_send_to_terminal` - Send commands to terminal
|
||||
- `vscode_get_terminal_output` - Get terminal output (if possible via API)
|
||||
- `vscode_close_terminal` - Close terminal instances
|
||||
- `vscode_run_task` - Execute VS Code tasks (build, test, etc.)
|
||||
- `vscode_get_tasks` - List available tasks
|
||||
- `vscode_stop_task` - Stop running task
|
||||
|
||||
**Value:** Enables agents to manage build processes and execute commands
|
||||
|
||||
#### **Phase 5: Git & Version Control Integration (Priority: High)**
|
||||
|
||||
**Target:** Week of September 16, 2025
|
||||
|
||||
**Tools to Implement:**
|
||||
|
||||
- `vscode_git_status` - Get repository status
|
||||
- `vscode_git_commit` - Create commits with messages
|
||||
- `vscode_git_push` - Push changes to remote
|
||||
- `vscode_git_pull` - Pull changes from remote
|
||||
- `vscode_git_branch` - Branch operations (create, switch, delete)
|
||||
- `vscode_git_diff` - Get file differences
|
||||
- `vscode_git_stage` - Stage/unstage files
|
||||
- `vscode_git_blame` - Get blame information
|
||||
|
||||
**Value:** Enables agents to manage version control workflows
|
||||
|
||||
#### **Phase 6: Advanced Features & Extension Management (Priority: Low)**
|
||||
|
||||
**Target:** Week of September 23, 2025
|
||||
|
||||
**Tools to Implement:**
|
||||
|
||||
- `vscode_get_settings` - Get VS Code settings
|
||||
- `vscode_update_settings` - Update settings
|
||||
- `vscode_get_extensions` - List installed extensions
|
||||
- `vscode_install_extension` - Install extensions (if permitted)
|
||||
- `vscode_debug_start` - Start debugging session
|
||||
- `vscode_debug_stop` - Stop debugging
|
||||
- `vscode_set_breakpoint` - Set/remove breakpoints
|
||||
|
||||
**Value:** Complete IDE automation capabilities
|
||||
|
||||
### 🚀 **Key Insights from Phase 1**
|
||||
|
||||
1. **Integration Success**: The MCP tool routing system works perfectly for VS Code tools
|
||||
2. **Permission System**: Granular permissions are essential for security
|
||||
3. **Agent Coordination**: VS Code tools integrate seamlessly with task management
|
||||
4. **Unified Experience**: Agents can now use external services + VS Code through same interface
|
||||
|
||||
### 🎯 **Next Immediate Actions**
|
||||
|
||||
1. **Priority 1**: Implement proper agent identification system for multi-agent scenarios
|
||||
2. **Priority 2**: Implement real VS Code Extension API bridge (replace placeholders)
|
||||
3. **Priority 3**: Add Phase 2 language services tools
|
||||
4. **Priority 4**: Create comprehensive testing suite
|
||||
5. **Priority 5**: Document usage patterns and best practices
|
||||
|
||||
### 🔧 **Critical Enhancement: Multi-Agent Identification System**
|
||||
|
||||
**Problem:** Current system treats all GitHub Copilot instances as the same agent, causing conflicts in multi-agent scenarios.
|
||||
|
||||
**Solution:** Implement unique agent identification with session-based tracking.
|
||||
|
||||
**Implementation Requirements:**
|
||||
|
||||
1. **Agent ID Parameter**: All tools must include an `agent_id` parameter
|
||||
2. **Session-Based Registration**: Each chat session/agent instance gets unique ID
|
||||
3. **Tool Schema Updates**: Add `agent_id` to all VS Code tool schemas
|
||||
4. **Auto-Registration**: System automatically creates unique agents per session
|
||||
5. **Agent Isolation**: Tasks, permissions, and state isolated per agent ID
|
||||
|
||||
**Benefits:**
|
||||
|
||||
- Multiple agents can work simultaneously without conflicts
|
||||
- Individual agent permissions and capabilities
|
||||
- Proper task assignment and coordination
|
||||
- Clear audit trails per agent
|
||||
|
||||
### 📊 **Success Metrics**
|
||||
|
||||
- **Tool Reliability**: >95% success rate for all VS Code tool calls
|
||||
- **Performance**: <500ms average response time for VS Code operations
|
||||
- **Security**: Zero security incidents with workspace sandboxing
|
||||
- **Integration**: All tools work seamlessly with agent coordination system
|
||||
- **Adoption**: Agents can complete full development workflows using only coordinated tools## Testing Strategy
|
||||
|
||||
1. **Unit Tests**: Each VS Code tool function
|
||||
2. **Integration Tests**: Tool coordination and routing
|
||||
3. **Security Tests**: Permission enforcement and sandboxing
|
||||
4. **Performance Tests**: Rate limiting and resource usage
|
||||
5. **User Acceptance**: Real workflow testing with multiple agents
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
- **Extension-specific Tools**: Tools for specific VS Code extensions
|
||||
- **Collaborative Features**: Multi-agent editing coordination
|
||||
- **AI-Enhanced Operations**: Intelligent code suggestions and fixes
|
||||
- **Remote Development**: Support for remote VS Code scenarios
|
||||
- **Custom Tool Creation**: Framework for users to create their own VS Code tools
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
This implementation transforms the Agent Coordinator from a simple MCP proxy into a comprehensive development environment orchestrator, enabling sophisticated AI-assisted development workflows.
|
||||
@@ -1,305 +0,0 @@
|
||||
<svg viewBox="0 0 1200 800" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs>
|
||||
<style>
|
||||
.agent-box {
|
||||
fill: #e3f2fd;
|
||||
stroke: #1976d2;
|
||||
stroke-width: 2;
|
||||
}
|
||||
.coordinator-box {
|
||||
fill: #f3e5f5;
|
||||
stroke: #7b1fa2;
|
||||
stroke-width: 3;
|
||||
}
|
||||
.component-box {
|
||||
fill: #fff3e0;
|
||||
stroke: #f57c00;
|
||||
stroke-width: 2;
|
||||
}
|
||||
.mcp-server-box {
|
||||
fill: #e8f5e8;
|
||||
stroke: #388e3c;
|
||||
stroke-width: 2;
|
||||
}
|
||||
.taskboard-box {
|
||||
fill: #fff8e1;
|
||||
stroke: #ffa000;
|
||||
stroke-width: 2;
|
||||
}
|
||||
.text {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
font-size: 12px;
|
||||
}
|
||||
.title-text {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
}
|
||||
.small-text {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
font-size: 10px;
|
||||
}
|
||||
.connection-line {
|
||||
stroke: #666;
|
||||
stroke-width: 2;
|
||||
fill: none;
|
||||
}
|
||||
.mcp-line {
|
||||
stroke: #1976d2;
|
||||
stroke-width: 3;
|
||||
fill: none;
|
||||
}
|
||||
.data-flow {
|
||||
stroke: #4caf50;
|
||||
stroke-width: 2;
|
||||
fill: none;
|
||||
stroke-dasharray: 5,5;
|
||||
}
|
||||
.text-bg {
|
||||
fill: white;
|
||||
fill-opacity: 0.9;
|
||||
stroke: #333;
|
||||
stroke-width: 1; rx: 4;
|
||||
}
|
||||
.overlay-text {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
|
||||
<!-- Arrow marker -->
|
||||
<marker id="arrowhead" markerWidth="6" markerHeight="4"
|
||||
refX="5" refY="2" orient="auto">
|
||||
<polygon points="0 0, 6 2, 0 4" fill="none" stroke="#666" stroke-width="0.01" />
|
||||
</marker>
|
||||
|
||||
<!-- MCP Arrow marker -->
|
||||
<marker id="mcpArrow" markerWidth="6" markerHeight="4"
|
||||
refX="5" refY="2" orient="auto">
|
||||
<polygon points="0 0, 6 2, 0 4" fill="#1976d2" stroke="#1976d2" stroke-width="0.01" />
|
||||
</marker>
|
||||
|
||||
<!-- Data flow arrow -->
|
||||
<marker id="dataArrow" markerWidth="6" markerHeight="4"
|
||||
refX="5" refY="2" orient="auto">
|
||||
<polygon points="0 0, 6 2, 0 4" fill="#4caf50" stroke="#4caf50" stroke-width="1" />
|
||||
</marker>
|
||||
</defs>
|
||||
|
||||
<!-- Background -->
|
||||
<rect width="1200" height="800" fill="#fafafa03" />
|
||||
|
||||
<!-- Title -->
|
||||
<text x="600" y="30" text-anchor="middle" class="title-text" font-size="18" fill="#333">
|
||||
Agent Coordinator: MCP Proxy Server Architecture
|
||||
</text>
|
||||
|
||||
<!-- AI Agents Section -->
|
||||
<text x="600" y="55" text-anchor="middle" class="text" fill="#666">
|
||||
Single MCP Interface → Multiple AI Agents → Unified Project Awareness
|
||||
</text>
|
||||
|
||||
<!-- Agent 1 -->
|
||||
<rect x="50" y="80" width="150" height="80" rx="8" class="agent-box" />
|
||||
<text x="125" y="105" text-anchor="middle" class="title-text" fill="#1976d2">Agent 1</text>
|
||||
<text x="125" y="120" text-anchor="middle" class="small-text" fill="#666">Purple Zebra</text>
|
||||
<text x="125" y="135" text-anchor="middle" class="small-text" fill="#666">Capabilities:</text>
|
||||
<text x="125" y="148" text-anchor="middle" class="small-text" fill="#666">coding, testing</text>
|
||||
|
||||
<!-- Agent 2 -->
|
||||
<rect x="250" y="80" width="150" height="80" rx="8" class="agent-box" />
|
||||
<text x="325" y="105" text-anchor="middle" class="title-text" fill="#1976d2">Agent 2</text>
|
||||
<text x="325" y="120" text-anchor="middle" class="small-text" fill="#666">Yellow Elephant</text>
|
||||
<text x="325" y="135" text-anchor="middle" class="small-text" fill="#666">Capabilities:</text>
|
||||
<text x="325" y="148" text-anchor="middle" class="small-text" fill="#666">analysis, docs</text>
|
||||
|
||||
<!-- Agent N -->
|
||||
<rect x="450" y="80" width="150" height="80" rx="8" class="agent-box" />
|
||||
<text x="525" y="105" text-anchor="middle" class="title-text" fill="#1976d2">Agent N</text>
|
||||
<text x="525" y="120" text-anchor="middle" class="small-text" fill="#666">More Agents...</text>
|
||||
<text x="525" y="135" text-anchor="middle" class="small-text" fill="#666">Dynamic</text>
|
||||
<text x="525" y="148" text-anchor="middle" class="small-text" fill="#666">Registration</text>
|
||||
|
||||
<!-- Lines from agents to coordinator (drawn first, behind text) -->
|
||||
<line x1="125" y1="160" x2="130" y2="220" class="mcp-line" marker-end="url(#mcpArrow)" />
|
||||
<line x1="325" y1="160" x2="330" y2="220" class="mcp-line" marker-end="url(#mcpArrow)" />
|
||||
<line x1="525" y1="160" x2="525" y2="220" class="mcp-line" marker-end="url(#mcpArrow)" />
|
||||
|
||||
<!-- MCP Protocol text with background (drawn on top of lines) -->
|
||||
<rect x="200" y="167" width="250" height="25" class="text-bg" />
|
||||
<text x="325" y="185" text-anchor="middle" class="overlay-text">
|
||||
MCP Protocol → Single Proxy Interface
|
||||
</text>
|
||||
|
||||
<!-- Main Coordinator Box -->
|
||||
<rect x="50" y="220" width="600" height="280" rx="12" class="coordinator-box" />
|
||||
<text x="350" y="245" text-anchor="middle" class="title-text" font-size="16">
|
||||
AGENT COORDINATOR (MCP Proxy Server)
|
||||
</text>
|
||||
<text x="350" y="255" text-anchor="middle" class="small-text" fill="#9c27b0">
|
||||
⚡ All tool calls proxy through here → Real-time agent tracking → Full project awareness
|
||||
</text>
|
||||
|
||||
<!-- Core Components Row -->
|
||||
<!-- Task Registry -->
|
||||
<rect x="70" y="260" width="160" height="100" rx="6" class="component-box" />
|
||||
<text x="150" y="280" text-anchor="middle" class="title-text" fill="#f57c00">Task Registry</text>
|
||||
<text x="150" y="298" text-anchor="middle" class="small-text" fill="#666">• Task Queuing</text>
|
||||
<text x="150" y="311" text-anchor="middle" class="small-text" fill="#666">• Agent Matching</text>
|
||||
<text x="150" y="324" text-anchor="middle" class="small-text" fill="#666">• Auto-Tracking</text>
|
||||
<text x="150" y="337" text-anchor="middle" class="small-text" fill="#666">• Progress Monitor</text>
|
||||
<text x="150" y="350" text-anchor="middle" class="small-text" fill="#666">• Conflict Prevention</text>
|
||||
|
||||
<!-- Agent Manager -->
|
||||
<rect x="250" y="260" width="160" height="100" rx="6" class="component-box" />
|
||||
<text x="330" y="280" text-anchor="middle" class="title-text" fill="#f57c00">Agent Manager</text>
|
||||
<text x="330" y="298" text-anchor="middle" class="small-text" fill="#666">• Registration</text>
|
||||
<text x="330" y="311" text-anchor="middle" class="small-text" fill="#666">• Heartbeat Monitor</text>
|
||||
<text x="330" y="324" text-anchor="middle" class="small-text" fill="#666">• Capabilities</text>
|
||||
<text x="330" y="337" text-anchor="middle" class="small-text" fill="#666">• Status Tracking</text>
|
||||
<text x="330" y="350" text-anchor="middle" class="small-text" fill="#666">• Load Balancing</text>
|
||||
|
||||
<!-- Codebase Registry -->
|
||||
<rect x="430" y="260" width="160" height="100" rx="6" class="component-box" />
|
||||
<text x="510" y="280" text-anchor="middle" class="title-text" fill="#f57c00">Codebase Registry</text>
|
||||
<text x="510" y="298" text-anchor="middle" class="small-text" fill="#666">• Cross-Repo</text>
|
||||
<text x="510" y="311" text-anchor="middle" class="small-text" fill="#666">• Dependencies</text>
|
||||
<text x="510" y="324" text-anchor="middle" class="small-text" fill="#666">• Workspace Mgmt</text>
|
||||
<text x="510" y="337" text-anchor="middle" class="small-text" fill="#666">• File Locking</text>
|
||||
<text x="510" y="350" text-anchor="middle" class="small-text" fill="#666">• Version Control</text>
|
||||
|
||||
<!-- Unified Tool Registry -->
|
||||
<rect x="70" y="380" width="520" height="100" rx="6" class="component-box" />
|
||||
<text x="330" y="400" text-anchor="middle" class="title-text" fill="#f57c00">UNIFIED TOOL REGISTRY (Proxy Layer)</text>
|
||||
<text x="330" y="415" text-anchor="middle" class="small-text" fill="#f57c00">Every tool call = Agent presence update + Task tracking + Project awareness</text>
|
||||
|
||||
<!-- Native Tools -->
|
||||
<text x="90" y="435" class="small-text" fill="#666" font-weight="bold">Native Tools:</text>
|
||||
<!-- <text x="90" y="434" class="small-text" fill="#666">register_agent, get_next_task, create_task_set,</text> -->
|
||||
<!-- <text x="90" y="448" class="small-text" fill="#666">complete_task, heartbeat, get_task_board</text> -->
|
||||
<text x="90" y="463" class="small-text" fill="#666" font-weight="bold">Proxied External Tools:</text>
|
||||
|
||||
<!-- External Tools -->
|
||||
<text x="320" y="435" class="small-text" fill="#666">register_agent, get_next_task, create_task_set,</text>
|
||||
<!-- <text x="320" y="420" class="small-text" fill="#666" font-weight="bold">External MCP Tools:</text> -->
|
||||
<text x="320" y="449" class="small-text" fill="#666">complete_task, heartbeat, get_task_board</text>
|
||||
<!-- <text x="320" y="434" class="small-text" fill="#666">read_file, write_file, search_memory,</text> -->
|
||||
<text x="320" y="463" class="small-text" fill="#666">read_file, write_file, search_memory, get_docs</text>
|
||||
|
||||
<!-- VS Code Tools -->
|
||||
<text x="90" y="477" class="small-text" fill="#666" font-weight="bold">VS Code Integration:</text>
|
||||
<text x="320" y="477" class="small-text" fill="#666">get_active_editor, set_selection, install_extension</text>
|
||||
|
||||
<!-- Task Board (Right side) -->
|
||||
<rect x="680" y="220" width="260" height="280" rx="8" class="coordinator-box"/>
|
||||
<text x="810" y="245" text-anchor="middle" class="title-text">Real-Time Task Board</text>
|
||||
|
||||
<!-- Agent Queues -->
|
||||
<rect x="700" y="260" width="100" height="80" rx="4" class="component-box"/>
|
||||
<text x="750" y="275" text-anchor="middle" class="small-text" fill="#666" font-weight="bold">Agent 1 Queue</text>
|
||||
<text x="750" y="290" text-anchor="middle" class="small-text" fill="#4caf50">✓ Task 1</text>
|
||||
<text x="750" y="303" text-anchor="middle" class="small-text" fill="#4caf50">✓ Task 2</text>
|
||||
<text x="750" y="316" text-anchor="middle" class="small-text" fill="#ff9800">→ Task 3</text>
|
||||
<text x="750" y="329" text-anchor="middle" class="small-text" fill="#666">… Task 4</text>
|
||||
|
||||
<rect x="820" y="260" width="100" height="80" rx="4" class="component-box" />
|
||||
<text x="870" y="275" text-anchor="middle" class="small-text" fill="#666" font-weight="bold">Agent 2 Queue</text>
|
||||
<text x="870" y="290" text-anchor="middle" class="small-text" fill="#4caf50">✓ Task 1</text>
|
||||
<text x="870" y="303" text-anchor="middle" class="small-text" fill="#ff9800">→ Task 2</text>
|
||||
<text x="870" y="316" text-anchor="middle" class="small-text" fill="#666">… Task 3</text>
|
||||
<text x="870" y="329" text-anchor="middle" class="small-text" fill="#666">… Task 4</text>
|
||||
|
||||
|
||||
|
||||
<!-- Agent Inboxes -->
|
||||
<rect x="700" y="360" width="100" height="60" rx="4" fill="#e3f2fd" stroke="#1976d2" stroke-width="1" />
|
||||
<text x="750" y="375" text-anchor="middle" class="small-text" fill="#1976d2" font-weight="bold">Agent 1 Inbox</text>
|
||||
<text x="750" y="390" text-anchor="middle" class="small-text" fill="#666">current: task 3</text>
|
||||
<text x="750" y="403" text-anchor="middle" class="small-text" fill="#666">[complete task]</text>
|
||||
<!-- <rect x="700" y="360" width="100" height="60" rx="4" fill="#e3f2fd" stroke="#1976d2" stroke-width="1" />
|
||||
<text x="750" y="375" text-anchor="middle" class="small-text" fill="#1976d2" font-weight="bold">Agent 1 Inbox</text>
|
||||
<text x="750" y="390" text-anchor="middle" class="small-text" fill="#666">current: task 3</text>
|
||||
<text x="750" y="403" text-anchor="middle" class="small-text" fill="#666">[complete task]</text> -->
|
||||
|
||||
<rect x="820" y="360" width="100" height="60" rx="4" fill="#e3f2fd" stroke="#1976d2" stroke-width="1" />
|
||||
<text x="870" y="375" text-anchor="middle" class="small-text" fill="#1976d2" font-weight="bold">Agent 2 Inbox</text>
|
||||
<text x="870" y="390" text-anchor="middle" class="small-text" fill="#666">current: task 2</text>
|
||||
<text x="870" y="403" text-anchor="middle" class="small-text" fill="#666">[complete task]</text>
|
||||
|
||||
<!-- Connection lines from coordinator to external servers (drawn first, behind text) -->
|
||||
<line x1="350" y1="500" x2="110" y2="550" class="connection-line" marker-end="url(#arrowhead)" />
|
||||
<line x1="350" y1="500" x2="250" y2="550" class="connection-line" marker-end="url(#arrowhead)" />
|
||||
<line x1="350" y1="500" x2="390" y2="550" class="connection-line" marker-end="url(#arrowhead)" />
|
||||
<line x1="350" y1="500" x2="530" y2="550" class="connection-line" marker-end="url(#arrowhead)" />
|
||||
|
||||
<!-- Data flow line to task board (drawn first, behind text) -->
|
||||
<line x1="650" y1="350" x2="680" y2="350" class="data-flow" marker-end="url(#dataArrow)" />
|
||||
|
||||
<!-- PROXY arrows showing reverse direction - tools flow UP through coordinator -->
|
||||
<line x1="110" y1="550" x2="330" y2="500" class="mcp-line" marker-end="url(#mcpArrow)" stroke-dasharray="3,3" />
|
||||
<line x1="250" y1="550" x2="340" y2="500" class="mcp-line" marker-end="url(#mcpArrow)" stroke-dasharray="3,3" />
|
||||
<line x1="390" y1="550" x2="360" y2="500" class="mcp-line" marker-end="url(#mcpArrow)" stroke-dasharray="3,3" />
|
||||
<line x1="530" y1="550" x2="370" y2="500" class="mcp-line" marker-end="url(#mcpArrow)" stroke-dasharray="3,3" />
|
||||
|
||||
<!-- External MCP Servers Section title with background -->
|
||||
<rect x="210" y="520" width="280" height="25" class="text-bg" />
|
||||
<text x="350" y="535" text-anchor="middle" class="overlay-text" fill="#388e3c">
|
||||
External MCP Servers (Proxied via Coordinator)
|
||||
</text>
|
||||
|
||||
<!-- Proxy flow label -->
|
||||
<rect x="550" y="520" width="140" height="25" class="text-bg" />
|
||||
<text x="620" y="535" text-anchor="middle" class="small-text" fill="#1976d2" font-weight="bold">
|
||||
⇅ Proxied Tool Calls
|
||||
</text>
|
||||
|
||||
<!-- Data flow label with background -->
|
||||
<rect x="630" y="340" width="80" height="20" class="text-bg" />
|
||||
<text x="670" y="352" text-anchor="middle" class="small-text" fill="#4caf50" font-weight="bold">
|
||||
Live Updates
|
||||
</text>
|
||||
|
||||
<!-- MCP Server boxes -->
|
||||
<rect x="50" y="550" width="120" height="80" rx="6" class="mcp-server-box" />
|
||||
<text x="110" y="570" text-anchor="middle" class="title-text" fill="#388e3c">Filesystem</text>
|
||||
<text x="110" y="585" text-anchor="middle" class="small-text" fill="#666">read_file</text>
|
||||
<text x="110" y="598" text-anchor="middle" class="small-text" fill="#666">write_file</text>
|
||||
<text x="110" y="611" text-anchor="middle" class="small-text" fill="#666">list_directory</text>
|
||||
|
||||
<rect x="190" y="550" width="120" height="80" rx="6" class="mcp-server-box" />
|
||||
<text x="250" y="570" text-anchor="middle" class="title-text" fill="#388e3c">Memory</text>
|
||||
<text x="250" y="585" text-anchor="middle" class="small-text" fill="#666">search_nodes</text>
|
||||
<text x="250" y="598" text-anchor="middle" class="small-text" fill="#666">store_memory</text>
|
||||
<text x="250" y="611" text-anchor="middle" class="small-text" fill="#666">recall_info</text>
|
||||
|
||||
<rect x="330" y="550" width="120" height="80" rx="6" class="mcp-server-box" />
|
||||
<text x="390" y="570" text-anchor="middle" class="title-text" fill="#388e3c">Context7</text>
|
||||
<text x="390" y="585" text-anchor="middle" class="small-text" fill="#666">get_docs</text>
|
||||
<text x="390" y="598" text-anchor="middle" class="small-text" fill="#666">search_docs</text>
|
||||
<text x="390" y="611" text-anchor="middle" class="small-text" fill="#666">get_library</text>
|
||||
|
||||
<rect x="470" y="550" width="120" height="80" rx="6" class="mcp-server-box" />
|
||||
<text x="530" y="570" text-anchor="middle" class="title-text" fill="#388e3c">Sequential</text>
|
||||
<text x="530" y="585" text-anchor="middle" class="small-text" fill="#666">thinking</text>
|
||||
<text x="530" y="598" text-anchor="middle" class="small-text" fill="#666">analyze</text>
|
||||
<text x="530" y="611" text-anchor="middle" class="small-text" fill="#666">problem</text>
|
||||
|
||||
<!-- Key Process Flow -->
|
||||
<text x="350" y="670" text-anchor="middle" class="title-text" fill="#d5d5d5ff">
|
||||
Key Proxy Flow: Agent → Coordinator → External Tools → Presence Tracking
|
||||
</text>
|
||||
|
||||
<text x="50" y="690" class="small-text" fill="#d5d5d5ff">1. Agents connect via single MCP interface</text>
|
||||
<text x="50" y="705" class="small-text" fill="#d5d5d5ff">2. ALL tool calls proxy through coordinator</text>
|
||||
<text x="50" y="720" class="small-text" fill="#d5d5d5ff">3. Coordinator updates agent presence + tracks tasks</text>
|
||||
|
||||
<text x="450" y="690" class="small-text" fill="#d5d5d5ff">4. Agents gain full project awareness via proxy</text>
|
||||
<text x="450" y="705" class="small-text" fill="#d5d5d5ff">5. Real-time coordination prevents conflicts</text>
|
||||
<text x="450" y="720" class="small-text" fill="#d5d5d5ff">6. Single interface → Multiple backends</text>
|
||||
|
||||
<!-- Version info -->
|
||||
<text x="1150" y="790" text-anchor="end" class="small-text" fill="#aaa">
|
||||
Agent Coordinator v0.1.0
|
||||
</text>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 16 KiB |
461
examples/director_demo.exs
Normal file
461
examples/director_demo.exs
Normal file
@@ -0,0 +1,461 @@
|
||||
#!/usr/bin/env elixir
|
||||
|
||||
# Director Management Demo Script
|
||||
#
|
||||
# This script demonstrates the director role functionality:
|
||||
# 1. Register a director agent with oversight capabilities
|
||||
# 2. Register multiple standard agents for the director to manage
|
||||
# 3. Show director observing and managing other agents
|
||||
# 4. Demonstrate task assignment, feedback, and redundancy detection
|
||||
# 5. Show autonomous workflow coordination
|
||||
|
||||
Mix.install([
|
||||
{:agent_coordinator, path: "."}
|
||||
])
|
||||
|
||||
defmodule DirectorDemo do
|
||||
alias AgentCoordinator.{TaskRegistry, Inbox, Agent, Task}
|
||||
|
||||
def run do
|
||||
IO.puts("\n🎬 Director Management Demo Starting...")
|
||||
IO.puts("=" <> String.duplicate("=", 50))
|
||||
|
||||
# Start the Agent Coordinator application
|
||||
{:ok, _} = AgentCoordinator.Application.start(:normal, [])
|
||||
:timer.sleep(2000) # Give more time for startup
|
||||
|
||||
# Setup demo scenario
|
||||
setup_demo_scenario()
|
||||
|
||||
# Demonstrate director capabilities
|
||||
demo_director_observations()
|
||||
demo_task_management()
|
||||
demo_redundancy_detection()
|
||||
demo_autonomous_workflow()
|
||||
|
||||
IO.puts("\n✅ Director Management Demo Complete!")
|
||||
IO.puts("=" <> String.duplicate("=", 50))
|
||||
end
|
||||
|
||||
defp setup_demo_scenario do
|
||||
IO.puts("\n📋 Setting up demo scenario...")
|
||||
|
||||
# Register a global director
|
||||
director_opts = %{
|
||||
role: :director,
|
||||
oversight_scope: :global,
|
||||
capabilities: ["management", "coordination", "oversight", "coding"],
|
||||
workspace_path: "/home/ra/agent_coordinator",
|
||||
codebase_id: "agent_coordinator"
|
||||
}
|
||||
|
||||
{:ok, director_id} = TaskRegistry.register_agent("Director Phoenix Eagle", director_opts)
|
||||
IO.puts("✅ Registered Director: #{director_id}")
|
||||
|
||||
# Register several standard agents for the director to manage
|
||||
agents = [
|
||||
{"Frontend Developer Ruby Shark", %{capabilities: ["coding", "testing"], role: :standard}},
|
||||
{"Backend Engineer Silver Wolf", %{capabilities: ["coding", "analysis"], role: :standard}},
|
||||
{"QA Tester Golden Panda", %{capabilities: ["testing", "documentation"], role: :standard}},
|
||||
{"DevOps Engineer Blue Tiger", %{capabilities: ["coding", "review"], role: :standard}}
|
||||
]
|
||||
|
||||
agent_ids = Enum.map(agents, fn {name, opts} ->
|
||||
base_opts = Map.merge(opts, %{
|
||||
workspace_path: "/home/ra/agent_coordinator",
|
||||
codebase_id: "agent_coordinator"
|
||||
})
|
||||
{:ok, agent_id} = TaskRegistry.register_agent(name, base_opts)
|
||||
IO.puts("✅ Registered Agent: #{name} (#{agent_id})")
|
||||
|
||||
# Add some initial tasks to create realistic scenario
|
||||
add_demo_tasks(agent_id, name)
|
||||
|
||||
agent_id
|
||||
end)
|
||||
|
||||
%{director_id: director_id, agent_ids: agent_ids}
|
||||
end
|
||||
|
||||
defp add_demo_tasks(agent_id, agent_name) do
|
||||
tasks = case agent_name do
|
||||
"Frontend Developer" <> _ -> [
|
||||
{"Implement User Dashboard", "Create responsive dashboard with user stats and activity feed"},
|
||||
{"Fix CSS Layout Issues", "Resolve responsive design problems on mobile devices"},
|
||||
{"Add Dark Mode Support", "Implement theme switching with proper contrast ratios"}
|
||||
]
|
||||
"Backend Engineer" <> _ -> [
|
||||
{"Optimize Database Queries", "Review and optimize slow queries in user management system"},
|
||||
{"Implement API Rate Limiting", "Add rate limiting to prevent API abuse"},
|
||||
{"Fix Authentication Bug", "Resolve JWT token refresh issue causing user logouts"}
|
||||
]
|
||||
"QA Tester" <> _ -> [
|
||||
{"Write End-to-End Tests", "Create comprehensive test suite for user authentication flow"},
|
||||
{"Performance Testing", "Conduct load testing on API endpoints"},
|
||||
{"Fix Authentication Bug", "Validate JWT token refresh fix from backend team"} # Intentional duplicate
|
||||
]
|
||||
"DevOps Engineer" <> _ -> [
|
||||
{"Setup CI/CD Pipeline", "Configure automated testing and deployment pipeline"},
|
||||
{"Monitor System Performance", "Setup monitoring dashboards and alerting"},
|
||||
{"Optimize Database Queries", "Database performance tuning and indexing"} # Intentional duplicate
|
||||
]
|
||||
end
|
||||
|
||||
Enum.each(tasks, fn {title, description} ->
|
||||
task = Task.new(title, description, %{
|
||||
priority: Enum.random([:low, :normal, :high]),
|
||||
codebase_id: "agent_coordinator"
|
||||
})
|
||||
Inbox.add_task(agent_id, task)
|
||||
end)
|
||||
end
|
||||
|
||||
defp demo_director_observations do
|
||||
IO.puts("\n👁️ Director Observation Capabilities")
|
||||
IO.puts("-" <> String.duplicate("-", 40))
|
||||
|
||||
# Get the director agent
|
||||
agents = TaskRegistry.list_agents()
|
||||
director = Enum.find(agents, fn agent -> Agent.is_director?(agent) end)
|
||||
|
||||
if director do
|
||||
IO.puts("🔍 Director '#{director.name}' observing all agents...")
|
||||
|
||||
# Simulate director observing agents
|
||||
args = %{
|
||||
"agent_id" => director.id,
|
||||
"scope" => "codebase",
|
||||
"include_activity_history" => true
|
||||
}
|
||||
|
||||
# This would normally be called through MCP, but we'll call directly for demo
|
||||
result = observe_all_agents_demo(director, args)
|
||||
|
||||
case result do
|
||||
{:ok, observation} ->
|
||||
IO.puts("📊 Observation Results:")
|
||||
IO.puts(" - Total Agents: #{observation.total_agents}")
|
||||
IO.puts(" - Oversight Scope: #{observation.oversight_capability}")
|
||||
|
||||
Enum.each(observation.agents, fn agent_info ->
|
||||
task_count = %{
|
||||
pending: length(agent_info.tasks.pending),
|
||||
in_progress: if(agent_info.tasks.in_progress, do: 1, else: 0),
|
||||
completed: length(agent_info.tasks.completed)
|
||||
}
|
||||
|
||||
IO.puts(" 📋 #{agent_info.name}:")
|
||||
IO.puts(" Role: #{agent_info.role} | Status: #{agent_info.status}")
|
||||
IO.puts(" Tasks: #{task_count.pending} pending, #{task_count.in_progress} active, #{task_count.completed} done")
|
||||
IO.puts(" Capabilities: #{Enum.join(agent_info.capabilities, ", ")}")
|
||||
end)
|
||||
|
||||
{:error, reason} ->
|
||||
IO.puts("❌ Observation failed: #{reason}")
|
||||
end
|
||||
else
|
||||
IO.puts("❌ No director found in system")
|
||||
end
|
||||
end
|
||||
|
||||
defp observe_all_agents_demo(director, args) do
|
||||
# Simplified version of the actual function for demo
|
||||
all_agents = TaskRegistry.list_agents()
|
||||
|> Enum.filter(fn a -> a.codebase_id == director.codebase_id end)
|
||||
|
||||
detailed_agents = Enum.map(all_agents, fn target_agent ->
|
||||
task_info = case Inbox.list_tasks(target_agent.id) do
|
||||
{:error, _} -> %{pending: [], in_progress: nil, completed: []}
|
||||
tasks -> tasks
|
||||
end
|
||||
|
||||
%{
|
||||
agent_id: target_agent.id,
|
||||
name: target_agent.name,
|
||||
role: target_agent.role,
|
||||
capabilities: target_agent.capabilities,
|
||||
status: target_agent.status,
|
||||
codebase_id: target_agent.codebase_id,
|
||||
managed_by_director: target_agent.id in (director.managed_agents || []),
|
||||
tasks: task_info
|
||||
}
|
||||
end)
|
||||
|
||||
{:ok, %{
|
||||
director_id: director.id,
|
||||
scope: "codebase",
|
||||
oversight_capability: director.oversight_scope,
|
||||
agents: detailed_agents,
|
||||
total_agents: length(detailed_agents),
|
||||
timestamp: DateTime.utc_now()
|
||||
}}
|
||||
end
|
||||
|
||||
defp demo_task_management do
|
||||
IO.puts("\n📝 Director Task Management")
|
||||
IO.puts("-" <> String.duplicate("-", 40))
|
||||
|
||||
agents = TaskRegistry.list_agents()
|
||||
director = Enum.find(agents, fn agent -> Agent.is_director?(agent) end)
|
||||
standard_agents = Enum.filter(agents, fn agent -> !Agent.is_director?(agent) end)
|
||||
|
||||
if director && length(standard_agents) > 0 do
|
||||
target_agent = Enum.random(standard_agents)
|
||||
|
||||
IO.puts("🎯 Director assigning new task to #{target_agent.name}...")
|
||||
|
||||
# Create a high-priority coordination task
|
||||
new_task = %{
|
||||
"title" => "Team Coordination Meeting",
|
||||
"description" => "Organize cross-functional team sync to align on project priorities and resolve blockers. Focus on identifying dependencies between frontend, backend, and QA work streams.",
|
||||
"priority" => "high",
|
||||
"file_paths" => []
|
||||
}
|
||||
|
||||
# Director assigns the task
|
||||
task = Task.new(new_task["title"], new_task["description"], %{
|
||||
priority: :high,
|
||||
codebase_id: target_agent.codebase_id,
|
||||
assignment_reason: "Director identified need for team alignment",
|
||||
metadata: %{
|
||||
director_assigned: true,
|
||||
director_id: director.id
|
||||
}
|
||||
})
|
||||
|
||||
case Inbox.add_task(target_agent.id, task) do
|
||||
:ok ->
|
||||
IO.puts("✅ Task assigned successfully!")
|
||||
IO.puts(" Task: #{task.title}")
|
||||
IO.puts(" Assigned to: #{target_agent.name}")
|
||||
IO.puts(" Priority: #{task.priority}")
|
||||
IO.puts(" Reason: #{task.assignment_reason}")
|
||||
|
||||
# Update director's managed agents list
|
||||
updated_director = Agent.add_managed_agent(director, target_agent.id)
|
||||
TaskRegistry.update_agent(director.id, updated_director)
|
||||
|
||||
{:error, reason} ->
|
||||
IO.puts("❌ Task assignment failed: #{reason}")
|
||||
end
|
||||
|
||||
IO.puts("\n💬 Director providing task feedback...")
|
||||
|
||||
# Simulate director providing feedback on existing tasks
|
||||
{:ok, tasks} = Inbox.list_tasks(target_agent.id)
|
||||
if length(tasks.pending) > 0 do
|
||||
sample_task = Enum.random(tasks.pending)
|
||||
|
||||
feedback_examples = [
|
||||
"Consider breaking this task into smaller, more manageable subtasks for better tracking.",
|
||||
"This aligns well with the current sprint goals. Prioritize integration with the new API endpoints.",
|
||||
"Coordinate with the QA team before implementation to ensure test coverage is adequate.",
|
||||
"This task may have dependencies on the backend authentication work. Check with the backend team first."
|
||||
]
|
||||
|
||||
feedback = Enum.random(feedback_examples)
|
||||
|
||||
IO.puts("📋 Feedback for task '#{sample_task.title}':")
|
||||
IO.puts(" 💡 #{feedback}")
|
||||
IO.puts(" ⏰ Timestamp: #{DateTime.utc_now()}")
|
||||
end
|
||||
|
||||
else
|
||||
IO.puts("❌ No director or standard agents found for task management demo")
|
||||
end
|
||||
end
|
||||
|
||||
defp demo_redundancy_detection do
|
||||
IO.puts("\n🔍 Director Redundancy Detection")
|
||||
IO.puts("-" <> String.duplicate("-", 40))
|
||||
|
||||
agents = TaskRegistry.list_agents()
|
||||
director = Enum.find(agents, fn agent -> Agent.is_director?(agent) end)
|
||||
|
||||
if director do
|
||||
IO.puts("🔎 Analyzing tasks across all agents for redundancy...")
|
||||
|
||||
# Collect all tasks from all agents
|
||||
all_agents = Enum.filter(agents, fn a -> a.codebase_id == director.codebase_id end)
|
||||
all_tasks = Enum.flat_map(all_agents, fn agent ->
|
||||
case Inbox.list_tasks(agent.id) do
|
||||
{:error, _} -> []
|
||||
tasks ->
|
||||
(tasks.pending ++ (if tasks.in_progress, do: [tasks.in_progress], else: []))
|
||||
|> Enum.map(fn task -> Map.put(task, :agent_id, agent.id) end)
|
||||
end
|
||||
end)
|
||||
|
||||
IO.puts("📊 Total tasks analyzed: #{length(all_tasks)}")
|
||||
|
||||
# Detect redundant tasks (simplified similarity detection)
|
||||
redundant_groups = detect_similar_tasks_demo(all_tasks)
|
||||
|
||||
if length(redundant_groups) > 0 do
|
||||
IO.puts("⚠️ Found #{length(redundant_groups)} groups of potentially redundant tasks:")
|
||||
|
||||
Enum.each(redundant_groups, fn group ->
|
||||
IO.puts("\n 🔄 Redundant Group: '#{group.similarity_key}'")
|
||||
IO.puts(" Task count: #{group.task_count}")
|
||||
|
||||
Enum.each(group.tasks, fn task ->
|
||||
agent = Enum.find(agents, fn a -> a.id == task.agent_id end)
|
||||
agent_name = if agent, do: agent.name, else: "Unknown Agent"
|
||||
IO.puts(" - #{task.title} (#{agent_name})")
|
||||
end)
|
||||
|
||||
IO.puts(" 🎯 Recommendation: Consider consolidating these similar tasks or clearly define distinct responsibilities.")
|
||||
end)
|
||||
|
||||
total_redundant = Enum.sum(Enum.map(redundant_groups, fn g -> g.task_count end))
|
||||
IO.puts("\n📈 Impact Analysis:")
|
||||
IO.puts(" - Total redundant tasks: #{total_redundant}")
|
||||
IO.puts(" - Potential efficiency gain: #{round(total_redundant / length(all_tasks) * 100)}%")
|
||||
|
||||
else
|
||||
IO.puts("✅ No redundant tasks detected. Teams are well-coordinated!")
|
||||
end
|
||||
|
||||
else
|
||||
IO.puts("❌ No director found for redundancy detection")
|
||||
end
|
||||
end
|
||||
|
||||
defp detect_similar_tasks_demo(tasks) do
|
||||
# Group tasks by normalized title keywords
|
||||
tasks
|
||||
|> Enum.group_by(fn task ->
|
||||
# Normalize title for comparison
|
||||
String.downcase(task.title)
|
||||
|> String.replace(~r/[^\w\s]/, "")
|
||||
|> String.split()
|
||||
|> Enum.take(3)
|
||||
|> Enum.join(" ")
|
||||
end)
|
||||
|> Enum.filter(fn {_key, group_tasks} -> length(group_tasks) > 1 end)
|
||||
|> Enum.map(fn {key, group_tasks} ->
|
||||
%{
|
||||
similarity_key: key,
|
||||
tasks: Enum.map(group_tasks, fn task ->
|
||||
%{
|
||||
task_id: task.id,
|
||||
title: task.title,
|
||||
agent_id: task.agent_id,
|
||||
codebase_id: task.codebase_id
|
||||
}
|
||||
end),
|
||||
task_count: length(group_tasks)
|
||||
}
|
||||
end)
|
||||
end
|
||||
|
||||
defp demo_autonomous_workflow do
|
||||
IO.puts("\n🤖 Director Autonomous Workflow Coordination")
|
||||
IO.puts("-" <> String.duplicate("-", 50))
|
||||
|
||||
agents = TaskRegistry.list_agents()
|
||||
director = Enum.find(agents, fn agent -> Agent.is_director?(agent) end)
|
||||
standard_agents = Enum.filter(agents, fn agent -> !Agent.is_director?(agent) end)
|
||||
|
||||
if director && length(standard_agents) >= 2 do
|
||||
IO.puts("🎭 Simulating autonomous workflow coordination scenario...")
|
||||
IO.puts("\nScenario: Director detects that authentication bug fixes require coordination")
|
||||
IO.puts("between Backend Engineer and QA Tester.")
|
||||
|
||||
# Find agents working on authentication
|
||||
backend_agent = Enum.find(standard_agents, fn agent ->
|
||||
String.contains?(agent.name, "Backend")
|
||||
end)
|
||||
|
||||
qa_agent = Enum.find(standard_agents, fn agent ->
|
||||
String.contains?(agent.name, "QA")
|
||||
end)
|
||||
|
||||
if backend_agent && qa_agent do
|
||||
IO.puts("\n1️⃣ Director sending coordination input to Backend Engineer...")
|
||||
|
||||
coordination_message = """
|
||||
🤖 Director Coordination:
|
||||
|
||||
I've identified that your JWT authentication fix needs to be coordinated with QA testing.
|
||||
|
||||
Action Required:
|
||||
- Notify QA team when your fix is ready for testing
|
||||
- Provide test credentials and reproduction steps
|
||||
- Schedule knowledge transfer session if needed
|
||||
|
||||
This will help avoid testing delays and ensure comprehensive coverage.
|
||||
"""
|
||||
|
||||
# Simulate sending input to backend agent
|
||||
IO.puts("📤 Sending message to #{backend_agent.name}:")
|
||||
IO.puts(" Input Type: chat_message")
|
||||
IO.puts(" Content: [Coordination message about JWT fix coordination]")
|
||||
IO.puts(" Context: authentication_workflow_coordination")
|
||||
|
||||
IO.puts("\n2️⃣ Director sending parallel input to QA Tester...")
|
||||
|
||||
qa_message = """
|
||||
🤖 Director Coordination:
|
||||
|
||||
Backend team is working on JWT authentication fix. Please prepare for coordinated testing.
|
||||
|
||||
Action Required:
|
||||
- Review current authentication test cases
|
||||
- Prepare test environment for JWT token scenarios
|
||||
- Block time for testing once backend fix is ready
|
||||
|
||||
I'll facilitate the handoff between teams when implementation is complete.
|
||||
"""
|
||||
|
||||
IO.puts("📤 Sending message to #{qa_agent.name}:")
|
||||
IO.puts(" Input Type: chat_message")
|
||||
IO.puts(" Content: [Coordination message about authentication testing prep]")
|
||||
IO.puts(" Context: authentication_workflow_coordination")
|
||||
|
||||
IO.puts("\n3️⃣ Director scheduling follow-up coordination...")
|
||||
|
||||
# Create coordination task
|
||||
coordination_task = Task.new(
|
||||
"Authentication Fix Coordination Follow-up",
|
||||
"Check progress on JWT fix coordination between backend and QA teams. Ensure handoff is smooth and testing is proceeding without blockers.",
|
||||
%{
|
||||
priority: :normal,
|
||||
codebase_id: director.codebase_id,
|
||||
assignment_reason: "Autonomous workflow coordination",
|
||||
metadata: %{
|
||||
workflow_type: "authentication_coordination",
|
||||
involves_agents: [backend_agent.id, qa_agent.id],
|
||||
coordination_phase: "follow_up"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
Inbox.add_task(director.id, coordination_task)
|
||||
IO.puts("✅ Created follow-up coordination task for director")
|
||||
|
||||
IO.puts("\n🎯 Autonomous Workflow Benefits Demonstrated:")
|
||||
IO.puts(" ✅ Proactive cross-team coordination")
|
||||
IO.puts(" ✅ Parallel communication to reduce delays")
|
||||
IO.puts(" ✅ Automated follow-up task creation")
|
||||
IO.puts(" ✅ Context-aware workflow management")
|
||||
IO.puts(" ✅ Human-out-of-the-loop efficiency")
|
||||
|
||||
IO.puts("\n🔮 Next Steps in Full Implementation:")
|
||||
IO.puts(" - VSCode integration for real agent messaging")
|
||||
IO.puts(" - Workflow templates for common coordination patterns")
|
||||
IO.puts(" - ML-based task dependency detection")
|
||||
IO.puts(" - Automated testing trigger coordination")
|
||||
IO.puts(" - Cross-codebase workflow orchestration")
|
||||
|
||||
else
|
||||
IO.puts("❌ Could not find Backend and QA agents for workflow demo")
|
||||
end
|
||||
else
|
||||
IO.puts("❌ Insufficient agents for autonomous workflow demonstration")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Run the demo
|
||||
DirectorDemo.run()
|
||||
@@ -16,7 +16,10 @@ defmodule AgentCoordinator.Agent do
|
||||
:metadata,
|
||||
:current_activity,
|
||||
:current_files,
|
||||
:activity_history
|
||||
:activity_history,
|
||||
:role,
|
||||
:managed_agents,
|
||||
:oversight_scope
|
||||
]}
|
||||
defstruct [
|
||||
:id,
|
||||
@@ -30,11 +33,23 @@ defmodule AgentCoordinator.Agent do
|
||||
:metadata,
|
||||
:current_activity,
|
||||
:current_files,
|
||||
:activity_history
|
||||
:activity_history,
|
||||
:role,
|
||||
:managed_agents,
|
||||
:oversight_scope
|
||||
]
|
||||
|
||||
@type status :: :idle | :busy | :offline | :error
|
||||
@type capability :: :coding | :testing | :documentation | :analysis | :review
|
||||
@type capability ::
|
||||
:coding
|
||||
| :testing
|
||||
| :documentation
|
||||
| :analysis
|
||||
| :review
|
||||
| :management
|
||||
| :coordination
|
||||
| :oversight
|
||||
@type role :: :standard | :director | :project_manager
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
id: String.t(),
|
||||
@@ -48,7 +63,10 @@ defmodule AgentCoordinator.Agent do
|
||||
metadata: map(),
|
||||
current_activity: String.t() | nil,
|
||||
current_files: [String.t()],
|
||||
activity_history: [map()]
|
||||
activity_history: [map()],
|
||||
role: role(),
|
||||
managed_agents: [String.t()],
|
||||
oversight_scope: :codebase | :global
|
||||
}
|
||||
|
||||
def new(name, capabilities, opts \\ []) do
|
||||
@@ -75,6 +93,9 @@ defmodule AgentCoordinator.Agent do
|
||||
)
|
||||
end
|
||||
|
||||
# Determine role based on capabilities
|
||||
role = determine_role(capabilities)
|
||||
|
||||
%__MODULE__{
|
||||
id: UUID.uuid4(),
|
||||
name: name,
|
||||
@@ -87,7 +108,11 @@ defmodule AgentCoordinator.Agent do
|
||||
metadata: Keyword.get(opts, :metadata, %{}),
|
||||
current_activity: nil,
|
||||
current_files: [],
|
||||
activity_history: []
|
||||
activity_history: [],
|
||||
role: role,
|
||||
managed_agents: [],
|
||||
oversight_scope:
|
||||
if(role == :director, do: Keyword.get(opts, :oversight_scope, :codebase), else: :codebase)
|
||||
}
|
||||
end
|
||||
|
||||
@@ -153,4 +178,55 @@ defmodule AgentCoordinator.Agent do
|
||||
def can_work_cross_codebase?(agent) do
|
||||
Map.get(agent.metadata, :cross_codebase_capable, false)
|
||||
end
|
||||
|
||||
# Director-specific functions
|
||||
|
||||
def is_director?(agent) do
|
||||
agent.role == :director
|
||||
end
|
||||
|
||||
def is_manager?(agent) do
|
||||
agent.role in [:director, :project_manager]
|
||||
end
|
||||
|
||||
def can_manage_agent?(director, target_agent) do
|
||||
case director.oversight_scope do
|
||||
:global -> true
|
||||
:codebase -> director.codebase_id == target_agent.codebase_id
|
||||
end
|
||||
end
|
||||
|
||||
def add_managed_agent(director, agent_id) do
|
||||
if is_manager?(director) do
|
||||
managed_agents = [agent_id | director.managed_agents] |> Enum.uniq()
|
||||
%{director | managed_agents: managed_agents}
|
||||
else
|
||||
director
|
||||
end
|
||||
end
|
||||
|
||||
def remove_managed_agent(director, agent_id) do
|
||||
if is_manager?(director) do
|
||||
managed_agents = director.managed_agents |> Enum.reject(&(&1 == agent_id))
|
||||
%{director | managed_agents: managed_agents}
|
||||
else
|
||||
director
|
||||
end
|
||||
end
|
||||
|
||||
# Private helper to determine role from capabilities
|
||||
defp determine_role(capabilities) do
|
||||
management_caps = [:management, :coordination, :oversight]
|
||||
|
||||
cond do
|
||||
Enum.any?(management_caps, &(&1 in capabilities)) and :oversight in capabilities ->
|
||||
:director
|
||||
|
||||
:management in capabilities ->
|
||||
:project_manager
|
||||
|
||||
true ->
|
||||
:standard
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -32,6 +32,10 @@ defmodule AgentCoordinator.Inbox do
|
||||
GenServer.call(via_tuple(agent_id), {:add_task, task}, 30_000)
|
||||
end
|
||||
|
||||
def remove_task(agent_id, task_id) do
|
||||
GenServer.call(via_tuple(agent_id), {:remove_task, task_id}, 30_000)
|
||||
end
|
||||
|
||||
def get_next_task(agent_id) do
|
||||
GenServer.call(via_tuple(agent_id), :get_next_task, 15_000)
|
||||
end
|
||||
@@ -92,6 +96,47 @@ defmodule AgentCoordinator.Inbox do
|
||||
{:reply, :ok, new_state}
|
||||
end
|
||||
|
||||
def handle_call({:remove_task, task_id}, _from, state) do
|
||||
# Remove task from pending tasks
|
||||
{removed_task, remaining_pending} =
|
||||
Enum.reduce(state.pending_tasks, {nil, []}, fn task, {found_task, acc} ->
|
||||
if task.id == task_id do
|
||||
{task, acc}
|
||||
else
|
||||
{found_task, [task | acc]}
|
||||
end
|
||||
end)
|
||||
|
||||
# Check if task is currently in progress
|
||||
{new_in_progress, removed_from_progress} =
|
||||
if state.in_progress_task && state.in_progress_task.id == task_id do
|
||||
{nil, state.in_progress_task}
|
||||
else
|
||||
{state.in_progress_task, nil}
|
||||
end
|
||||
|
||||
final_removed_task = removed_task || removed_from_progress
|
||||
|
||||
if final_removed_task do
|
||||
new_state = %{
|
||||
state
|
||||
| pending_tasks: Enum.reverse(remaining_pending),
|
||||
in_progress_task: new_in_progress
|
||||
}
|
||||
|
||||
# Broadcast task removed
|
||||
Phoenix.PubSub.broadcast(
|
||||
AgentCoordinator.PubSub,
|
||||
"agent:#{state.agent_id}",
|
||||
{:task_removed, final_removed_task}
|
||||
)
|
||||
|
||||
{:reply, :ok, new_state}
|
||||
else
|
||||
{:reply, {:error, :task_not_found}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call(:get_next_task, _from, state) do
|
||||
case state.pending_tasks do
|
||||
[] ->
|
||||
|
||||
@@ -47,7 +47,16 @@ defmodule AgentCoordinator.MCPServer do
|
||||
"type" => "array",
|
||||
"items" => %{
|
||||
"type" => "string",
|
||||
"enum" => ["coding", "testing", "documentation", "analysis", "review"]
|
||||
"enum" => [
|
||||
"coding",
|
||||
"testing",
|
||||
"documentation",
|
||||
"analysis",
|
||||
"review",
|
||||
"management",
|
||||
"coordination",
|
||||
"oversight"
|
||||
]
|
||||
}
|
||||
},
|
||||
"codebase_id" => %{
|
||||
@@ -377,6 +386,128 @@ defmodule AgentCoordinator.MCPServer do
|
||||
},
|
||||
"required" => ["agent_id", "workspace_path"]
|
||||
}
|
||||
},
|
||||
%{
|
||||
"name" => "observe_all_agents",
|
||||
"description" =>
|
||||
"[Director Only] Get comprehensive view of all agents and their activities for management oversight",
|
||||
"inputSchema" => %{
|
||||
"type" => "object",
|
||||
"properties" => %{
|
||||
"agent_id" => %{"type" => "string"},
|
||||
"include_activity_history" => %{"type" => "boolean", "default" => true},
|
||||
"scope" => %{
|
||||
"type" => "string",
|
||||
"enum" => ["codebase", "global"],
|
||||
"default" => "codebase"
|
||||
}
|
||||
},
|
||||
"required" => ["agent_id"]
|
||||
}
|
||||
},
|
||||
%{
|
||||
"name" => "modify_agent_tasks",
|
||||
"description" =>
|
||||
"[Director Only] Add, remove, or update tasks for other agents under management",
|
||||
"inputSchema" => %{
|
||||
"type" => "object",
|
||||
"properties" => %{
|
||||
"director_id" => %{"type" => "string"},
|
||||
"target_agent_id" => %{"type" => "string"},
|
||||
"action" => %{"type" => "string", "enum" => ["add", "remove", "update"]},
|
||||
"task_id" => %{
|
||||
"type" => "string",
|
||||
"description" => "Required for remove/update actions"
|
||||
},
|
||||
"task" => %{
|
||||
"type" => "object",
|
||||
"description" => "Required for add/update actions",
|
||||
"properties" => %{
|
||||
"title" => %{"type" => "string"},
|
||||
"description" => %{"type" => "string"},
|
||||
"priority" => %{"type" => "string", "enum" => ["low", "normal", "high", "urgent"]},
|
||||
"file_paths" => %{"type" => "array", "items" => %{"type" => "string"}}
|
||||
}
|
||||
},
|
||||
"reason" => %{"type" => "string", "description" => "Reason for the modification"}
|
||||
},
|
||||
"required" => ["director_id", "target_agent_id", "action"]
|
||||
}
|
||||
},
|
||||
%{
|
||||
"name" => "add_task_feedback",
|
||||
"description" => "[Director Only] Add feedback or guidance notes to a specific task",
|
||||
"inputSchema" => %{
|
||||
"type" => "object",
|
||||
"properties" => %{
|
||||
"director_id" => %{"type" => "string"},
|
||||
"task_id" => %{"type" => "string"},
|
||||
"feedback" => %{
|
||||
"type" => "string",
|
||||
"description" => "Feedback for the agent working on this task"
|
||||
},
|
||||
"notes" => %{"type" => "string", "description" => "Private director notes"},
|
||||
"blocking_issues" => %{"type" => "array", "items" => %{"type" => "string"}}
|
||||
},
|
||||
"required" => ["director_id", "task_id"]
|
||||
}
|
||||
},
|
||||
%{
|
||||
"name" => "detect_redundant_tasks",
|
||||
"description" =>
|
||||
"[Director Only] Analyze all agent tasks to detect redundant or overlapping work",
|
||||
"inputSchema" => %{
|
||||
"type" => "object",
|
||||
"properties" => %{
|
||||
"director_id" => %{"type" => "string"},
|
||||
"scope" => %{
|
||||
"type" => "string",
|
||||
"enum" => ["codebase", "global"],
|
||||
"default" => "codebase"
|
||||
},
|
||||
"similarity_threshold" => %{
|
||||
"type" => "number",
|
||||
"default" => 0.7,
|
||||
"description" => "Task similarity threshold for redundancy detection"
|
||||
}
|
||||
},
|
||||
"required" => ["director_id"]
|
||||
}
|
||||
},
|
||||
%{
|
||||
"name" => "reassign_tasks",
|
||||
"description" =>
|
||||
"[Director Only] Move tasks between agents based on workload or capability analysis",
|
||||
"inputSchema" => %{
|
||||
"type" => "object",
|
||||
"properties" => %{
|
||||
"director_id" => %{"type" => "string"},
|
||||
"task_ids" => %{"type" => "array", "items" => %{"type" => "string"}},
|
||||
"from_agent_id" => %{"type" => "string"},
|
||||
"to_agent_id" => %{"type" => "string"},
|
||||
"reason" => %{"type" => "string"}
|
||||
},
|
||||
"required" => ["director_id", "task_ids", "from_agent_id", "to_agent_id", "reason"]
|
||||
}
|
||||
},
|
||||
%{
|
||||
"name" => "send_agent_input",
|
||||
"description" =>
|
||||
"[Director Only] Send VSCode input/commands to specific agents for human-out-of-loop workflows",
|
||||
"inputSchema" => %{
|
||||
"type" => "object",
|
||||
"properties" => %{
|
||||
"director_id" => %{"type" => "string"},
|
||||
"target_agent_id" => %{"type" => "string"},
|
||||
"input_type" => %{
|
||||
"type" => "string",
|
||||
"enum" => ["chat_message", "command", "file_action"]
|
||||
},
|
||||
"content" => %{"type" => "string"},
|
||||
"context" => %{"type" => "object", "description" => "Additional context for the input"}
|
||||
},
|
||||
"required" => ["director_id", "target_agent_id", "input_type", "content"]
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1264,6 +1395,353 @@ defmodule AgentCoordinator.MCPServer do
|
||||
Enum.reverse(recommendations)
|
||||
end
|
||||
|
||||
# Director-specific tool implementations
|
||||
|
||||
defp observe_all_agents(%{"agent_id" => agent_id} = args) do
|
||||
# Verify this agent is a director
|
||||
case TaskRegistry.get_agent(agent_id) do
|
||||
{:error, :not_found} ->
|
||||
{:error, "Agent not found: #{agent_id}"}
|
||||
|
||||
{:ok, agent} ->
|
||||
unless Agent.is_director?(agent) do
|
||||
{:error, "Access denied: Only directors can use this tool"}
|
||||
else
|
||||
scope = Map.get(args, "scope", "codebase")
|
||||
include_history = Map.get(args, "include_activity_history", true)
|
||||
|
||||
all_agents = TaskRegistry.list_agents()
|
||||
|
||||
# Filter based on director's oversight scope
|
||||
filtered_agents =
|
||||
case scope do
|
||||
"global" ->
|
||||
if agent.oversight_scope == :global do
|
||||
all_agents
|
||||
else
|
||||
{:error, "Director does not have global oversight scope"}
|
||||
end
|
||||
|
||||
"codebase" ->
|
||||
Enum.filter(all_agents, fn a -> a.codebase_id == agent.codebase_id end)
|
||||
end
|
||||
|
||||
case filtered_agents do
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
|
||||
agents ->
|
||||
detailed_agents =
|
||||
Enum.map(agents, fn target_agent ->
|
||||
task_info =
|
||||
case Inbox.list_tasks(target_agent.id) do
|
||||
{:error, _} -> %{pending: [], in_progress: nil, completed: []}
|
||||
tasks -> tasks
|
||||
end
|
||||
|
||||
base_info = %{
|
||||
agent_id: target_agent.id,
|
||||
name: target_agent.name,
|
||||
role: target_agent.role,
|
||||
capabilities: target_agent.capabilities,
|
||||
status: target_agent.status,
|
||||
codebase_id: target_agent.codebase_id,
|
||||
workspace_path: target_agent.workspace_path,
|
||||
online: Agent.is_online?(target_agent),
|
||||
last_heartbeat: target_agent.last_heartbeat,
|
||||
current_activity: target_agent.current_activity,
|
||||
current_files: target_agent.current_files || [],
|
||||
managed_by_director: target_agent.id in agent.managed_agents,
|
||||
tasks: task_info
|
||||
}
|
||||
|
||||
if include_history do
|
||||
Map.put(base_info, :activity_history, target_agent.activity_history || [])
|
||||
else
|
||||
base_info
|
||||
end
|
||||
end)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
director_id: agent_id,
|
||||
scope: scope,
|
||||
oversight_capability: agent.oversight_scope,
|
||||
agents: detailed_agents,
|
||||
total_agents: length(detailed_agents),
|
||||
timestamp: DateTime.utc_now()
|
||||
}}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp modify_agent_tasks(args) do
|
||||
director_id = Map.get(args, "director_id")
|
||||
target_agent_id = Map.get(args, "target_agent_id")
|
||||
action = Map.get(args, "action")
|
||||
|
||||
with {:ok, director} <- TaskRegistry.get_agent(director_id),
|
||||
true <- Agent.is_director?(director),
|
||||
{:ok, target_agent} <- TaskRegistry.get_agent(target_agent_id),
|
||||
true <- Agent.can_manage_agent?(director, target_agent) do
|
||||
case action do
|
||||
"add" ->
|
||||
task_data = Map.get(args, "task")
|
||||
reason = Map.get(args, "reason", "Director assigned task")
|
||||
|
||||
opts = %{
|
||||
priority: String.to_atom(Map.get(task_data, "priority", "normal")),
|
||||
codebase_id: target_agent.codebase_id,
|
||||
file_paths: Map.get(task_data, "file_paths", []),
|
||||
assignment_reason: reason,
|
||||
metadata: %{
|
||||
director_assigned: true,
|
||||
director_id: director_id
|
||||
}
|
||||
}
|
||||
|
||||
task = Task.new(task_data["title"], task_data["description"], opts)
|
||||
|
||||
case Inbox.add_task(target_agent_id, task) do
|
||||
:ok ->
|
||||
# Add target agent to director's managed list
|
||||
updated_director = Agent.add_managed_agent(director, target_agent_id)
|
||||
TaskRegistry.update_agent(director_id, updated_director)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
action: "task_added",
|
||||
task_id: task.id,
|
||||
target_agent_id: target_agent_id,
|
||||
reason: reason
|
||||
}}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, "Failed to add task: #{reason}"}
|
||||
end
|
||||
|
||||
"remove" ->
|
||||
task_id = Map.get(args, "task_id")
|
||||
reason = Map.get(args, "reason", "Director removed task")
|
||||
|
||||
case Inbox.remove_task(target_agent_id, task_id) do
|
||||
:ok ->
|
||||
{:ok,
|
||||
%{
|
||||
action: "task_removed",
|
||||
task_id: task_id,
|
||||
target_agent_id: target_agent_id,
|
||||
reason: reason
|
||||
}}
|
||||
|
||||
{:error, reason} ->
|
||||
{:error, "Failed to remove task: #{reason}"}
|
||||
end
|
||||
|
||||
"update" ->
|
||||
task_id = Map.get(args, "task_id")
|
||||
task_data = Map.get(args, "task")
|
||||
reason = Map.get(args, "reason", "Director updated task")
|
||||
|
||||
# This would require implementing task update functionality in Inbox
|
||||
{:error, "Task update functionality not yet implemented"}
|
||||
end
|
||||
else
|
||||
{:error, :not_found} -> {:error, "Director or target agent not found"}
|
||||
false -> {:error, "Access denied: Only directors can modify agent tasks"}
|
||||
end
|
||||
end
|
||||
|
||||
defp add_task_feedback(args) do
|
||||
director_id = Map.get(args, "director_id")
|
||||
task_id = Map.get(args, "task_id")
|
||||
feedback = Map.get(args, "feedback")
|
||||
notes = Map.get(args, "notes")
|
||||
blocking_issues = Map.get(args, "blocking_issues", [])
|
||||
|
||||
with {:ok, director} <- TaskRegistry.get_agent(director_id),
|
||||
true <- Agent.is_director?(director) do
|
||||
# This would require implementing task lookup and update functionality
|
||||
# For now, return a placeholder implementation
|
||||
{:ok,
|
||||
%{
|
||||
task_id: task_id,
|
||||
feedback_added: feedback != nil,
|
||||
notes_added: notes != nil,
|
||||
blocking_issues_added: length(blocking_issues),
|
||||
director_id: director_id,
|
||||
timestamp: DateTime.utc_now()
|
||||
}}
|
||||
else
|
||||
{:error, :not_found} -> {:error, "Director not found"}
|
||||
false -> {:error, "Access denied: Only directors can add task feedback"}
|
||||
end
|
||||
end
|
||||
|
||||
defp detect_redundant_tasks(args) do
|
||||
director_id = Map.get(args, "director_id")
|
||||
scope = Map.get(args, "scope", "codebase")
|
||||
threshold = Map.get(args, "similarity_threshold", 0.7)
|
||||
|
||||
with {:ok, director} <- TaskRegistry.get_agent(director_id),
|
||||
true <- Agent.is_director?(director) do
|
||||
all_agents = TaskRegistry.list_agents()
|
||||
|
||||
# Filter agents based on scope
|
||||
target_agents =
|
||||
case scope do
|
||||
"global" when director.oversight_scope == :global -> all_agents
|
||||
"codebase" -> Enum.filter(all_agents, fn a -> a.codebase_id == director.codebase_id end)
|
||||
"global" -> {:error, "Director does not have global scope"}
|
||||
end
|
||||
|
||||
case target_agents do
|
||||
{:error, reason} ->
|
||||
{:error, reason}
|
||||
|
||||
agents ->
|
||||
# Collect all tasks from all agents
|
||||
all_tasks =
|
||||
Enum.flat_map(agents, fn agent ->
|
||||
case Inbox.list_tasks(agent.id) do
|
||||
{:error, _} -> []
|
||||
tasks -> tasks.pending ++ if tasks.in_progress, do: [tasks.in_progress], else: []
|
||||
end
|
||||
end)
|
||||
|
||||
# Simple redundancy detection based on title/description similarity
|
||||
redundant_groups = detect_similar_tasks(all_tasks, threshold)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
director_id: director_id,
|
||||
scope: scope,
|
||||
total_tasks_analyzed: length(all_tasks),
|
||||
redundant_groups: redundant_groups,
|
||||
total_redundant_tasks: Enum.sum(Enum.map(redundant_groups, &length(&1.tasks))),
|
||||
similarity_threshold: threshold,
|
||||
timestamp: DateTime.utc_now()
|
||||
}}
|
||||
end
|
||||
else
|
||||
{:error, :not_found} -> {:error, "Director not found"}
|
||||
false -> {:error, "Access denied: Only directors can detect redundant tasks"}
|
||||
end
|
||||
end
|
||||
|
||||
defp detect_similar_tasks(tasks, threshold) do
|
||||
# Simple implementation - group tasks with similar titles
|
||||
tasks
|
||||
|> Enum.group_by(fn task ->
|
||||
# Normalize title for comparison
|
||||
String.downcase(task.title)
|
||||
|> String.replace(~r/[^\w\s]/, "")
|
||||
|> String.split()
|
||||
|> Enum.take(3)
|
||||
|> Enum.join(" ")
|
||||
end)
|
||||
|> Enum.filter(fn {_key, group_tasks} -> length(group_tasks) > 1 end)
|
||||
|> Enum.map(fn {key, group_tasks} ->
|
||||
%{
|
||||
similarity_key: key,
|
||||
tasks:
|
||||
Enum.map(group_tasks, fn task ->
|
||||
%{
|
||||
task_id: task.id,
|
||||
title: task.title,
|
||||
description: String.slice(task.description, 0, 100) <> "...",
|
||||
agent_id: task.agent_id,
|
||||
codebase_id: task.codebase_id
|
||||
}
|
||||
end),
|
||||
task_count: length(group_tasks)
|
||||
}
|
||||
end)
|
||||
end
|
||||
|
||||
defp reassign_tasks(args) do
|
||||
director_id = Map.get(args, "director_id")
|
||||
task_ids = Map.get(args, "task_ids")
|
||||
from_agent_id = Map.get(args, "from_agent_id")
|
||||
to_agent_id = Map.get(args, "to_agent_id")
|
||||
reason = Map.get(args, "reason")
|
||||
|
||||
with {:ok, director} <- TaskRegistry.get_agent(director_id),
|
||||
true <- Agent.is_director?(director),
|
||||
{:ok, from_agent} <- TaskRegistry.get_agent(from_agent_id),
|
||||
{:ok, to_agent} <- TaskRegistry.get_agent(to_agent_id),
|
||||
true <- Agent.can_manage_agent?(director, from_agent),
|
||||
true <- Agent.can_manage_agent?(director, to_agent) do
|
||||
results =
|
||||
Enum.map(task_ids, fn task_id ->
|
||||
# This would require implementing task transfer between inboxes
|
||||
# For now, return placeholder
|
||||
%{
|
||||
task_id: task_id,
|
||||
status: "reassigned",
|
||||
from_agent_id: from_agent_id,
|
||||
to_agent_id: to_agent_id,
|
||||
reason: reason
|
||||
}
|
||||
end)
|
||||
|
||||
# Add both agents to director's managed list
|
||||
updated_director =
|
||||
director
|
||||
|> Agent.add_managed_agent(from_agent_id)
|
||||
|> Agent.add_managed_agent(to_agent_id)
|
||||
|
||||
TaskRegistry.update_agent(director_id, updated_director)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
director_id: director_id,
|
||||
reassigned_tasks: results,
|
||||
total_reassigned: length(results),
|
||||
timestamp: DateTime.utc_now()
|
||||
}}
|
||||
else
|
||||
{:error, :not_found} -> {:error, "Agent not found"}
|
||||
false -> {:error, "Access denied: Director cannot manage one or more agents"}
|
||||
end
|
||||
end
|
||||
|
||||
defp send_agent_input(args) do
|
||||
director_id = Map.get(args, "director_id")
|
||||
target_agent_id = Map.get(args, "target_agent_id")
|
||||
input_type = Map.get(args, "input_type")
|
||||
content = Map.get(args, "content")
|
||||
context = Map.get(args, "context", %{})
|
||||
|
||||
with {:ok, director} <- TaskRegistry.get_agent(director_id),
|
||||
true <- Agent.is_director?(director),
|
||||
{:ok, target_agent} <- TaskRegistry.get_agent(target_agent_id),
|
||||
true <- Agent.can_manage_agent?(director, target_agent) do
|
||||
# This would integrate with VSCode APIs to send input to agents
|
||||
# For now, return a placeholder that logs the action
|
||||
IO.puts(
|
||||
:stderr,
|
||||
"Director #{director_id} sending #{input_type} to agent #{target_agent_id}: #{content}"
|
||||
)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
director_id: director_id,
|
||||
target_agent_id: target_agent_id,
|
||||
input_type: input_type,
|
||||
content_length: String.length(content),
|
||||
context: context,
|
||||
status: "input_queued",
|
||||
timestamp: DateTime.utc_now(),
|
||||
note: "VSCode integration pending - input logged for future implementation"
|
||||
}}
|
||||
else
|
||||
{:error, :not_found} -> {:error, "Director or target agent not found"}
|
||||
false -> {:error, "Access denied: Director cannot manage target agent"}
|
||||
end
|
||||
end
|
||||
|
||||
# External MCP server management functions
|
||||
|
||||
defp start_external_server(name, %{type: :stdio} = config) do
|
||||
@@ -1338,6 +1816,7 @@ defmodule AgentCoordinator.MCPServer do
|
||||
port_options = [
|
||||
:binary,
|
||||
:stream,
|
||||
{:cd, workspace_root()},
|
||||
{:env, env_list},
|
||||
:exit_status,
|
||||
:hide
|
||||
@@ -1583,6 +2062,25 @@ defmodule AgentCoordinator.MCPServer do
|
||||
pid_file_path
|
||||
end
|
||||
|
||||
defp workspace_root do
|
||||
["MCP_WORKSPACE_DIR", "WORKSPACE_DIR"]
|
||||
|> Enum.find_value(fn var ->
|
||||
case System.get_env(var) do
|
||||
path when is_binary(path) and path != "" ->
|
||||
expanded = Path.expand(path)
|
||||
|
||||
if File.dir?(expanded), do: expanded, else: nil
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end)
|
||||
|> case do
|
||||
nil -> File.cwd!()
|
||||
path -> path
|
||||
end
|
||||
end
|
||||
|
||||
defp get_all_unified_tools_from_state(state) do
|
||||
# Combine coordinator tools with external server tools from state
|
||||
coordinator_tools = @mcp_tools
|
||||
@@ -1663,6 +2161,12 @@ defmodule AgentCoordinator.MCPServer do
|
||||
"get_detailed_task_board" -> get_detailed_task_board(args)
|
||||
"get_agent_task_history" -> get_agent_task_history(args)
|
||||
"discover_codebase_info" -> discover_codebase_info(args)
|
||||
"observe_all_agents" -> observe_all_agents(args)
|
||||
"modify_agent_tasks" -> modify_agent_tasks(args)
|
||||
"add_task_feedback" -> add_task_feedback(args)
|
||||
"detect_redundant_tasks" -> detect_redundant_tasks(args)
|
||||
"reassign_tasks" -> reassign_tasks(args)
|
||||
"send_agent_input" -> send_agent_input(args)
|
||||
_ -> {:error, "Unknown coordinator tool: #{tool_name}"}
|
||||
end
|
||||
end
|
||||
@@ -1789,7 +2293,19 @@ defmodule AgentCoordinator.MCPServer do
|
||||
end
|
||||
|
||||
defp load_server_config do
|
||||
config_file = System.get_env("MCP_CONFIG_FILE", "mcp_servers.json")
|
||||
workspace_dir = workspace_root()
|
||||
|
||||
config_file =
|
||||
case System.get_env("MCP_CONFIG_FILE") do
|
||||
nil ->
|
||||
Path.join(workspace_dir, "mcp_servers.json")
|
||||
path ->
|
||||
if Path.type(path) == :absolute do
|
||||
path
|
||||
else
|
||||
Path.expand(path, workspace_dir)
|
||||
end
|
||||
end
|
||||
|
||||
if File.exists?(config_file) do
|
||||
try do
|
||||
@@ -1797,20 +2313,23 @@ defmodule AgentCoordinator.MCPServer do
|
||||
%{"servers" => servers} ->
|
||||
normalized_servers =
|
||||
Enum.into(servers, %{}, fn {name, config} ->
|
||||
normalized_config = normalize_server_config(config)
|
||||
normalized_config =
|
||||
config
|
||||
|> normalize_server_config()
|
||||
|> update_workspace_paths(workspace_dir)
|
||||
{name, normalized_config}
|
||||
end)
|
||||
|
||||
%{servers: normalized_servers}
|
||||
|
||||
_ ->
|
||||
get_default_server_config()
|
||||
get_default_server_config(workspace_dir)
|
||||
end
|
||||
rescue
|
||||
_ -> get_default_server_config()
|
||||
_ -> get_default_server_config(workspace_dir)
|
||||
end
|
||||
else
|
||||
get_default_server_config()
|
||||
get_default_server_config(workspace_dir)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1828,13 +2347,28 @@ defmodule AgentCoordinator.MCPServer do
|
||||
end)
|
||||
end
|
||||
|
||||
defp get_default_server_config do
|
||||
defp update_workspace_paths(config, workspace_dir) do
|
||||
# Update filesystem server args to use the current workspace directory
|
||||
case config do
|
||||
%{command: "bunx", args: args} = config ->
|
||||
updated_args =
|
||||
case args do
|
||||
["-y", "@modelcontextprotocol/server-filesystem", _old_path | rest] ->
|
||||
["-y", "@modelcontextprotocol/server-filesystem", workspace_dir | rest]
|
||||
other -> other
|
||||
end
|
||||
Map.put(config, :args, updated_args)
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
|
||||
defp get_default_server_config(workspace_dir) do
|
||||
%{
|
||||
servers: %{
|
||||
"mcp_filesystem" => %{
|
||||
type: :stdio,
|
||||
command: "bunx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/ra"],
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", workspace_dir],
|
||||
auto_restart: true,
|
||||
description: "Filesystem operations server"
|
||||
},
|
||||
|
||||
@@ -17,7 +17,12 @@ defmodule AgentCoordinator.Task do
|
||||
:cross_codebase_dependencies,
|
||||
:created_at,
|
||||
:updated_at,
|
||||
:metadata
|
||||
:metadata,
|
||||
:feedback,
|
||||
:director_notes,
|
||||
:assignment_reason,
|
||||
:refinement_history,
|
||||
:blocking_issues
|
||||
]}
|
||||
defstruct [
|
||||
:id,
|
||||
@@ -32,7 +37,12 @@ defmodule AgentCoordinator.Task do
|
||||
:cross_codebase_dependencies,
|
||||
:created_at,
|
||||
:updated_at,
|
||||
:metadata
|
||||
:metadata,
|
||||
:feedback,
|
||||
:director_notes,
|
||||
:assignment_reason,
|
||||
:refinement_history,
|
||||
:blocking_issues
|
||||
]
|
||||
|
||||
@type status :: :pending | :in_progress | :completed | :failed | :blocked
|
||||
@@ -51,7 +61,12 @@ defmodule AgentCoordinator.Task do
|
||||
cross_codebase_dependencies: [%{codebase_id: String.t(), task_id: String.t()}],
|
||||
created_at: DateTime.t(),
|
||||
updated_at: DateTime.t(),
|
||||
metadata: map()
|
||||
metadata: map(),
|
||||
feedback: String.t() | nil,
|
||||
director_notes: String.t() | nil,
|
||||
assignment_reason: String.t() | nil,
|
||||
refinement_history: [map()],
|
||||
blocking_issues: [String.t()]
|
||||
}
|
||||
|
||||
def new(title, description, opts \\ []) do
|
||||
@@ -78,7 +93,12 @@ defmodule AgentCoordinator.Task do
|
||||
cross_codebase_dependencies: get_opt.(:cross_codebase_dependencies, []),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
metadata: get_opt.(:metadata, %{})
|
||||
metadata: get_opt.(:metadata, %{}),
|
||||
feedback: nil,
|
||||
director_notes: nil,
|
||||
assignment_reason: nil,
|
||||
refinement_history: [],
|
||||
blocking_issues: []
|
||||
}
|
||||
end
|
||||
|
||||
@@ -115,4 +135,109 @@ defmodule AgentCoordinator.Task do
|
||||
dependencies = [dependency | task.cross_codebase_dependencies]
|
||||
%{task | cross_codebase_dependencies: dependencies, updated_at: DateTime.utc_now()}
|
||||
end
|
||||
|
||||
# Director management functions
|
||||
|
||||
def add_feedback(task, feedback, director_id) do
|
||||
refinement_entry = %{
|
||||
type: "feedback_added",
|
||||
director_id: director_id,
|
||||
content: feedback,
|
||||
timestamp: DateTime.utc_now()
|
||||
}
|
||||
|
||||
%{
|
||||
task
|
||||
| feedback: feedback,
|
||||
refinement_history: [refinement_entry | task.refinement_history],
|
||||
updated_at: DateTime.utc_now()
|
||||
}
|
||||
end
|
||||
|
||||
def add_director_notes(task, notes, director_id) do
|
||||
refinement_entry = %{
|
||||
type: "director_notes_added",
|
||||
director_id: director_id,
|
||||
content: notes,
|
||||
timestamp: DateTime.utc_now()
|
||||
}
|
||||
|
||||
%{
|
||||
task
|
||||
| director_notes: notes,
|
||||
refinement_history: [refinement_entry | task.refinement_history],
|
||||
updated_at: DateTime.utc_now()
|
||||
}
|
||||
end
|
||||
|
||||
def set_assignment_reason(task, reason, director_id) do
|
||||
refinement_entry = %{
|
||||
type: "assignment_reason_set",
|
||||
director_id: director_id,
|
||||
reason: reason,
|
||||
timestamp: DateTime.utc_now()
|
||||
}
|
||||
|
||||
%{
|
||||
task
|
||||
| assignment_reason: reason,
|
||||
refinement_history: [refinement_entry | task.refinement_history],
|
||||
updated_at: DateTime.utc_now()
|
||||
}
|
||||
end
|
||||
|
||||
def add_blocking_issue(task, issue, director_id) do
|
||||
new_issues = [issue | task.blocking_issues] |> Enum.uniq()
|
||||
|
||||
refinement_entry = %{
|
||||
type: "blocking_issue_added",
|
||||
director_id: director_id,
|
||||
issue: issue,
|
||||
timestamp: DateTime.utc_now()
|
||||
}
|
||||
|
||||
%{
|
||||
task
|
||||
| blocking_issues: new_issues,
|
||||
refinement_history: [refinement_entry | task.refinement_history],
|
||||
updated_at: DateTime.utc_now()
|
||||
}
|
||||
end
|
||||
|
||||
def remove_blocking_issue(task, issue, director_id) do
|
||||
new_issues = task.blocking_issues |> Enum.reject(&(&1 == issue))
|
||||
|
||||
refinement_entry = %{
|
||||
type: "blocking_issue_removed",
|
||||
director_id: director_id,
|
||||
issue: issue,
|
||||
timestamp: DateTime.utc_now()
|
||||
}
|
||||
|
||||
%{
|
||||
task
|
||||
| blocking_issues: new_issues,
|
||||
refinement_history: [refinement_entry | task.refinement_history],
|
||||
updated_at: DateTime.utc_now()
|
||||
}
|
||||
end
|
||||
|
||||
def reassign(task, new_agent_id, director_id, reason) do
|
||||
refinement_entry = %{
|
||||
type: "task_reassigned",
|
||||
director_id: director_id,
|
||||
from_agent_id: task.agent_id,
|
||||
to_agent_id: new_agent_id,
|
||||
reason: reason,
|
||||
timestamp: DateTime.utc_now()
|
||||
}
|
||||
|
||||
%{
|
||||
task
|
||||
| agent_id: new_agent_id,
|
||||
assignment_reason: reason,
|
||||
refinement_history: [refinement_entry | task.refinement_history],
|
||||
updated_at: DateTime.utc_now()
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,20 +6,27 @@
|
||||
|
||||
set -e
|
||||
|
||||
CALLER_PWD="${PWD}"
|
||||
WORKSPACE_DIR="${MCP_WORKSPACE_DIR:-$CALLER_PWD}"
|
||||
|
||||
export PATH="$HOME/.asdf/shims:$PATH"
|
||||
|
||||
# Change to the project directory
|
||||
cd "$(dirname "$0")/.."
|
||||
export MCP_WORKSPACE_DIR="$WORKSPACE_DIR"
|
||||
|
||||
# Set environment
|
||||
export MIX_ENV="${MIX_ENV:-dev}"
|
||||
export NATS_HOST="${NATS_HOST:-localhost}"
|
||||
export NATS_PORT="${NATS_PORT:-4222}"
|
||||
|
||||
# Log startup
|
||||
# Log startup with workspace information
|
||||
echo "Starting AgentCoordinator Unified MCP Server..." >&2
|
||||
echo "Environment: $MIX_ENV" >&2
|
||||
echo "NATS: $NATS_HOST:$NATS_PORT" >&2
|
||||
echo "Caller PWD: $CALLER_PWD" >&2
|
||||
echo "Workspace Directory: $WORKSPACE_DIR" >&2
|
||||
echo "Agent Coordinator Directory: $(pwd)" >&2
|
||||
|
||||
# Start the Elixir application with unified MCP server
|
||||
exec mix run --no-halt -e "
|
||||
|
||||
@@ -10,10 +10,14 @@
|
||||
|
||||
set -e
|
||||
|
||||
CALLER_PWD="${PWD}"
|
||||
WORKSPACE_DIR="${MCP_WORKSPACE_DIR:-$CALLER_PWD}"
|
||||
|
||||
export PATH="$HOME/.asdf/shims:$PATH"
|
||||
|
||||
# Change to the project directory
|
||||
cd "$(dirname "$0")/.."
|
||||
export MCP_WORKSPACE_DIR="$WORKSPACE_DIR"
|
||||
|
||||
# Parse command line arguments
|
||||
INTERFACE_MODE="${1:-stdio}"
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Ultra-minimal test that doesn't start the full application
|
||||
|
||||
echo "🔬 Ultra-Minimal AgentCoordinator Test"
|
||||
echo "======================================"
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
echo "📋 Testing compilation..."
|
||||
if mix compile >/dev/null 2>&1; then
|
||||
echo "✅ Compilation successful"
|
||||
else
|
||||
echo "❌ Compilation failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📋 Testing MCP server without application startup..."
|
||||
if timeout 10 mix run --no-start -e "
|
||||
# Load compiled modules without starting application
|
||||
Code.ensure_loaded(AgentCoordinator.MCPServer)
|
||||
|
||||
# Test MCP server directly
|
||||
try do
|
||||
# Start just the required processes manually
|
||||
{:ok, _} = Registry.start_link(keys: :unique, name: AgentCoordinator.InboxRegistry)
|
||||
{:ok, _} = Phoenix.PubSub.start_link(name: AgentCoordinator.PubSub)
|
||||
|
||||
# Start TaskRegistry without NATS
|
||||
{:ok, _} = GenServer.start_link(AgentCoordinator.TaskRegistry, [nats: nil], name: AgentCoordinator.TaskRegistry)
|
||||
|
||||
# Start MCP server
|
||||
{:ok, _} = GenServer.start_link(AgentCoordinator.MCPServer, %{}, name: AgentCoordinator.MCPServer)
|
||||
|
||||
IO.puts('✅ Core components started')
|
||||
|
||||
# Test MCP functionality
|
||||
response = AgentCoordinator.MCPServer.handle_mcp_request(%{
|
||||
\"jsonrpc\" => \"2.0\",
|
||||
\"id\" => 1,
|
||||
\"method\" => \"tools/list\"
|
||||
})
|
||||
|
||||
case response do
|
||||
%{\"result\" => %{\"tools\" => tools}} when is_list(tools) ->
|
||||
IO.puts(\"✅ MCP server working (#{length(tools)} tools)\")
|
||||
_ ->
|
||||
IO.puts(\"❌ MCP server not working: #{inspect(response)}\")
|
||||
end
|
||||
|
||||
rescue
|
||||
e ->
|
||||
IO.puts(\"❌ Error: #{inspect(e)}\")
|
||||
end
|
||||
|
||||
System.halt(0)
|
||||
"; then
|
||||
echo "✅ Minimal test passed!"
|
||||
else
|
||||
echo "❌ Minimal test failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎉 Core MCP functionality works!"
|
||||
echo ""
|
||||
echo "📝 The hanging issue was due to NATS persistence trying to connect."
|
||||
echo " Your MCP server core functionality is working perfectly."
|
||||
echo ""
|
||||
echo "🚀 To run with proper NATS setup:"
|
||||
echo " 1. Make sure NATS server is running: sudo systemctl start nats"
|
||||
echo " 2. Or run: nats-server -js -p 4222 -m 8222 &"
|
||||
echo " 3. Then use: ../scripts/mcp_launcher.sh"
|
||||
@@ -1,54 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Quick test script to verify Agentecho "💡 Next steps:"
|
||||
echo " 1. Run scripts/setup.sh to configure VS Code integration"
|
||||
echo " 2. Or test manually with: scripts/mcp_launcher.sh"rdinator works without getting stuck
|
||||
|
||||
echo "🧪 Quick AgentCoordinator Test"
|
||||
echo "=============================="
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
echo "📋 Testing basic compilation..."
|
||||
if mix compile --force >/dev/null 2>&1; then
|
||||
echo "✅ Compilation successful"
|
||||
else
|
||||
echo "❌ Compilation failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📋 Testing application startup (without persistence)..."
|
||||
if timeout 10 mix run -e "
|
||||
Application.put_env(:agent_coordinator, :enable_persistence, false)
|
||||
{:ok, _apps} = Application.ensure_all_started(:agent_coordinator)
|
||||
IO.puts('✅ Application started successfully')
|
||||
|
||||
# Quick MCP server test
|
||||
response = AgentCoordinator.MCPServer.handle_mcp_request(%{
|
||||
\"jsonrpc\" => \"2.0\",
|
||||
\"id\" => 1,
|
||||
\"method\" => \"tools/list\"
|
||||
})
|
||||
|
||||
case response do
|
||||
%{\"result\" => %{\"tools\" => tools}} when is_list(tools) ->
|
||||
IO.puts(\"✅ MCP server working (#{length(tools)} tools available)\")
|
||||
_ ->
|
||||
IO.puts(\"❌ MCP server not responding correctly\")
|
||||
end
|
||||
|
||||
System.halt(0)
|
||||
"; then
|
||||
echo "✅ Quick test passed!"
|
||||
else
|
||||
echo "❌ Quick test failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎉 AgentCoordinator is ready!"
|
||||
echo ""
|
||||
echo "🚀 Next steps:"
|
||||
echo " 1. Run ./setup.sh to configure VS Code integration"
|
||||
echo " 2. Or test manually with: ./mcp_launcher.sh"
|
||||
echo " 3. Or run Python example: python3 mcp_client_example.py"
|
||||
@@ -145,7 +145,7 @@ if [ -f "$SETTINGS_FILE" ]; then
|
||||
echo "$MCP_CONFIG" | jq -s '.[0] * .[1]' "$SETTINGS_FILE" - > "$SETTINGS_FILE.tmp"
|
||||
mv "$SETTINGS_FILE.tmp" "$SETTINGS_FILE"
|
||||
else
|
||||
echo "⚠️ jq not found. Please manually add MCP configuration to $SETTINGS_FILE"
|
||||
echo "jq not found. Please manually add MCP configuration to $SETTINGS_FILE"
|
||||
echo "Add this configuration:"
|
||||
echo "$MCP_CONFIG"
|
||||
fi
|
||||
@@ -153,25 +153,25 @@ else
|
||||
echo "$MCP_CONFIG" > "$SETTINGS_FILE"
|
||||
fi
|
||||
|
||||
echo "✅ VS Code settings updated"
|
||||
echo "VS Code settings updated"
|
||||
|
||||
# Test MCP server
|
||||
echo -e "\n🧪 Testing MCP server..."
|
||||
echo -e "\nTesting MCP server..."
|
||||
cd "$PROJECT_DIR"
|
||||
if timeout 5 ./scripts/mcp_launcher.sh >/dev/null 2>&1; then
|
||||
echo "✅ MCP server test passed"
|
||||
echo "MCP server test passed"
|
||||
else
|
||||
echo "⚠️ MCP server test timed out (this is expected)"
|
||||
echo "MCP server test timed out (this is expected)"
|
||||
fi
|
||||
|
||||
# Create desktop shortcut for easy access
|
||||
echo -e "\n🖥️ Creating desktop shortcuts..."
|
||||
echo -e "\nCreating desktop shortcuts..."
|
||||
|
||||
# Start script
|
||||
cat > "$PROJECT_DIR/start_agent_coordinator.sh" << 'EOF'
|
||||
#!/bin/bash
|
||||
cd "$(dirname "$0")"
|
||||
echo "🚀 Starting AgentCoordinator..."
|
||||
echo "Starting AgentCoordinator..."
|
||||
|
||||
# Start NATS if not running
|
||||
if ! pgrep -f nats-server > /dev/null; then
|
||||
@@ -191,7 +191,7 @@ chmod +x "$PROJECT_DIR/start_agent_coordinator.sh"
|
||||
# Stop script
|
||||
cat > "$PROJECT_DIR/stop_agent_coordinator.sh" << 'EOF'
|
||||
#!/bin/bash
|
||||
echo "🛑 Stopping AgentCoordinator..."
|
||||
echo "Stopping AgentCoordinator..."
|
||||
|
||||
# Stop NATS if we started it
|
||||
if [ -f /tmp/nats.pid ]; then
|
||||
@@ -203,24 +203,24 @@ fi
|
||||
pkill -f "scripts/mcp_launcher.sh" || true
|
||||
pkill -f "agent_coordinator" || true
|
||||
|
||||
echo "✅ AgentCoordinator stopped"
|
||||
echo "AgentCoordinator stopped"
|
||||
EOF
|
||||
|
||||
chmod +x "$PROJECT_DIR/stop_agent_coordinator.sh"
|
||||
|
||||
echo "✅ Created start/stop scripts"
|
||||
echo "Created start/stop scripts"
|
||||
|
||||
# Final instructions
|
||||
echo -e "\n🎉 Setup Complete!"
|
||||
echo -e "\nSetup Complete!"
|
||||
echo "==================="
|
||||
echo ""
|
||||
echo "📋 Next Steps:"
|
||||
echo "Next Steps:"
|
||||
echo ""
|
||||
echo "1. 🔄 Restart VS Code to load the new MCP configuration"
|
||||
echo "1. Restart VS Code to load the new MCP configuration"
|
||||
echo " - Close all VS Code windows"
|
||||
echo " - Reopen VS Code in your project"
|
||||
echo ""
|
||||
echo "2. 🤖 GitHub Copilot should now have access to AgentCoordinator tools:"
|
||||
echo "2. GitHub Copilot should now have access to AgentCoordinator tools:"
|
||||
echo " - register_agent"
|
||||
echo " - create_task"
|
||||
echo " - get_next_task"
|
||||
@@ -233,14 +233,13 @@ echo " - Ask Copilot: 'Register me as an agent with coding capabilities'"
|
||||
echo " - Ask Copilot: 'Create a task to refactor the login module'"
|
||||
echo " - Ask Copilot: 'Show me the task board'"
|
||||
echo ""
|
||||
echo "📂 Useful files:"
|
||||
echo " Useful files:"
|
||||
echo " - Start server: $PROJECT_DIR/start_agent_coordinator.sh"
|
||||
echo " - Stop server: $PROJECT_DIR/stop_agent_coordinator.sh"
|
||||
echo " - Test client: $PROJECT_DIR/mcp_client_example.py"
|
||||
echo " - VS Code settings: $SETTINGS_FILE"
|
||||
echo ""
|
||||
echo "🔧 Manual start (if needed):"
|
||||
echo " cd $PROJECT_DIR && ./scripts/mcp_launcher.sh"
|
||||
echo ""
|
||||
echo "💡 Tip: The MCP server will auto-start when Copilot needs it!"
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
Reference in New Issue
Block a user