Add ServiceNow MCP client and local proxy

This commit is contained in:
2026-10-30 11:44:24 +01:00
commit 5eba2ecb36
12 changed files with 1991 additions and 0 deletions
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""Opt-in live integration test. Creates a real story and leaves it in ServiceNow."""
import ast
import argparse
import asyncio
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import httpx
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from story_client import OAuth, MCP_URL, EXPECTED
def payload(result):
if result.structuredContent is not None: return result.structuredContent
for block in result.content:
text = getattr(block, 'text', None)
if text:
for parser in (json.loads, ast.literal_eval):
try: return parser(text)
except (ValueError, SyntaxError): pass
return text
return None
def unwrap(data):
while isinstance(data, dict) and set(data) == {'result'}:
data = data['result']
return data
def error_text(result):
return str(payload(result))
async def main(product):
failures = []
def check(label, ok, detail=''):
print(('OK' if ok else 'FEHLER') + ': ' + label + (f' – {detail}' if detail else ''), flush=True)
if not ok: failures.append(label)
auth = OAuth()
story_id = None
try:
await auth.ensure()
if auth.tokens.get('refresh_token'):
old = auth.tokens['access_token']
await auth.ensure(force=True, rejected_token=old)
check('Token-Refresh', bool(auth.tokens.get('access_token')))
else:
check('Token-Refresh', False, 'Kein Refresh-Token vorhanden')
async with httpx.AsyncClient(auth=auth, timeout=httpx.Timeout(30, read=300)) 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()
tools, cursor = [], None
while True:
page = await session.list_tools(cursor=cursor)
tools.extend(t.name for t in page.tools)
cursor = page.nextCursor
if not cursor: break
check('tools/list: genau vier Tools, kein Delete', len(tools) == 4 and set(tools) == EXPECTED)
listed = await session.call_tool('rm_story_list', {'limit': '5'})
listing = unwrap(payload(listed))
rows = listing.get('result', []) if isinstance(listing, dict) else []
check('Stories lesen (limit=5)', not listed.isError and isinstance(rows, list) and len(rows) <= 5, f'{len(rows)} Treffer')
filtered = await session.call_tool('rm_story_list', {'query': 'active=true^priority=1', 'limit': '5'})
check('Stories filtern', not filtered.isError)
if rows and rows[0].get('sys_id'):
got = await session.call_tool('rm_story_get', {'sys_id': rows[0]['sys_id']})
check('Einzelne vorhandene Story lesen', not got.isError)
else: check('Einzelne vorhandene Story lesen', False, 'Keine sichtbare Story vorhanden')
missing = await session.call_tool('rm_story_create', {'request_body': {'short_description': 'MCP Negativtest', 'product': product}})
check('Create ohne type abgelehnt', bool(missing.isError) and ('400' in error_text(missing) or 'required' in error_text(missing).lower()))
absent = await session.call_tool('rm_story_get', {'sys_id': '00000000000000000000000000000000'})
check('Unbekannte Story abgelehnt (404)', bool(absent.isError) and '404' in error_text(absent), error_text(absent)[:200] if not absent.isError else '')
title = 'MCP Integrationstest ' + datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')
created = await session.call_tool('rm_story_create', {'request_body': {'short_description': title, 'type': 'Development', 'product': product}})
body = unwrap(payload(created))
story_id = body.get('sys_id') if isinstance(body, dict) else None
check('Test-Story erstellen', not created.isError and bool(story_id), error_text(created)[:500] if created.isError else '')
if story_id:
print('Test-Story sys_id:', story_id, flush=True)
got = await session.call_tool('rm_story_get', {'sys_id': story_id})
read_story = unwrap(payload(got))
check('Test-Story lesen', not got.isError and isinstance(read_story, dict) and read_story.get('sys_id') == story_id)
updated = await session.call_tool('rm_story_update', {'sys_id': story_id, 'request_body': {'story_points': '3'}})
update_body = unwrap(payload(updated))
fields = update_body.get('updated_fields', []) if isinstance(update_body, dict) else []
check('Test-Story ändern', not updated.isError and 'story_points' in fields, error_text(updated)[:500] if updated.isError or 'story_points' not in fields else '')
if not updated.isError:
reread = await session.call_tool('rm_story_get', {'sys_id': story_id})
after = unwrap(payload(reread))
check('Änderung erneut lesen', not reread.isError and isinstance(after, dict) and str(after.get('story_points')) in ('3', '3.0'))
else:
print('ÜBERSPRUNGEN: Lesen und Ändern der Test-Story (Create fehlgeschlagen).', flush=True)
finally:
await auth.close()
print('\n' + ('Alle Tests bestanden.' if not failures else f'{len(failures)} Test(s) fehlgeschlagen: ' + ', '.join(failures)))
if story_id: print('Die Test-Story bleibt bestehen; der Server bietet kein Delete-Tool.')
return 1 if failures else 0
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Echter Integrationstest: legt eine Test-Story an.')
parser.add_argument('--product', required=True, help='sys_id eines gültigen Produkts')
args = parser.parse_args()
try: sys.exit(asyncio.run(main(args.product)))
except Exception as exc:
print(f'Integrationstest abgebrochen: {exc}', file=sys.stderr)
sys.exit(1)