Compare commits

..

No commits in common. "7289a91b66cc7eaade06ef3bc684b69c1072076a" and "2ee93048e1dca2fb77424bbac5deb5377a8b6bbb" have entirely different histories.

4 changed files with 23 additions and 123 deletions

View File

@ -1,41 +1,13 @@
# ══════════════════════════════════════════════════════════════════════════════ # ── Frappe Connection ────────────────────────────────────────────────────────
# THREE SUPPORTED MODES # URL of your Frappe Docker instance (VPS IP or domain)
# ══════════════════════════════════════════════════════════════════════════════ FRAPPE_URL=http://YOUR_VPS_IP:8000
#
# MODE 1 — Local / stdio (single user, your machine)
# Run: frappe-mcp
# Config: Set FRAPPE_URL + credentials below.
# Claude Desktop spawns the process directly via stdio.
#
# MODE 2 — VPS / SSE, multi-tenant (public hosted server)
# Run: frappe-mcp --sse
# Config: Set only MCP_HOST, MCP_PORT, MCP_BEARER_TOKEN here.
# Each connecting user supplies their own Frappe credentials as
# request headers: X-Frappe-URL, X-Frappe-API-Key, X-Frappe-API-Secret
# No Frappe credentials are stored on the server.
#
# MODE 3 — VPS / SSE, single-tenant (you host it for yourself)
# Run: frappe-mcp --sse
# Config: Set BOTH the MCP server settings AND Frappe credentials here.
# Users connect without sending credential headers — the server's
# .env credentials are used for everyone.
#
# ── SSE Server Settings (modes 2 & 3) ────────────────────────────────────────
MCP_HOST=0.0.0.0
MCP_PORT=8001
# Shared access token — clients must send: Authorization: Bearer <token> # API credentials — generate in Frappe: Settings > My Profile > API Access
# Generate: python -c "import secrets; print(secrets.token_hex(32))" FRAPPE_API_KEY=your_api_key_here
MCP_BEARER_TOKEN=change_this_to_a_strong_random_token FRAPPE_API_SECRET=your_api_secret_here
# ── Frappe Connection (modes 1 & 3) ────────────────────────────────────────── # For multi-site Docker setups — the site name e.g. "site1.localhost"
# Required for local stdio mode (mode 1). FRAPPE_SITE_NAME=
# Optional for SSE mode — set these only if you want a single fixed Frappe
# instance for all connections (mode 3). Leave commented for multi-tenant (mode 2).
# FRAPPE_URL=http://YOUR_VPS_IP:8000
# FRAPPE_API_KEY=your_api_key_here
# FRAPPE_API_SECRET=your_api_secret_here
# FRAPPE_SITE_NAME=
# ── Safety ─────────────────────────────────────────────────────────────────── # ── Safety ───────────────────────────────────────────────────────────────────
# Set to true to block ALL write/delete operations (read-only audit mode) # Set to true to block ALL write/delete operations (read-only audit mode)

View File

@ -7,7 +7,6 @@ import json
import httpx import httpx
from typing import Any from typing import Any
from frappe_mcp.config import get_settings from frappe_mcp.config import get_settings
from frappe_mcp.session import get_session
class FrappeAPIError(Exception): class FrappeAPIError(Exception):
@ -19,37 +18,21 @@ class FrappeAPIError(Exception):
class FrappeClient: class FrappeClient:
def __init__(self): def __init__(self):
session = get_session() self.settings = get_settings()
if session: self.base_url = self.settings.frappe_url
# SSE mode: credentials supplied per-connection via request headers self._auth_header = self._build_auth_header()
self.base_url = session.frappe_url.rstrip("/")
self._api_key = session.api_key
self._api_secret = session.api_secret
self._site_name = session.site_name
self.request_timeout = session.request_timeout
else:
# Stdio/local mode: credentials from .env
s = get_settings()
self.base_url = s.frappe_url
self._api_key = s.frappe_api_key
self._api_secret = s.frappe_api_secret
self._site_name = s.frappe_site_name
self.request_timeout = s.request_timeout
if not self._api_key or not self._api_secret:
raise FrappeAPIError(
"Frappe credentials not configured. "
"In SSE mode pass X-Frappe-URL, X-Frappe-API-Key, X-Frappe-API-Secret headers. "
"In local mode set FRAPPE_API_KEY and FRAPPE_API_SECRET in .env"
)
def _build_auth_header(self) -> dict[str, str]: def _build_auth_header(self) -> dict[str, str]:
return {"Authorization": f"token {self._api_key}:{self._api_secret}"} key = self.settings.frappe_api_key
secret = self.settings.frappe_api_secret
if not key or not secret:
raise FrappeAPIError("FRAPPE_API_KEY and FRAPPE_API_SECRET must be set in .env")
return {"Authorization": f"token {key}:{secret}"}
def _headers(self, extra: dict | None = None) -> dict[str, str]: def _headers(self, extra: dict | None = None) -> dict[str, str]:
h = {**self._build_auth_header(), "Content-Type": "application/json", "Accept": "application/json"} h = {**self._auth_header, "Content-Type": "application/json", "Accept": "application/json"}
if self._site_name: if self.settings.frappe_site_name:
h["X-Frappe-Site-Name"] = self._site_name h["X-Frappe-Site-Name"] = self.settings.frappe_site_name
if extra: if extra:
h.update(extra) h.update(extra)
return h return h
@ -65,7 +48,7 @@ class FrappeClient:
) )
async def get(self, path: str, params: dict | None = None) -> Any: async def get(self, path: str, params: dict | None = None) -> Any:
async with httpx.AsyncClient(timeout=self.request_timeout) as client: async with httpx.AsyncClient(timeout=self.settings.request_timeout) as client:
resp = await client.get(self._url(path), headers=self._headers(), params=params) resp = await client.get(self._url(path), headers=self._headers(), params=params)
resp.raise_for_status() resp.raise_for_status()
data = resp.json() data = resp.json()
@ -104,7 +87,7 @@ class FrappeClient:
resp.raise_for_status() resp.raise_for_status()
async def post(self, path: str, payload: dict | None = None) -> Any: async def post(self, path: str, payload: dict | None = None) -> Any:
async with httpx.AsyncClient(timeout=self.request_timeout) as client: async with httpx.AsyncClient(timeout=self.settings.request_timeout) as client:
resp = await client.post(self._url(path), headers=self._headers(), json=payload or {}) resp = await client.post(self._url(path), headers=self._headers(), json=payload or {})
self._handle_error_response(resp) self._handle_error_response(resp)
data = resp.json() data = resp.json()
@ -112,7 +95,7 @@ class FrappeClient:
return data.get("data", data) return data.get("data", data)
async def put(self, path: str, payload: dict | None = None) -> Any: async def put(self, path: str, payload: dict | None = None) -> Any:
async with httpx.AsyncClient(timeout=self.request_timeout) as client: async with httpx.AsyncClient(timeout=self.settings.request_timeout) as client:
resp = await client.put(self._url(path), headers=self._headers(), json=payload or {}) resp = await client.put(self._url(path), headers=self._headers(), json=payload or {})
self._handle_error_response(resp) self._handle_error_response(resp)
data = resp.json() data = resp.json()
@ -120,7 +103,7 @@ class FrappeClient:
return data.get("data", data) return data.get("data", data)
async def delete(self, path: str) -> Any: async def delete(self, path: str) -> Any:
async with httpx.AsyncClient(timeout=self.request_timeout) as client: async with httpx.AsyncClient(timeout=self.settings.request_timeout) as client:
resp = await client.delete(self._url(path), headers=self._headers()) resp = await client.delete(self._url(path), headers=self._headers())
resp.raise_for_status() resp.raise_for_status()
data = resp.json() data = resp.json()

View File

@ -82,32 +82,6 @@ def _run_sse():
auth = request.headers.get("Authorization", "") auth = request.headers.get("Authorization", "")
if auth != f"Bearer {bearer_token}": if auth != f"Bearer {bearer_token}":
return Response("Unauthorized", status_code=401) return Response("Unauthorized", status_code=401)
# Per-user Frappe credentials via request headers (optional).
# If omitted, FrappeClient falls back to .env values — useful when the
# server owner is the only user, or for a single-tenant VPS deployment.
frappe_url = request.headers.get("X-Frappe-URL", "")
api_key = request.headers.get("X-Frappe-API-Key", "")
api_secret = request.headers.get("X-Frappe-API-Secret", "")
site_name = request.headers.get("X-Frappe-Site-Name", "")
if frappe_url or api_key or api_secret:
# At least one header present — require all three to be explicit
if not (frappe_url and api_key and api_secret):
return Response(
"Partial credentials: supply all three headers together — "
"X-Frappe-URL, X-Frappe-API-Key, X-Frappe-API-Secret",
status_code=400,
)
from frappe_mcp.session import SessionConfig, set_session
set_session(SessionConfig(
frappe_url=frappe_url,
api_key=api_key,
api_secret=api_secret,
site_name=site_name,
))
# else: no headers — FrappeClient will use .env credentials
async with sse.connect_sse( async with sse.connect_sse(
request.scope, request.receive, request._send request.scope, request.receive, request._send
) as streams: ) as streams:

View File

@ -1,29 +0,0 @@
"""
Per-connection session config using Python contextvars.
Each SSE connection sets its own Frappe credentials, isolated from other users.
Falls back to .env values if no per-session config is set (local stdio mode).
"""
from contextvars import ContextVar
from dataclasses import dataclass
@dataclass
class SessionConfig:
frappe_url: str
api_key: str
api_secret: str
site_name: str = ""
read_only_mode: bool = False
request_timeout: int = 30
_session: ContextVar[SessionConfig | None] = ContextVar("frappe_session", default=None)
def set_session(config: SessionConfig) -> None:
_session.set(config)
def get_session() -> SessionConfig | None:
return _session.get()