83 lines
3.2 KiB
Python
83 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Loopback-only MCP bridge to the OAuth-protected ServiceNow MCP server."""
|
|
import argparse
|
|
import contextlib
|
|
import logging
|
|
import sys
|
|
|
|
import httpx
|
|
import uvicorn
|
|
from mcp import ClientSession
|
|
from mcp.server.lowlevel import Server
|
|
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
|
|
from mcp.server.transport_security import TransportSecuritySettings
|
|
from starlette.applications import Starlette
|
|
from starlette.routing import Mount
|
|
|
|
from story_client import EXPECTED, MCP_URL, OAuth
|
|
|
|
logger = logging.getLogger('servicenow-proxy')
|
|
server = Server('servicenow-story-proxy', version='1.0.0', instructions='Proxy to ServiceNow Scrum Story tools. Creating a story requires short_description, type, and a product sys_id on this instance.')
|
|
auth = None
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def upstream():
|
|
from mcp.client.streamable_http import streamable_http_client
|
|
if auth is None: raise RuntimeError('Proxy wurde nicht initialisiert.')
|
|
async with httpx.AsyncClient(auth=auth, timeout=httpx.Timeout(30, read=300), follow_redirects=False) as http:
|
|
async with streamable_http_client(MCP_URL, http_client=http) as (read, write, _):
|
|
async with ClientSession(read, write) as session:
|
|
await session.initialize()
|
|
yield session
|
|
|
|
|
|
@server.list_tools()
|
|
async def list_tools():
|
|
tools, cursor = [], None
|
|
async with upstream() as session:
|
|
while True:
|
|
page = await session.list_tools(cursor=cursor)
|
|
tools.extend(tool for tool in page.tools if tool.name in EXPECTED)
|
|
cursor = page.nextCursor
|
|
if not cursor: break
|
|
return tools
|
|
|
|
|
|
@server.call_tool(validate_input=False)
|
|
async def call_tool(name, arguments):
|
|
if name not in EXPECTED: raise ValueError('Unbekanntes oder nicht erlaubtes Tool.')
|
|
async with upstream() as session:
|
|
return await session.call_tool(name, arguments)
|
|
|
|
|
|
def make_app(port):
|
|
global auth
|
|
auth = OAuth()
|
|
manager = StreamableHTTPSessionManager(
|
|
app=server, json_response=True, stateless=True,
|
|
security_settings=TransportSecuritySettings(enable_dns_rebinding_protection=True,
|
|
allowed_hosts=[f'127.0.0.1:{port}', f'localhost:{port}'],
|
|
allowed_origins=[f'http://127.0.0.1:{port}', f'http://localhost:{port}']))
|
|
@contextlib.asynccontextmanager
|
|
async def lifespan(app):
|
|
try:
|
|
async with manager.run(): yield
|
|
finally:
|
|
await auth.close()
|
|
async def handle(scope, receive, send):
|
|
# A fixed local route; mounted ASGI app receives /mcp in the original path.
|
|
await manager.handle_request(scope, receive, send)
|
|
return Starlette(routes=[Mount('/mcp', app=handle)], lifespan=lifespan)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description='Lokaler ServiceNow-MCP-Proxy (nur 127.0.0.1).')
|
|
parser.add_argument('--port', type=int, default=8766)
|
|
args = parser.parse_args()
|
|
if not 1 <= args.port <= 65535: parser.error('Port muss zwischen 1 und 65535 liegen.')
|
|
print(f'ServiceNow MCP Proxy: http://127.0.0.1:{args.port}/mcp', file=sys.stderr)
|
|
uvicorn.run(make_app(args.port), host='127.0.0.1', port=args.port, log_level='warning', access_log=False)
|
|
|
|
if __name__ == '__main__': main()
|