-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_api.py
More file actions
246 lines (198 loc) · 7.59 KB
/
http_api.py
File metadata and controls
246 lines (198 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
#!/usr/bin/env python3
"""
HTTP REST API wrapper for coordination-mcp.
Exposes MCP tools as REST endpoints for HTTP clients.
Runs on port 8000 for backwards compatibility.
"""
import os
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent
os.chdir(REPO_ROOT)
sys.path.insert(0, str(REPO_ROOT))
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Any, Dict, List, Optional
import uvicorn
# Import stores directly
from coordination_mcp.stores_db.proposals_db import ProposalStore
from coordination_mcp.stores_db.tasks_db import TaskStore
from coordination_mcp.stores_db.events_db import EventStore
from coordination_mcp.stores_db.plans_db import PlanStore
from coordination_mcp.stores_db.metrics_db import MetricsStore
from coordination_mcp.stores_db.sessions_db import SessionStore
# Initialize stores
proposal_store = ProposalStore()
task_store = TaskStore()
event_store = EventStore(EVENT_TYPES={
"proposal_created", "proposal_approved", "proposal_rejected",
"proposal_filtered", "proposal_planned",
"task_queued", "execution_started", "execution_complete",
"daemon_started", "daemon_stopped", "daemon_cycle", "daemon_error",
"daemon_generate_start", "daemon_generate_failed", "daemon_generate_complete",
"scan_complete", "filter_complete", "learning_update",
})
plan_store = PlanStore()
metrics_store = MetricsStore()
session_store = SessionStore()
app = FastAPI(title="Coordination MCP HTTP API", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ----------------------------------------------------------------
# Models
# ----------------------------------------------------------------
class ProposalCreate(BaseModel):
source: str
raw_item: Dict[str, Any]
proof_packet: Optional[Dict[str, Any]] = None
class ProposalUpdate(BaseModel):
status: str
data: Optional[Dict[str, Any]] = None
class MCPCall(BaseModel):
tool: str
params: Dict[str, Any]
# ----------------------------------------------------------------
# Health
# ----------------------------------------------------------------
@app.get("/healthz")
def healthz():
return {"ok": True}
@app.get("/mcp/healthz")
def mcp_healthz():
return {"ok": True}
# ----------------------------------------------------------------
# Generic MCP tool call (for compatibility)
# ----------------------------------------------------------------
@app.post("/mcp")
async def mcp_call(req: MCPCall):
"""Generic MCP tool invocation endpoint."""
tool = req.tool
params = req.params
try:
if tool == "healthz":
return {"result": {"ok": True}}
elif tool == "proposal_create":
proposal_id = params.get("id") or f"proposal-{os.urandom(4).hex()}"
proposal_data = {
"source": params.get("source", "unknown"),
"raw_item": params.get("raw_item", {}),
"proof_packet": params.get("proof_packet"),
"status": params.get("status", "created"),
}
success = proposal_store.create(proposal_id, proposal_data)
return {"result": {"success": success, "id": proposal_id}}
elif tool == "proposal_update":
result = proposal_store.update(
params["id"],
params["status"],
params.get("data", {})
)
return {"result": result}
elif tool == "proposal_list":
result = proposal_store.list_proposals(params.get("status_filter"))
return {"result": result}
elif tool == "proposal_get":
result = proposal_store.get(params["id"])
return {"result": result}
elif tool == "task_queue":
result = task_store.create(
f"task-{os.urandom(4).hex()}",
params["proposal_id"]
)
return {"result": result}
elif tool == "task_status":
result = task_store.get(params["task_id"])
return {"result": result}
elif tool == "event_publish":
event = params.get("event", params)
result = event_store.log_event(event)
return {"result": result}
elif tool == "plan_create":
result = plan_store.create(
params["proposal_id"],
params["manifest"]
)
return {"result": result}
elif tool == "plan_get":
result = plan_store.get(params.get("id", ""))
return {"result": result}
elif tool == "learning_record":
# Just log it
return {"result": True}
elif tool == "learning_summary":
return {"result": {"available": True}}
elif tool == "metrics_record":
result = metrics_store.record(
params["model"],
params.get("latency", 0),
params.get("tokens", 0),
params.get("success", True)
)
return {"result": result}
else:
raise HTTPException(400, f"Unknown tool: {tool}")
except Exception as e:
return {"error": str(e)}
# ----------------------------------------------------------------
# Direct REST endpoints (for telegram bot compatibility)
# ----------------------------------------------------------------
@app.get("/proposals")
def list_proposals(status: Optional[str] = None):
"""List all proposals."""
proposals = proposal_store.list_proposals(status)
return {"proposals": proposals}
@app.get("/proposals/{proposal_id}")
def get_proposal(proposal_id: str):
"""Get a single proposal."""
proposal = proposal_store.get(proposal_id)
if not proposal:
raise HTTPException(404, "Proposal not found")
return proposal
@app.post("/proposals")
def create_proposal(req: ProposalCreate):
"""Create a new proposal."""
import uuid
proposal_id = f"proposal-{uuid.uuid4().hex[:8]}"
proposal_data = {
"id": proposal_id,
"source": req.source,
**req.raw_item,
"status": "pending",
}
if req.proof_packet:
proposal_data["proof_packet"] = req.proof_packet
proposal_store.create(proposal_id, proposal_data)
return proposal_data
@app.post("/proposals/approve")
def approve_proposal(proposal_id: str, approved_by: str = "human"):
"""Approve a proposal."""
proposal = proposal_store.get(proposal_id)
if not proposal:
raise HTTPException(404, "Proposal not found")
proposal_store.update(proposal_id, "approved", {
"approved_by": approved_by,
})
return {"success": True, "proposal_id": proposal_id}
@app.post("/proposals/reject")
def reject_proposal(proposal_id: str, reason: str, rejected_by: str = "human"):
"""Reject a proposal."""
proposal = proposal_store.get(proposal_id)
if not proposal:
raise HTTPException(404, "Proposal not found")
proposal_store.update(proposal_id, "rejected", {
"rejected_by": rejected_by,
"rejection_reason": reason,
})
return {"success": True, "proposal_id": proposal_id}
# ----------------------------------------------------------------
# Main
# ----------------------------------------------------------------
if __name__ == "__main__":
host = os.environ.get("HTTP_HOST", "127.0.0.1")
port = int(os.environ.get("HTTP_PORT", "8000"))
uvicorn.run(app, host=host, port=port)