File size: 7,923 Bytes
2021f39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# Minimal MCP-style tools server.
# Endpoints:
# - GET /health
# - GET /tools  -> list available tools and schemas
# - POST /call  -> {"tool": "calculator", "input": "sqrt(144)"}

import os
import re
import ast
import math
import json
from typing import Dict, Any

import requests
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import uvicorn
from prometheus_client import Counter, Histogram, make_asgi_app
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export import ConsoleSpanExporter

PORT = int(os.getenv("PORT", "7001"))

app = FastAPI(title="Nova Tools MCP", version="0.1.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

REQUESTS = Counter("mcp_requests_total", "MCP requests", ["route"])
LATENCY = Histogram("mcp_request_latency_seconds", "Latency", ["route"])

# OTel tracer to console
resource = Resource.create({"service.name": "nova-tools-mcp"})
provider = TracerProvider(resource=resource)
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)


def safe_calc_eval(expr: str) -> str:
    allowed_funcs = {
        'sqrt': math.sqrt, 'log': math.log, 'log10': math.log10,
        'sin': math.sin, 'cos': math.cos, 'tan': math.tan,
        'exp': math.exp, 'pow': math.pow, 'abs': abs,
        'floor': math.floor, 'ceil': math.ceil
    }
    allowed_names = {'pi': math.pi, 'e': math.e, **allowed_funcs}

    def eval_node(node: ast.AST):
        if isinstance(node, ast.Expression):
            return eval_node(node.body)
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)):
            val = eval_node(node.operand)
            return +val if isinstance(node.op, ast.UAdd) else -val
        if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod, ast.Pow, ast.FloorDiv)):
            left, right = eval_node(node.left), eval_node(node.right)
            return {
                ast.Add: lambda a, b: a + b,
                ast.Sub: lambda a, b: a - b,
                ast.Mult: lambda a, b: a * b,
                ast.Div: lambda a, b: a / b,
                ast.Mod: lambda a, b: a % b,
                ast.Pow: lambda a, b: a ** b,
                ast.FloorDiv: lambda a, b: a // b,
            }[type(node.op)](left, right)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
            func_name = node.func.id
            if func_name not in allowed_funcs:
                raise ValueError(f"Function '{func_name}' not allowed")
            args = [eval_node(arg) for arg in node.args]
            return allowed_funcs[func_name](*args)
        if isinstance(node, ast.Name) and node.id in allowed_names:
            return allowed_names[node.id]
        raise ValueError("Unsupported expression")

    tree = ast.parse(expr, mode='eval')
    return str(eval_node(tree))


def http_get(url: str) -> str:
    try:
        r = requests.get(url, timeout=10)
        r.raise_for_status()
        title = re.search(r"<title[^>]*>(.*?)</title>", r.text or "", flags=re.I|re.S)
        t = title.group(1).strip() if title else "(no title)"
        preview = re.sub(r"\s+", " ", (r.text or ""))[:300]
        return f"title: {t}\npreview: {preview}"
    except Exception as e:
        return f"http_get error: {e}"


TOOLS = {
    "calculator": {
        "schema": {"type": "object", "properties": {"input": {"type": "string"}}, "required": ["input"]},
        "run": lambda arg: safe_calc_eval(arg),
    },
    "http_get": {
        "schema": {"type": "object", "properties": {"input": {"type": "string", "format": "uri"}}, "required": ["input"]},
        "run": lambda url: http_get(url),
    },
    "time": {
        "schema": {"type": "object", "properties": {"input": {"type": "string"}}, "required": []},
        "run": lambda _=None: __import__("datetime").datetime.now().isoformat(),
    },
}

_DYNAMIC: Dict[str, Dict[str, Any]] = {}


@app.get("/health")
def health() -> Dict[str, Any]:
    REQUESTS.labels(route="health").inc()
    return {"status": "ok", "port": PORT, "dynamic_tools": list(_DYNAMIC.keys())}


@app.get("/tools")
def list_tools() -> Dict[str, Any]:
    REQUESTS.labels(route="tools").inc()
    combined = {name: {"schema": meta["schema"]} for name, meta in TOOLS.items()}
    combined.update({name: {"schema": meta.get("schema", {})} for name, meta in _DYNAMIC.items()})
    return combined


@app.post("/call")
async def call(req: Request) -> JSONResponse:
    with LATENCY.labels(route="call").time():
        REQUESTS.labels(route="call").inc()
        body = await req.json()
        tool = str(body.get("tool", "")).strip()
        inp = body.get("input", "")
        if tool in TOOLS:
            try:
                out = TOOLS[tool]["run"](inp)
                return JSONResponse(status_code=200, content={"tool": tool, "output": out})
            except Exception as e:
                return JSONResponse(status_code=500, content={"error": str(e)})
        if tool in _DYNAMIC:
            meta = _DYNAMIC[tool]
            kind = meta.get("type")
            if kind == "gorilla":
                # Forward to Gorilla bridge; expects dict input
                base = meta.get("base", "http://127.0.0.1:8089")
                try:
                    payload = inp if isinstance(inp, dict) else {"prompt": str(inp)}
                    r = requests.post(f"{base}/gorilla/completions", json=payload, timeout=30)
                    return JSONResponse(status_code=r.status_code, content=r.json())
                except Exception as e:
                    return JSONResponse(status_code=502, content={"error": f"gorilla error: {e}"})
            if kind == "http":
                base = meta.get("base", "")
                path = meta.get("path", "/")
                method = str(meta.get("method", "POST")).upper()
                url = (base.rstrip("/") + path) if base else path
                try:
                    if method == "POST":
                        r = requests.post(url, json=inp if isinstance(inp, dict) else {"input": inp}, timeout=30)
                    else:
                        r = requests.get(url, timeout=30)
                    content = r.json() if r.headers.get("content-type", "").startswith("application/json") else {"text": r.text}
                    return JSONResponse(status_code=r.status_code, content=content)
                except Exception as e:
                    return JSONResponse(status_code=502, content={"error": f"http tool error: {e}"})
            return JSONResponse(status_code=400, content={"error": f"unsupported dynamic tool type: {kind}"})
        return JSONResponse(status_code=400, content={"error": f"unknown tool: {tool}"})


@app.post("/register_tool")
async def register_tool(req: Request) -> JSONResponse:
    REQUESTS.labels(route="register").inc()
    body = await req.json()
    name = str(body.get("name", "")).strip()
    if not name:
        return JSONResponse(status_code=400, content={"error": "missing name"})
    _DYNAMIC[name] = {
        "type": body.get("type"),
        "schema": body.get("schema", {}),
        "base": body.get("base", ""),
    }
    return JSONResponse(status_code=200, content={"registered": name})

# Prometheus metrics
metrics_app = make_asgi_app()
app.mount("/metrics", metrics_app)


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=PORT)