PD03 commited on
Commit
458173c
·
verified ·
1 Parent(s): 75c2b28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -55
app.py CHANGED
@@ -1,86 +1,48 @@
1
  import os
2
  import json
3
  import httpx
4
- from typing import Any
5
- from fastapi import FastAPI, Request, Response, HTTPException
6
- from fastapi.responses import StreamingResponse
7
  from mcp.server import Server
8
- from mcp.server.sse import SseServerTransport
9
  from mcp.types import Tool, TextContent
10
 
11
  # Create MCP Server
12
- mcp_server = Server("sap-mcp-proxy")
13
 
14
- # SAP API function
15
  async def fetch_supplier_invoices():
16
  api_key = os.getenv("API_KEY")
17
  if not api_key:
18
- return {"error": "SAP API_KEY not configured"}
19
-
20
  url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SUPPLIERINVOICE_PROCESS_SRV/A_BR_SupplierInvoiceNFDocument?$top=50&$inlinecount=allpages"
21
  headers = {"APIKey": api_key, "Accept": "application/json"}
22
-
23
  async with httpx.AsyncClient() as client:
24
  resp = await client.get(url, headers=headers)
25
- return resp.json() if resp.status_code == 200 else {"error": resp.status_code, "body": resp.text}
26
 
27
- # Register MCP tools
28
- @mcp_server.list_tools()
29
  async def list_tools() -> list[Tool]:
30
- return [
31
- Tool(
32
- name="get_supplier_invoices",
33
- description="Fetch 50 supplier invoices from SAP S/4HANA OData API",
34
- inputSchema={"type": "object", "properties": {}, "required": []}
35
- )
36
- ]
37
 
38
- @mcp_server.call_tool()
39
  async def call_tool(name: str, arguments: dict) -> list[TextContent]:
40
  if name == "get_supplier_invoices":
41
  result = await fetch_supplier_invoices()
42
  return [TextContent(type="text", text=json.dumps(result))]
43
  raise ValueError(f"Unknown tool: {name}")
44
 
45
- # Create FastAPI app
46
- app = FastAPI(title="SAP MCP Proxy")
 
 
47
  API_GATEWAY_KEY = os.getenv("API_GATEWAY_KEY")
48
 
49
- # Auth middleware
50
  @app.middleware("http")
51
  async def check_api_key(request: Request, call_next):
52
- if request.url.path in ["/", "/docs", "/redoc", "/openapi.json"]:
53
  return await call_next(request)
54
- token = request.headers.get("X-API-Key") or request.headers.get("Authorization", "").replace("Bearer ", "")
55
  if not token or token != API_GATEWAY_KEY:
56
- raise HTTPException(status_code=401, detail="Invalid or missing API key")
57
  return await call_next(request)
58
-
59
- # MCP SSE endpoint
60
- @app.get("/sse")
61
- @app.post("/sse")
62
- async def handle_sse(request: Request):
63
- async def event_generator():
64
- transport = SseServerTransport("/messages")
65
- async with mcp_server.run(transport.read, transport.write):
66
- async for message in transport.connect():
67
- yield message
68
-
69
- return StreamingResponse(event_generator(), media_type="text/event-stream")
70
-
71
- # MCP message endpoint
72
- @app.post("/messages")
73
- async def handle_message(request: Request):
74
- body = await request.json()
75
- # Process MCP JSON-RPC message
76
- response = await mcp_server.handle_message(body)
77
- return response
78
-
79
- # Health check
80
- @app.get("/")
81
- def root():
82
- return {
83
- "message": "SAP MCP Proxy is running",
84
- "mcp_sse_endpoint": "/sse",
85
- "mcp_messages_endpoint": "/messages"
86
- }
 
1
  import os
2
  import json
3
  import httpx
4
+ from fastapi import FastAPI, Request, HTTPException
 
 
5
  from mcp.server import Server
6
+ from mcp.server.sse import sse_server
7
  from mcp.types import Tool, TextContent
8
 
9
  # Create MCP Server
10
+ server = Server("sap-mcp-proxy")
11
 
12
+ # SAP function
13
  async def fetch_supplier_invoices():
14
  api_key = os.getenv("API_KEY")
15
  if not api_key:
16
+ return {"error": "API_KEY not configured"}
 
17
  url = "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata/sap/API_SUPPLIERINVOICE_PROCESS_SRV/A_BR_SupplierInvoiceNFDocument?$top=50&$inlinecount=allpages"
18
  headers = {"APIKey": api_key, "Accept": "application/json"}
 
19
  async with httpx.AsyncClient() as client:
20
  resp = await client.get(url, headers=headers)
21
+ return resp.json() if resp.status_code == 200 else {"error": resp.status_code}
22
 
23
+ # Register tools
24
+ @server.list_tools()
25
  async def list_tools() -> list[Tool]:
26
+ return [Tool(name="get_supplier_invoices", description="Fetch supplier invoices from SAP", inputSchema={"type": "object", "properties": {}})]
 
 
 
 
 
 
27
 
28
+ @server.call_tool()
29
  async def call_tool(name: str, arguments: dict) -> list[TextContent]:
30
  if name == "get_supplier_invoices":
31
  result = await fetch_supplier_invoices()
32
  return [TextContent(type="text", text=json.dumps(result))]
33
  raise ValueError(f"Unknown tool: {name}")
34
 
35
+ # Create app using MCP's built-in SSE server helper
36
+ app = sse_server(server)
37
+
38
+ # Add auth middleware
39
  API_GATEWAY_KEY = os.getenv("API_GATEWAY_KEY")
40
 
 
41
  @app.middleware("http")
42
  async def check_api_key(request: Request, call_next):
43
+ if request.url.path in ["/", "/health"]:
44
  return await call_next(request)
45
+ token = request.headers.get("X-API-Key")
46
  if not token or token != API_GATEWAY_KEY:
47
+ raise HTTPException(status_code=401, detail="Unauthorized")
48
  return await call_next(request)