abcd118q commited on
Commit
598b366
·
verified ·
1 Parent(s): ee9be2d

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +317 -0
main.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import sys
4
+ import io
5
+ import contextlib
6
+ import urllib.request
7
+ import urllib.parse
8
+ from fastapi import FastAPI, Request, HTTPException
9
+ from fastapi.responses import HTMLResponse
10
+ from pydantic import BaseModel
11
+ from typing import Dict, Any, List
12
+
13
+ app = FastAPI(title="Composio Custom Self-Hosted Platform")
14
+
15
+ DATA_DIR = "/data"
16
+ SECRETS_FILE = os.path.join(DATA_DIR, "secrets.json") if os.path.exists(DATA_DIR) else "secrets.json"
17
+
18
+ def load_secrets():
19
+ if os.path.exists(SECRETS_FILE):
20
+ try:
21
+ with open(SECRETS_FILE, "r") as f:
22
+ return json.load(f)
23
+ except Exception:
24
+ return {}
25
+ return {"gemini_api_key": "", "github_client_id": "", "github_client_secret": "", "slack_token": ""}
26
+
27
+ def save_secrets(secrets):
28
+ with open(SECRETS_FILE, "w") as f:
29
+ json.dump(secrets, f, indent=4)
30
+
31
+ class SettingsPayload(BaseModel):
32
+ gemini_api_key: str
33
+ github_client_id: str
34
+ github_client_secret: str
35
+ slack_token: str
36
+
37
+ class CodePayload(BaseModel):
38
+ code: str
39
+
40
+ class MCPCallPayload(BaseModel):
41
+ method: str
42
+ params: Dict[str, Any]
43
+
44
+ # HTML Web Console layout
45
+ HTML_CONTENT = """
46
+ <!DOCTYPE html>
47
+ <html lang="en">
48
+ <head>
49
+ <meta charset="UTF-8">
50
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
51
+ <title>Composio Self-Hosted Dashboard</title>
52
+ <script src="https://cdn.tailwindcss.com"></script>
53
+ <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
54
+ </head>
55
+ <body class="bg-slate-950 text-slate-100 min-h-screen font-sans">
56
+ <nav class="border-b border-slate-800 bg-slate-900 px-6 py-4 flex justify-between items-center">
57
+ <div class="flex items-center space-x-3">
58
+ <div class="bg-cyan-500 text-slate-950 p-2 rounded-lg font-bold tracking-wider text-sm">COMPOSIO LOCAL</div>
59
+ <span class="text-xs text-slate-400 border border-slate-700 rounded px-2 py-0.5 bg-slate-950">V2.0 Self-Hosted</span>
60
+ </div>
61
+ <div class="flex items-center space-x-4">
62
+ <span class="flex items-center text-xs text-emerald-400 bg-emerald-950/50 border border-emerald-800 px-3 py-1 rounded-full">
63
+ <span class="w-2 h-2 rounded-full bg-emerald-400 mr-2 animate-pulse"></span> Persistent Storage Linked
64
+ </span>
65
+ </div>
66
+ </nav>
67
+
68
+ <div class="max-w-7xl mx-auto p-6 grid grid-cols-1 lg:grid-cols-4 gap-6">
69
+ <div class="space-y-2">
70
+ <button onclick="switchTab('credentials')" id="btn-credentials" class="w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium bg-slate-800 text-cyan-400 border-l-4 border-cyan-400 transition-all">
71
+ <i class="fa-solid fa-key w-5"></i> <span>Credential Vault</span>
72
+ </button>
73
+ <button onclick="switchTab('interpreter')" id="btn-interpreter" class="w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium text-slate-400 hover:bg-slate-900 transition-all">
74
+ <i class="fa-solid fa-terminal w-5"></i> <span>Code Interpreter Sandbox</span>
75
+ </button>
76
+ <button onclick="switchTab('mcp')" id="btn-mcp" class="w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium text-slate-400 hover:bg-slate-900 transition-all">
77
+ <i class="fa-solid fa-network-wired w-5"></i> <span>MCP Protocol Hub</span>
78
+ </button>
79
+ </div>
80
+
81
+ <div class="lg:col-span-3 bg-slate-900 border border-slate-800 rounded-xl p-6 min-h-[500px]">
82
+
83
+ <div id="tab-credentials" class="space-y-6">
84
+ <div>
85
+ <h2 class="text-xl font-semibold mb-1">Identity & Authentication Settings</h2>
86
+ <p class="text-sm text-slate-400">Manage client keys and integration profiles dynamically without a terminal.</p>
87
+ </div>
88
+ <div class="space-y-4 max-w-2xl">
89
+ <div>
90
+ <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">Gemini API Token</label>
91
+ <input type="password" id="gemini_api_key" class="w-full bg-slate-950 border border-slate-800 rounded-lg px-4 py-2.5 focus:outline-none focus:border-cyan-500 font-mono text-sm">
92
+ </div>
93
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
94
+ <div>
95
+ <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">GitHub Client ID</label>
96
+ <input type="text" id="github_client_id" class="w-full bg-slate-950 border border-slate-800 rounded-lg px-4 py-2.5 focus:outline-none focus:border-cyan-500 font-mono text-sm">
97
+ </div>
98
+ <div>
99
+ <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">GitHub Client Secret</label>
100
+ <input type="password" id="github_client_secret" class="w-full bg-slate-950 border border-slate-800 rounded-lg px-4 py-2.5 focus:outline-none focus:border-cyan-500 font-mono text-sm">
101
+ </div>
102
+ </div>
103
+ <div>
104
+ <label class="block text-xs font-semibold uppercase tracking-wider text-slate-400 mb-2">Slack Workspace Token</label>
105
+ <input type="password" id="slack_token" class="w-full bg-slate-950 border border-slate-800 rounded-lg px-4 py-2.5 focus:outline-none focus:border-cyan-500 font-mono text-sm">
106
+ </div>
107
+ <button onclick="saveConfig()" class="bg-cyan-500 text-slate-950 font-semibold text-sm px-6 py-2.5 rounded-lg hover:bg-cyan-400 transition-colors">
108
+ Commit Configurations to Storage
109
+ </button>
110
+ </div>
111
+ </div>
112
+
113
+ <div id="tab-interpreter" class="hidden space-y-6">
114
+ <div>
115
+ <h2 class="text-xl font-semibold mb-1">Code Execution Environment</h2>
116
+ <p class="text-sm text-slate-400">Run code snippets inside an isolated compute sandbox interface.</p>
117
+ </div>
118
+ <div class="space-y-4">
119
+ <textarea id="code-input" rows="8" class="w-full bg-slate-950 border border-slate-800 rounded-lg p-4 font-mono text-sm focus:outline-none focus:border-cyan-500" placeholder="print('Running calculations...')&#10;import math&#10;print(math.factorial(10))"></textarea>
120
+ <button onclick="runCode()" class="bg-cyan-500 text-slate-950 font-semibold text-sm px-6 py-2.5 rounded-lg hover:bg-cyan-400 transition-colors">
121
+ Execute Sandbox Script
122
+ </button>
123
+ <div class="border border-slate-800 rounded-lg bg-slate-950 p-4">
124
+ <div class="text-xs uppercase tracking-wider text-slate-500 mb-2 font-semibold">Console Output Logs</div>
125
+ <pre id="code-output" class="font-mono text-sm text-emerald-400 min-h-[100px] whitespace-pre-wrap">Execution console idle...</pre>
126
+ </div>
127
+ </div>
128
+ </div>
129
+
130
+ <div id="tab-mcp" class="hidden space-y-6">
131
+ <div>
132
+ <h2 class="text-xl font-semibold mb-1">Model Context Protocol Engine</h2>
133
+ <p class="text-sm text-slate-400">Bridge external development systems directly to your instance.</p>
134
+ </div>
135
+ <div class="bg-slate-950 border border-slate-800 rounded-lg p-4 space-y-3">
136
+ <div>
137
+ <span class="text-xs font-semibold text-slate-400 block uppercase mb-1">Target MCP Endpoint Discovery URL</span>
138
+ <code class="text-cyan-400 font-mono text-xs select-all break-all" id="mcp-url"></code>
139
+ </div>
140
+ </div>
141
+ <div class="border border-slate-800 rounded-lg overflow-hidden">
142
+ <table class="w-full text-left text-sm">
143
+ <thead class="bg-slate-950 text-slate-400 uppercase text-xs tracking-wider border-b border-slate-800">
144
+ <tr>
145
+ <th class="px-4 py-3">Feature Name</th>
146
+ <th class="px-4 py-3">Protocol Identity</th>
147
+ <th class="px-4 py-3">Operational Status</th>
148
+ </tr>
149
+ </thead>
150
+ <tbody class="divide-y divide-slate-800">
151
+ <tr>
152
+ <td class="px-4 py-3 font-semibold">Web Search Engine</td>
153
+ <td class="px-4 py-3 font-mono text-xs text-slate-400">web_search</td>
154
+ <td class="px-4 py-3"><span class="text-xs bg-emerald-950 text-emerald-400 border border-emerald-800 px-2 py-0.5 rounded">Active</span></td>
155
+ </tr>
156
+ <tr>
157
+ <td class="px-4 py-3 font-semibold">Code Interpreter Core</td>
158
+ <td class="px-4 py-3 font-mono text-xs text-slate-400">code_interpreter</td>
159
+ <td class="px-4 py-3"><span class="text-xs bg-emerald-950 text-emerald-400 border border-emerald-800 px-2 py-0.5 rounded">Active</span></td>
160
+ </tr>
161
+ </tbody>
162
+ </table>
163
+ </div>
164
+ </div>
165
+
166
+ </div>
167
+ </div>
168
+
169
+ <script>
170
+ document.getElementById('mcp-url').innerText = window.location.origin + '/mcp/v1/endpoint';
171
+
172
+ function switchTab(tabId) {
173
+ ['credentials', 'interpreter', 'mcp'].forEach(t => {
174
+ document.getElementById('tab-' + t).classList.add('hidden');
175
+ document.getElementById('btn-' + t).className = "w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium text-slate-400 hover:bg-slate-900 transition-all";
176
+ });
177
+ document.getElementById('tab-' + tabId).classList.remove('hidden');
178
+ document.getElementById('btn-' + tabId).className = "w-full flex items-center space-x-3 px-4 py-3 rounded-lg text-sm font-medium bg-slate-800 text-cyan-400 border-l-4 border-cyan-400 transition-all";
179
+ }
180
+
181
+ async function loadConfig() {
182
+ const res = await fetch('/api/settings');
183
+ const data = await res.json();
184
+ document.getElementById('gemini_api_key').value = data.gemini_api_key || '';
185
+ document.getElementById('github_client_id').value = data.github_client_id || '';
186
+ document.getElementById('github_client_secret').value = data.github_client_secret || '';
187
+ document.getElementById('slack_token').value = data.slack_token || '';
188
+ }
189
+
190
+ async function saveConfig() {
191
+ const payload = {
192
+ gemini_api_key: document.getElementById('gemini_api_key').value,
193
+ github_client_id: document.getElementById('github_client_id').value,
194
+ github_client_secret: document.getElementById('github_client_secret').value,
195
+ slack_token: document.getElementById('slack_token').value
196
+ };
197
+ const res = await fetch('/api/settings', {
198
+ method: 'POST',
199
+ headers: {'Content-Type': 'application/json'},
200
+ body: JSON.stringify(payload)
201
+ });
202
+ if (res.ok) alert('Settings saved permanently to /data!');
203
+ }
204
+
205
+ async function runCode() {
206
+ const outBox = document.getElementById('code-output');
207
+ outBox.innerText = 'Executing...';
208
+ const res = await fetch('/api/execute-code', {
209
+ method: 'POST',
210
+ headers: {'Content-Type': 'application/json'},
211
+ body: JSON.stringify({code: document.getElementById('code-input').value})
212
+ });
213
+ const data = await res.json();
214
+ outBox.innerText = data.output || data.error;
215
+ }
216
+
217
+ window.onload = loadConfig;
218
+ </script>
219
+ </body>
220
+ </html>
221
+ """
222
+
223
+ @app.get("/", response_class=HTMLResponse)
224
+ def index():
225
+ return HTML_CONTENT
226
+
227
+ @app.get("/api/settings")
228
+ def get_settings():
229
+ return load_secrets()
230
+
231
+ @app.post("/api/settings")
232
+ def save_settings(payload: SettingsPayload):
233
+ save_secrets(payload.model_dump())
234
+ return {"status": "success"}
235
+
236
+ @app.post("/api/execute-code")
237
+ def run_code(payload: CodePayload):
238
+ # Core Code Interpreter Engine Logic
239
+ output_capture = io.StringIO()
240
+ with contextlib.redirect_stdout(output_capture), contextlib.redirect_stderr(output_capture):
241
+ try:
242
+ # Create isolated local execution context
243
+ local_scope = {}
244
+ exec(payload.code, {"__builtins__": __builtins__}, local_scope)
245
+ result = output_capture.getvalue()
246
+ return {"output": result if result else "Execution completed with empty return payload."}
247
+ except Exception as e:
248
+ return {"error": f"Execution Traceback Failure: {str(e)}"}
249
+
250
+ # Core Custom Search Engine Utility
251
+ def execute_web_search(query: str) -> str:
252
+ try:
253
+ url = f"https://html.duckduckgo.com/html/?q={urllib.parse.quote(query)}"
254
+ req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
255
+ with urllib.request.urlopen(req, timeout=6) as response:
256
+ html = response.read().decode('utf-8')
257
+ # Extract basic readable textual paragraphs from the markup body
258
+ from xml.etree import ElementTree
259
+ import re
260
+ text_snippets = re.findall(r'<a class="element--title"[^>]*>(.*?)</a>.*<p class="element--snippet"[^>]*>(.*?)</p>', html, re.DOTALL)
261
+ results = []
262
+ for title, snippet in text_snippets[:3]:
263
+ clean_title = re.sub('<[^<]+?>', '', title).strip()
264
+ clean_snippet = re.sub('<[^<]+?>', '', snippet).strip()
265
+ results.append(f"Result: {clean_title} - {clean_snippet}")
266
+ return "\\n".join(results) if results else "Search completed. No matches returned."
267
+ except Exception as e:
268
+ return f"Search Provider Error: {str(e)}"
269
+
270
+ # Model Context Protocol (MCP) Router Specification Layer
271
+ @app.post("/mcp/v1/endpoint")
272
+ async def mcp_server_router(payload: MCPCallPayload):
273
+ if payload.method == "tools/list":
274
+ return {
275
+ "tools": [
276
+ {
277
+ "name": "web_search",
278
+ "description": "Query live search indexes to retrieve real-time documents and technical context.",
279
+ "inputSchema": {
280
+ "type": "object",
281
+ "properties": {"query": {"type": "string"}},
282
+ "required": ["query"]
283
+ }
284
+ },
285
+ {
286
+ "name": "code_interpreter",
287
+ "description": "Execute arbitrary runtime Python modules and return calculations or modifications.",
288
+ "inputSchema": {
289
+ "type": "object",
290
+ "properties": {"code": {"type": "string"}},
291
+ "required": ["code"]
292
+ }
293
+ }
294
+ ]
295
+ }
296
+
297
+ elif payload.method == "tools/call":
298
+ tool_name = payload.params.get("name")
299
+ args = payload.params.get("arguments", {})
300
+
301
+ if tool_name == "web_search":
302
+ res = execute_web_search(args.get("query", ""))
303
+ return {"content": [{"type": "text", "text": res}]}
304
+ elif tool_name == "code_interpreter":
305
+ output_capture = io.StringIO()
306
+ with contextlib.redirect_stdout(output_capture), contextlib.redirect_stderr(output_capture):
307
+ try:
308
+ exec(args.get("code", ""), {}, {})
309
+ res = output_capture.getvalue()
310
+ except Exception as e:
311
+ res = str(e)
312
+ return {"content": [{"type": "text", "text": res}]}
313
+ else:
314
+ raise HTTPException(status_code=444, detail="Target protocol signature unrecognized.")
315
+
316
+ else:
317
+ raise HTTPException(status_code=400, detail="Method parameter unsupported by core definition.")