π 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.
π¬ Demo

See Loopgate in action: AI agent requests human approval via Telegram, human responds, and the agent receives the decision in real-time.
π Table of Contents
π― 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
β‘ Quick Start
1. Setup
# Clone the repository
git clone https://github.com/iris-networks/loopgate
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
Using PostgreSQL with Docker
If you prefer to use PostgreSQL as the database, you can use the provided Docker Compose setup.
Start PostgreSQL:
make docker-compose
Configure Environment Variables:
Update your environment variables to use the PostgreSQL database.
export DB_ADAPTER=postgres
export DB_URI="host=localhost port=5432 user=loopgate password=loopgate dbname=loopgate sslmode=disable"
Run the server:
make run
2. Register Your AI Agent Session
Testing the Human-in-the-Loop Flow
We've included an example HTTP client that you can use to test the entire HITL flow.
Start the server:
make run
Run the example client:
In a new terminal, run the following command. Make sure to replace 123456789 with your actual Telegram user ID. You can get your Telegram user ID by talking to the @userinfobot bot on Telegram.
go run examples/http_client_example.go
You should see output indicating that a session has been registered and a request has been submitted. You will then receive a message on Telegram asking for your input. After you respond, you will see the client print the result.
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
import time
# 1. Submit request
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()
request_id = result["request_id"]
print(f"β
Request submitted: {request_id}")
# 2. Poll for human response
while True:
poll_response = requests.get(f'http://localhost:8080/hitl/poll?request_id={request_id}')
status = poll_response.json()
if status["status"] == "completed":
if status["approved"]:
print("π Deployment approved! Proceeding...")
# Execute deployment
else:
print(f"π Deployment denied: {status['response']}")
break
print("β³ Waiting for human response...")
time.sleep(5)
4. User Account and API Key Management (New)
Loopgate now supports user accounts and API key generation for securing access to its services. Here's how to interact with these new endpoints using curl:
a. Register a New User
curl -X POST http://localhost:8080/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "SecurePassword123!"
}'
# Expected response (201 Created):
# {
# "message": "User registered successfully",
# "user_id": "<user_uuid>"
# }
b. Login as a User
This will return a JWT (JSON Web Token) needed for API key management.
curl -X POST http://localhost:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "SecurePassword123!"
}'
# Expected response (200 OK):
# {
# "token": "<YOUR_JWT_TOKEN>",
# "user_id": "<user_uuid>",
# "username": "testuser"
# }
Note: Copy the token value. You'll need it for the next steps.
c. Create an API Key
Replace <YOUR_JWT_TOKEN> with the token obtained from the login step.
export JWT_TOKEN="<YOUR_JWT_TOKEN>" # Store your JWT in an environment variable
curl -X POST http://localhost:8080/api/user/apikeys \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $JWT_TOKEN" \
-d '{
"label": "My Test Key"
}'
# Expected response (201 Created):
# {
# "id": "<api_key_uuid>",
# "raw_key": "lk_pub_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", # Store this securely!
# "label": "My Test Key",
# "prefix": "lk_pub_",
# "expires_at": null,
# "created_at": "YYYY-MM-DDTHH:MM:SSZ"
# }
Important: The raw_key is shown only once. Make sure to save it immediately and securely.
d. List API Keys
curl -X GET http://localhost:8080/api/user/apikeys \
-H "Authorization: Bearer $JWT_TOKEN"
# Expected response (200 OK):
# [
# {
# "id": "<api_key_uuid>",
# "label": "My Test Key",
# "prefix": "lk_pub_",
# "last_used_at": null,
# "expires_at": null,
# "created_at": "YYYY-MM-DDTHH:MM:SSZ",
# "is_active": true
# }
# ]
e. Revoke an API Key
Replace <API_KEY_ID_TO_REVOKE> with the id of the key you want to revoke (from the list or create response).
export API_KEY_ID_TO_REVOKE="<api_key_uuid>"
curl -X DELETE http://localhost:8080/api/user/apikeys/$API_KEY_ID_TO_REVOKE \
-H "Authorization: Bearer $JWT_TOKEN"
# Expected response (200 OK):
# {
# "message": "API key revoked successfully"
# }
f. Using an API Key
Once you have a raw_key, you can use it to authenticate requests to API key-protected endpoints (specific endpoints TBD or configured by admin).
export MY_API_KEY="<YOUR_RAW_API_KEY>" # e.g., lk_pub_xxxxxxxx...
# Example: Accessing a hypothetical protected endpoint
curl -X GET http://localhost:8080/api/saas/some-data \
-H "Authorization: Bearer $MY_API_KEY"
# or
curl -X GET http://localhost:8080/api/saas/some-data \
-H "X-API-Key: $MY_API_KEY"
For more details on these API endpoints, see the API Reference.
π 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 |
| β‘ Async by Default |
Non-blocking requests with polling and webhooks |
| π 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
response = requests.post('http://localhost:8080/hitl/request', json={
"session_id": "deploy-agent",
"client_id": "ci-cd-pipeline",
"message": "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 response = await fetch('http://localhost:8080/hitl/request', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
session_id: "trading-bot",
client_id: "algo-trader",
message: "Execute large trade: Buy 10,000 AAPL at $150.25",
options: ['Execute', 'Cancel', 'Reduce Size'],
metadata: { symbol: 'AAPL', value: '$1,502,500', risk_score: 'Medium' }
})
});
π₯ Healthcare AI
// Medical AI requests doctor approval using MCP client
client := client.NewMCPClient()
client.ConnectToServer("./loopgate")
client.Initialize("MedicalAI", "1.0.0")
response, err := client.SendHITLRequest(
"medical-session",
"diagnostic-ai",
"Recommend immediate surgery for patient #1234?",
[]string{"Approve", "Reject", "Request Second Opinion"},
map[string]interface{}{
"patient_id": "1234",
"condition": "appendicitis",
"confidence": "89%",
},
)
π€ Content Moderation
# Content AI escalates edge cases to human moderators
response = requests.post('http://localhost:8080/hitl/request', json={
"session_id": "content-mod",
"client_id": "moderation-ai",
"message": "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
See API Reference for detailed documentation of MCP tools and HTTP endpoints.
π§ Configuration
Environment Variables
# Required
TELEGRAM_BOT_TOKEN=your_telegram_bot_token
# Optional
SERVER_PORT=8080 # Default: 8080
LOG_LEVEL=info # Default: info
REQUEST_TIMEOUT=300 # Default: 300 seconds
MAX_CONCURRENT_REQUESTS=100 # Default: 100
Docker Support
# Build Docker image
make docker-build
# Run with Docker
docker run -e TELEGRAM_BOT_TOKEN=your_token loopgate:latest
π Client SDKs
Go MCP Client
import "loopgate/pkg/client"
client := client.NewMCPClient()
client.ConnectToServer("./loopgate")
client.Initialize("MyAI", "1.0.0")
response, err := client.SendHITLRequest(
"session-1",
"my-ai",
"Approve this action?",
[]string{"Yes", "No"},
map[string]interface{}{"context": "deployment"},
)
Python HTTP Client