Spaces:
Runtime error
Runtime error
File size: 1,845 Bytes
4ba130d 75c2b28 4ba130d 458173c a556d91 458173c a556d91 4ba130d 75c2b28 458173c a556d91 458173c a556d91 458173c a556d91 458173c a556d91 458173c 75c2b28 458173c a0bcdfd 458173c 75c2b28 a556d91 75c2b28 a556d91 4ba130d 458173c 88f9581 97004bb a0bcdfd 458173c a0bcdfd 458173c a0bcdfd 458173c a556d91 |
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 |
import os
import json
import httpx
from fastapi import FastAPI, Request, HTTPException
from mcp.server import Server
from mcp.server.sse import sse_server
from mcp.types import Tool, TextContent
# Create MCP Server
server = Server("sap-mcp-proxy")
# SAP function
async def fetch_supplier_invoices():
api_key = os.getenv("API_KEY")
if not api_key:
return {"error": "API_KEY not configured"}
url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SUPPLIERINVOICE_PROCESS_SRV/A_BR_SupplierInvoiceNFDocument?$top=50&$inlinecount=allpages"
headers = {"APIKey": api_key, "Accept": "application/json"}
async with httpx.AsyncClient() as client:
resp = await client.get(url, headers=headers)
return resp.json() if resp.status_code == 200 else {"error": resp.status_code}
# Register tools
@server.list_tools()
async def list_tools() -> list[Tool]:
return [Tool(name="get_supplier_invoices", description="Fetch supplier invoices from SAP", inputSchema={"type": "object", "properties": {}})]
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if name == "get_supplier_invoices":
result = await fetch_supplier_invoices()
return [TextContent(type="text", text=json.dumps(result))]
raise ValueError(f"Unknown tool: {name}")
# Create app using MCP's built-in SSE server helper
app = sse_server(server)
# Add auth middleware
API_GATEWAY_KEY = os.getenv("API_GATEWAY_KEY")
@app.middleware("http")
async def check_api_key(request: Request, call_next):
if request.url.path in ["/", "/health"]:
return await call_next(request)
token = request.headers.get("X-API-Key")
if not token or token != API_GATEWAY_KEY:
raise HTTPException(status_code=401, detail="Unauthorized")
return await call_next(request)
|