| | |
| | |
| | |
| | |
| | |
| | |
| |
|
| | 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"]) |
| |
|
| | |
| | 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": |
| | |
| | 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}) |
| |
|
| | |
| | metrics_app = make_asgi_app() |
| | app.mount("/metrics", metrics_app) |
| |
|
| |
|
| | if __name__ == "__main__": |
| | uvicorn.run(app, host="0.0.0.0", port=PORT) |
| |
|