Thanks to visit codestin.com
Credit goes to github.com

Skip to content

anascann/loopgate

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”„ Loopgate

The Model Context Protocol (MCP) server that empowers AI agents with human oversight

Loopgate is a high-performance, Golang-based MCP server that bridges AI agents and human operators for seamless Human-in-the-Loop (HITL) workflows. With real-time communication via Telegram, Loopgate ensures AI systems stay intelligent, compliant, and human-approved.

Build Status Go Version MCP Version License

🎯 Why Loopgate?

In a world driven by automation, human wisdom remains essential. Loopgate enables AI agents to pause for human input, ensuring confidence in high-stakes decisions, compliance, or complex workflows.

graph LR
    A[AI Agent] -->|HITL Request| B[Loopgate Server]
    B -->|Send Message| C[Telegram]
    C -->|Human Response| B
    B -->|Response| A
Loading

⚑ Quick Start

1. Setup

# Clone the repository
git clone https://github.com/your-username/loopgate.git
cd loopgate

# Build the server
make build

# Set environment variables
export TELEGRAM_BOT_TOKEN="7123456789:AAEhBOweik6ad6PsWZRcXUgPaGFhqOClv"
export SERVER_PORT=8080

# Run the server
make run

2. Register Your AI Agent Session

curl -X POST http://localhost:8080/hitl/register \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "production-deploy-bot",
    "client_id": "ci-cd-pipeline", 
    "telegram_id": 123456789
  }'

3. Send HITL Request from Your AI Agent

import requests

# Your AI agent requests human approval
response = requests.post('http://localhost:8080/hitl/request', json={
    "session_id": "production-deploy-bot",
    "client_id": "ci-cd-pipeline",
    "message": "Deploy v2.1.0 to production? All tests passed βœ…",
    "options": ["πŸš€ Deploy", "⏸️ Hold", "πŸ” Review First"],
    "metadata": {
        "version": "v2.1.0",
        "tests_passed": 847,
        "code_coverage": "94.2%",
        "environment": "production"
    }
})

result = response.json()
if result["approved"]:
    print("πŸŽ‰ Deployment approved! Proceeding...")
    # Execute deployment
else:
    print(f"πŸ›‘ Deployment denied: {result['response']}")

🌟 Key Features

Feature Description
πŸ€– Multi-Agent Support Handle requests from multiple AI agents simultaneously
πŸ“± Telegram Integration Real-time communication through Telegram Bot API
πŸ”„ MCP Protocol Full Model Context Protocol 2.0 implementation
⚑ High Performance Built with Go for speed and concurrency
πŸ“Š Session Management Persistent session tracking and routing
πŸ”§ Flexible APIs HTTP REST + MCP protocol support

πŸ’‘ Use Cases

πŸš€ Production Deployments

# AI requests approval before deploying to production
await loopgate.request_approval(
    "Deploy new ML model to production?",
    options=["Deploy", "Cancel", "Deploy to Staging First"],
    metadata={"model": "recommendation-v2.1", "accuracy": "94.2%"}
)

πŸ’° Financial Trading

// Trading bot requests approval for large orders
const approval = await loopgate.requestApproval(
    `Execute large trade: Buy 10,000 AAPL at $150.25`,
    ['Execute', 'Cancel', 'Reduce Size'],
    { symbol: 'AAPL', value: '$1,502,500', risk_score: 'Medium' }
);

πŸ₯ Healthcare AI

// Medical AI requests doctor approval
response, err := client.SendHITLRequest(ctx, HITLRequest{
    Message: "Recommend immediate surgery for patient #1234?",
    Options: []string{"Approve", "Reject", "Request Second Opinion"},
    Metadata: map[string]interface{}{
        "patient_id": "1234",
        "condition": "appendicitis", 
        "confidence": "89%",
    },
})

πŸ€– Content Moderation

# Content AI escalates edge cases to human moderators
await loopgate.request_approval(
    "Flag this content as inappropriate?",
    options=["Flag", "Approve", "Needs Review"],
    metadata={"content_type": "image", "ai_confidence": 0.75}
)

πŸ› οΈ Architecture

Loopgate implements a robust, event-driven architecture:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ AI Agent A  β”‚    β”‚ AI Agent B  β”‚    β”‚ AI Agent C  β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚                  β”‚                  β”‚
       β”‚ MCP Protocol     β”‚ HTTP API         β”‚ WebSocket
       β”‚                  β”‚                  β”‚
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                          β”‚
                    β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
                    β”‚ Loopgate  β”‚
                    β”‚  Server   β”‚
                    β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
                          β”‚
                    β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
                    β”‚ Telegram  β”‚
                    β”‚   Bot     β”‚
                    β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
                          β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β”‚               β”‚               β”‚
    β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”
    β”‚ Human A   β”‚  β”‚ Human B   β”‚  β”‚ Human C   β”‚
    β”‚ Operator  β”‚  β”‚ Operator  β”‚  β”‚ Operator  β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“‘ API Reference

MCP Protocol Tools

Loopgate exposes MCP tools for seamless AI agent integration:

hitl_request

Send human-in-the-loop requests via MCP protocol.

{
  "name": "hitl_request",
  "arguments": {
    "session_id": "my-agent-session",
    "client_id": "my-ai-agent",
    "message": "Should I proceed with this action?",
    "options": ["Yes", "No", "Maybe"],
    "metadata": {"key": "value"}
  }
}

HTTP Endpoints

Endpoint Method Description
/hitl/register POST Register AI agent session
/hitl/request POST Send HITL request
/hitl/status GET Check session status
/hitl/deactivate POST Deactivate session
/health GET Server health check
/mcp POST MCP protocol endpoint

πŸ”§ Configuration

Environment Variables

# Required
TELEGRAM_BOT_TOKEN=your_telegram_bot_token

# Optional  
SERVER_PORT=8080                 # Default: 8080
LOG_LEVEL=info                   # Default: info

Docker Support

# Build Docker image
make docker-build

# Run with Docker
docker run -e TELEGRAM_BOT_TOKEN=your_token loopgate:latest

πŸ“š Client SDKs

Go SDK

import "loopgate/pkg/client"

client := client.NewMCPClient()
client.ConnectToServer("./loopgate")
client.Initialize("MyAI", "1.0.0")

response, err := client.SendHITLRequest(ctx, HITLRequest{
    SessionID: "session-1",
    ClientID:  "my-ai",
    Message:   "Approve this action?",
})

Python SDK

import requests

class LoopgateClient:
    def __init__(self, base_url="http://localhost:8080"):
        self.base_url = base_url
    
    def request_approval(self, session_id, message, options=None):
        # Implementation details...

Node.js SDK

const { LoopgateClient } = require('loopgate-client');

const client = new LoopgateClient('http://localhost:8080');
const response = await client.requestApproval(sessionId, message, options);

πŸ§ͺ Example Integrations

Claude with MCP

// Claude's Model Context Protocol integration
const server = new MCPServer({
  name: "loopgate-integration",
  version: "1.0.0"
});

server.addTool({
  name: "request_human_approval",
  description: "Request human approval for actions",
  parameters: {
    message: { type: "string" },
    options: { type: "array" }
  },
  handler: async (params) => {
    return await loopgate.requestApproval(params.message, params.options);
  }
});

OpenAI Function Calling

import openai

def request_human_approval(message: str, options: list) -> dict:
    """Request human approval via Loopgate"""
    # Call Loopgate API
    return loopgate_client.request_approval(message, options)

# Register as OpenAI function
functions = [{
    "name": "request_human_approval",
    "description": "Request human approval for sensitive actions",
    "parameters": {
        "type": "object",
        "properties": {
            "message": {"type": "string"},
            "options": {"type": "array"}
        }
    }
}]

πŸš€ Production Deployment

Prerequisites

  • Go 1.21+
  • Telegram Bot Token
  • PostgreSQL (optional, for persistent storage)

Deployment Options

Traditional Server

# Build for production
make build

# Run with systemd
sudo systemctl enable loopgate
sudo systemctl start loopgate

Docker

FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -o loopgate cmd/server/main.go

FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=builder /app/loopgate .
CMD ["./loopgate"]

Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: loopgate
spec:
  replicas: 3
  selector:
    matchLabels:
      app: loopgate
  template:
    metadata:
      labels:
        app: loopgate
    spec:
      containers:
      - name: loopgate
        image: loopgate:latest
        env:
        - name: TELEGRAM_BOT_TOKEN
          valueFrom:
            secretKeyRef:
              name: loopgate-secret
              key: token

πŸ“Š Monitoring

Metrics

Loopgate exposes Prometheus metrics at /metrics:

# HELP loopgate_hitl_requests_total Total HITL requests
# TYPE loopgate_hitl_requests_total counter
loopgate_hitl_requests_total{client_id="production-bot"} 1234

# HELP loopgate_active_sessions Current active sessions  
# TYPE loopgate_active_sessions gauge
loopgate_active_sessions 5

# HELP loopgate_response_time_seconds HITL response time
# TYPE loopgate_response_time_seconds histogram

Health Checks

# Basic health check
curl http://localhost:8080/health

# Detailed status
curl http://localhost:8080/hitl/status?session_id=my-session

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/your-username/loopgate.git
cd loopgate
make deps
make test
make run

Running Tests

make test          # Run all tests
make test-coverage # Run tests with coverage
make lint          # Run linter

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

🌟 Star History

Star History Chart


Loopgate: Where AI meets human wisdom for smarter, safer automation.

Made with ❀️ by the Loopgate team

About

Central broker to support Human-in-the-Loop (HITL) workflows for AI agents

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Go 96.4%
  • Makefile 2.9%
  • Dockerfile 0.7%