263 lines
9.5 KiB
Python
263 lines
9.5 KiB
Python
"""MCP Ghostfolio Server — steuert das Portfolio komplett (read + write).
|
|
|
|
Wrappt die Ghostfolio-REST-API (Container auf 127.0.0.1:3333) ueber ein
|
|
JWT-Token aus /opt/ghostfolio/migration/.auth-token. Dieser MCP-Server
|
|
exponieret die Tools Docker-intern ans openclaw-net.
|
|
|
|
Tools: Portfolio-Uebersicht (Konten, Bestaende, Performance, Dividenden),
|
|
Konten (list/create/update/delete), Activities/Transaktionen (import,
|
|
list, delete), Balance-Setze.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import urllib.request
|
|
import urllib.error
|
|
import contextlib
|
|
from typing import Annotated
|
|
|
|
from pydantic import Field
|
|
from mcp.server.fastmcp import FastMCP
|
|
from starlette.applications import Starlette
|
|
from starlette.routing import Mount
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
from common import get_current_user, OAUTH_ROUTES, BearerAuthMiddleware
|
|
|
|
API_BASE = os.environ.get("GF_API_BASE", "http://127.0.0.1:3333")
|
|
AUTH_TOKEN_FILE = "/opt/ghostfolio/migration/.auth-token"
|
|
|
|
mcp = FastMCP("Ghostfolio", stateless_http=True,
|
|
transport_security={"enable_dns_rebinding_protection": False})
|
|
|
|
|
|
def _token():
|
|
with open(AUTH_TOKEN_FILE) as f:
|
|
return f.read().strip()
|
|
|
|
|
|
def _api(method: str, path: str, body=None):
|
|
url = API_BASE + path
|
|
headers = {
|
|
"Authorization": "Bearer " + _token(),
|
|
"Content-Type": "application/json",
|
|
}
|
|
data = json.dumps(body).encode() if body is not None else None
|
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
raw = resp.read()
|
|
if not raw:
|
|
return {}
|
|
return json.loads(raw.decode())
|
|
except urllib.error.HTTPError as e:
|
|
return {"error": f"HTTP {e.code} bei {method} {path}: {e.read().decode()[:400]}"}
|
|
except Exception as e:
|
|
return {"error": f"Ghostfolio nicht erreichbar: {e}"}
|
|
|
|
|
|
REPORT_SCRIPT = "/opt/ghostfolio/report/update-report.sh"
|
|
|
|
|
|
def _trigger_report():
|
|
"""Stoesst den Status-Report fuer das accessible dashboard neu an.
|
|
|
|
Laueft asynchron (subprocess), damit das Tool sofort antwortet. Laueft als
|
|
root ueber sudo, da der Zielordner /opt/accessible-dashboard/public/portfolio
|
|
gitea-runner gehoert und stefan dorthin nicht direkt schreiben kann.
|
|
"""
|
|
try:
|
|
subprocess.Popen(
|
|
["/usr/bin/sudo", "/opt/ghostfolio/report/update-report.sh"],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
start_new_session=True,
|
|
)
|
|
except Exception as e:
|
|
print(f"Report-Trigger fehlgeschlagen: {e}", file=sys.stderr)
|
|
|
|
|
|
# --- Portfolio Uebersicht (read) ---
|
|
|
|
@mcp.tool()
|
|
def portfolio_details() -> str:
|
|
"""Get the full portfolio overview: accounts, holdings, summary. Call this first."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
r = _api("GET", "/api/v1/portfolio/details")
|
|
if "error" in r:
|
|
return r["error"]
|
|
summary = r.get("summary", {})
|
|
lines = [
|
|
f"Gesamtvermoegen: {summary.get('totalValue', '?')} {summary.get('currency', '')}",
|
|
f"Konten: {summary.get('totalAccounts', '?')} | Holdings: {summary.get('totalHoldings', '?')}",
|
|
f"Cash: {summary.get('cash', '?')} | Angelegt: {summary.get('totalInvestment', '?')}",
|
|
f"Performance: {summary.get('totalPerformance', '?')} ({summary.get('totalPerformancePercentage', '?')}%)",
|
|
]
|
|
lines.append("")
|
|
lines.append("Konten:")
|
|
for acc_id, a in r.get("accounts", {}).items():
|
|
lines.append(f" {a.get('name')} (id: {acc_id}) | Wert: {a.get('valueInBaseCurrency', '?')} {a.get('currency', '')}")
|
|
lines.append("")
|
|
lines.append("Bestaende (Top nach Wert):")
|
|
for sym, h in sorted(r.get("holdings", {}).items(), key=lambda x: -x[1].get("valueInBaseCurrency", 0)):
|
|
lines.append(f" {sym}: {h.get('name', '')} | Wert: {h.get('valueInBaseCurrency', '?')} | Anzahl: {h.get('quantity', '?')} | Perf: {h.get('grossPerformancePercent', '?')}%")
|
|
return "\n".join(lines)
|
|
|
|
|
|
@mcp.tool()
|
|
def get_performance(
|
|
range: Annotated[str, Field(description="Zeitraum: 1d, 1w, 1m, 3m, ytd, 1y, 5y, max")] = "max",
|
|
) -> str:
|
|
"""Get portfolio performance for a time range (net/gross performance, totals)."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
r = _api("GET", f"/api/v2/portfolio/performance?range={range}")
|
|
if "error" in r:
|
|
return r["error"]
|
|
p = r.get("performance", {})
|
|
return (f"Zeitraum {range}:\n"
|
|
f"Netto-Performance: {p.get('netPerformance', '?')} ({p.get('netPerformancePercentage', '?')}%)\n"
|
|
f"Brutto-Performance: {p.get('grossPerformance', '?')} ({p.get('grossPerformancePercentage', '?')}%)\n"
|
|
f"Investiert: {p.get('totalInvestment', '?')} | Wertzuwachs: {p.get('totalValue', '?')}")
|
|
|
|
|
|
@mcp.tool()
|
|
def get_dividends(
|
|
range: Annotated[str, Field(description="Zeitraum: ytd, 1y, 5y, max")] = "ytd",
|
|
) -> str:
|
|
"""Get dividend income for a time range."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
r = _api("GET", f"/api/v1/portfolio/dividends?range={range}")
|
|
if "error" in r:
|
|
return r["error"]
|
|
total = sum(d.get("investment", 0) for d in r.get("dividends", []))
|
|
lines = [f"Dividenden ({range}): Gesamt {total}"]
|
|
for d in r.get("dividends", []):
|
|
lines.append(f" {d.get('date', '')}: {d.get('symbol', '')} | {d.get('investment', 0)}")
|
|
return "\n".join(lines)
|
|
|
|
|
|
@mcp.tool()
|
|
def list_accounts() -> str:
|
|
"""List all accounts with their balances."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
r = _api("GET", "/api/v1/account")
|
|
if "error" in r:
|
|
return r["error"]
|
|
data = r.get("accounts", r) if isinstance(r, dict) else r
|
|
if isinstance(data, dict):
|
|
lines = [f" {a.get('name')} (id: {a.get('id')}) | {a.get('currency', '')} | {a.get('comment', '')}"
|
|
for a in data.values()]
|
|
else:
|
|
lines = [f" {a.get('name')} (id: {a.get('id')}) | {a.get('currency', '')} | {a.get('comment', '')}"
|
|
for a in data]
|
|
return "\n".join(lines) if lines else "Keine Konten"
|
|
|
|
|
|
@mcp.tool()
|
|
def create_account(
|
|
name: Annotated[str, Field(description="Kontoname, z.B. 'Girokonto'")],
|
|
currency: Annotated[str, Field(description="Waehrung, z.B. 'EUR'")] = "EUR",
|
|
comment: Annotated[str, Field(description="Kommentar/Beschreibung")] = "",
|
|
) -> str:
|
|
"""Create a new account/depot. Returns the account ID."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
body = {"name": name, "currency": currency, "balance": 0, "platformId": None}
|
|
if comment:
|
|
body["comment"] = comment
|
|
r = _api("POST", "/api/v1/account", body)
|
|
if "error" in r:
|
|
return r["error"]
|
|
_trigger_report()
|
|
return f"Konto angelegt: {r.get('id')}"
|
|
|
|
|
|
@mcp.tool()
|
|
def import_activities(
|
|
payload: Annotated[str, Field(description="JSON-Payload mit accounts, activities, optional assetProfiles (Ghostfolio-Importformat)")],
|
|
) -> str:
|
|
"""Import activities (BUY/SELL/DIVIDEND etc.) in Ghostfolio-Importformat. Advanced use; see Ghostfolio docs for the schema."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
try:
|
|
body = json.loads(payload)
|
|
except json.JSONDecodeError as e:
|
|
return f"Ungueltiges JSON: {e}"
|
|
r = _api("POST", "/api/v1/import", body)
|
|
if "error" in r:
|
|
return r["error"]
|
|
_trigger_report()
|
|
return f"Import abgeschlossen: {len(r.get('activities', []))} Activities"
|
|
|
|
|
|
# --- Activities ---
|
|
|
|
@mcp.tool()
|
|
def list_activities(
|
|
account_id: Annotated[str, Field(description="Konto-ID. Leer fuer alle.")] = "",
|
|
limit: Annotated[int, Field(description="Maximale Anzahl")] = 50,
|
|
) -> str:
|
|
"""List recent activities (transactions) across the portfolio or a single account."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
q = f"?take={limit}"
|
|
if account_id:
|
|
q += f"&accounts={account_id}"
|
|
r = _api("GET", f"/api/v1/activities{q}")
|
|
if "error" in r:
|
|
return r["error"]
|
|
items = r.get("activities", [])
|
|
lines = [f"{len(items)} Activities"]
|
|
for a in items[:limit]:
|
|
lines.append(f" {a.get('date', '')[:10]} | {a.get('type', '')} | {a.get('symbol', '')} | qty {a.get('quantity', '')} | Preis {a.get('unitPrice', '')} | {a.get('comment', '')} | id: {a.get('id')}")
|
|
return "\n".join(lines)
|
|
|
|
|
|
@mcp.tool()
|
|
def delete_activity(
|
|
id: Annotated[str, Field(description="Activity-ID aus list_activities")],
|
|
) -> str:
|
|
"""Delete a single activity/transaction."""
|
|
user = get_current_user()
|
|
if not user:
|
|
return "Error: not authenticated"
|
|
r = _api("DELETE", f"/api/v1/activities/{id}")
|
|
if "error" in r:
|
|
return r["error"]
|
|
_trigger_report()
|
|
return f"Activity {id} geloescht"
|
|
|
|
|
|
def create_app():
|
|
from contextlib import asynccontextmanager
|
|
mcp_app = mcp.streamable_http_app()
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app):
|
|
async with contextlib.AsyncExitStack() as stack:
|
|
await stack.enter_async_context(mcp_app.router.lifespan_context(mcp_app))
|
|
yield
|
|
|
|
routes = list(OAUTH_ROUTES) + [Mount("/", app=mcp_app)]
|
|
app = Starlette(routes=routes, lifespan=lifespan)
|
|
app.add_middleware(BearerAuthMiddleware)
|
|
return app
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(create_app(), host="0.0.0.0", port=5120)
|