MCP v1: Thor's tools for Claude Code, behind Authelia OAuth (thor#1)
CI / Lint (flake8, house style) (pull_request) Successful in 57s
CI / Test (pytest) (pull_request) Successful in 1m15s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m3s
CI / Integration (MariaDB) (pull_request) Successful in 1m53s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Failing after 1m36s
CI / UI (screenshots) (pull_request) Failing after 2m6s
CI / Deploy (pull_request) Skipped
CI / Lint (flake8, house style) (pull_request) Successful in 57s
CI / Test (pytest) (pull_request) Successful in 1m15s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m3s
CI / Integration (MariaDB) (pull_request) Successful in 1m53s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Failing after 1m36s
CI / UI (screenshots) (pull_request) Failing after 2m6s
CI / Deploy (pull_request) Skipped
- thor/web/mcp.py: stateless Streamable HTTP at POST /mcp (JSON-RPC 2.0), RFC 9728 metadata at /.well-known/oauth-protected-resource[/mcp], 401 with resource_metadata. Tokens checked against Authelia's JWKS: RS256, iss, aud (this server), exp, typ at+jwt, client_id thor-mcp, scp array; group admin only; Remote-* headers never trusted; every tool call logged with the user. - Read tools (thor:read): list_incidents, get_incident, what_covers, thor_status, list_known_conditions. Write tools (thor:write): add_known_condition, end_known_condition, attach_ticket, detach_ticket. Tools a token's scopes can't use aren't listed. - Migration 4: incident_links (who attached which ticket to which incident). attach_ticket records an 'attach' action; in shadow nothing is sent, live sends a 'Root cause' comment. - Incident page lists attached tickets. PyJWT[crypto] added. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f7623840c
commit
45afd6e247
10 files changed
+593
-3
No files matched your search
@@ -2,3 +2,4 @@ flask>=3.0
|
||||
gunicorn>=22
|
||||
pymysql>=1.1
|
||||
requests>=2.32
|
||||
pyjwt[crypto]>=2.9
|
||||
@@ -21,6 +21,7 @@ class FakeStore:
|
||||
self.incidents: Dict[str, dict] = {}
|
||||
self.actions: List[dict] = []
|
||||
self.observations: Dict[str, dict] = {}
|
||||
self.links: List[dict] = []
|
||||
self.known: List[dict] = [
|
||||
{'id': 1, 'kind': 'reboot', 'subject': 'compute-storage-02', 'ticket_id': '693930698',
|
||||
'reason': 'compute-storage-02 reboots every 2 to 3 days from a failing DIMM.'},
|
||||
@@ -135,6 +136,36 @@ class FakeStore:
|
||||
return [dict(o, first_seen=o['start'], last_seen=o['end'], k=o['key'])
|
||||
for o in self.observations.values() if o['end'] >= since]
|
||||
|
||||
def add_known_condition(self, kind, subject, ticket_id, reason, created_by, now):
|
||||
self._check('add_known_condition')
|
||||
new = {'id': max([k['id'] for k in self.known] + [0]) + 1, 'kind': kind, 'subject': subject,
|
||||
'ticket_id': ticket_id, 'reason': reason, 'created_by': created_by, 'created_at': now}
|
||||
self.known.append(new)
|
||||
return new['id']
|
||||
|
||||
def end_known_condition(self, condition_id, ended_by, now):
|
||||
self._check('end_known_condition')
|
||||
for k in self.known:
|
||||
if k['id'] == condition_id and not k.get('ended'):
|
||||
k['ended'] = now
|
||||
return 1
|
||||
return 0
|
||||
|
||||
def add_incident_link(self, key, ticket_id, who, now):
|
||||
self._check('add_incident_link')
|
||||
self.links.append({'incident_key': key, 'ticket_id': ticket_id, 'added_by': who, 'added_at': now})
|
||||
return len(self.links)
|
||||
|
||||
def remove_incident_link(self, key, ticket_id, who, now):
|
||||
self._check('remove_incident_link')
|
||||
before = len(self.links)
|
||||
self.links = [x for x in self.links if not (x['incident_key'] == key and x['ticket_id'] == ticket_id)]
|
||||
return before - len(self.links)
|
||||
|
||||
def incident_links(self, key):
|
||||
self._check('incident_links')
|
||||
return [dict(x) for x in self.links if x['incident_key'] == key]
|
||||
|
||||
def known_conditions(self):
|
||||
self._check('known_conditions')
|
||||
return [dict(k) for k in self.known if not k.get('ended')]
|
||||
|
||||
@@ -16,7 +16,7 @@ def db():
|
||||
name=os.environ.get('THOR_TEST_DB_NAME', 'thor'), user=os.environ.get('THOR_TEST_DB_USER', 'thor'),
|
||||
password=os.environ.get('THOR_TEST_DB_PASSWORD', '')))
|
||||
for t in ('state', 'cycles', 'source_status', 'blind_periods', 'incidents', 'actions', 'observations',
|
||||
'known_conditions', 'schema_version'):
|
||||
'known_conditions', 'incident_links', 'schema_version'):
|
||||
d.execute(f'DROP TABLE IF EXISTS {t}') # nosec B608 - fixed table names
|
||||
return d
|
||||
|
||||
@@ -117,3 +117,20 @@ def test_known_conditions_seeded_and_managed(db):
|
||||
'first_seen': 1.0, 'last_seen': 1.0}, 2.0)
|
||||
s.delete_incident('k')
|
||||
assert s.load_incidents(0) == []
|
||||
|
||||
|
||||
def test_incident_links(db):
|
||||
db.migrate()
|
||||
s = Store(db)
|
||||
s.add_incident_link('k', '615797777', 'jared', 10.0)
|
||||
s.add_incident_link('k', '1', 'jared', 11.0)
|
||||
assert [x['ticket_id'] for x in s.incident_links('k')] == ['615797777', '1']
|
||||
assert s.remove_incident_link('k', '1', 'jared', 12.0) == 1
|
||||
assert s.remove_incident_link('k', '1', 'jared', 12.0) == 0
|
||||
assert [x['ticket_id'] for x in s.incident_links('k')] == ['615797777']
|
||||
s.save_incident({'key': 'k', 'state': 'open', 'priority': 2, 'kind': 'oom', 'subject': 'h', 'mode': 'shadow',
|
||||
'first_seen': 1.0, 'last_seen': 2.0, 'summary': 'x'}, 3.0)
|
||||
assert s.get_incident('k')['summary'] == 'x' and s.get_incident('none') is None
|
||||
s.add_action({'incident_key': 'k', 'kind': 'open', 'created': 3.0, 'mode': 'shadow', 'payload': {'a': 1}})
|
||||
acts = s.actions_for('k')
|
||||
assert len(acts) == 1 and acts[0]['payload'] == {'a': 1} and acts[0]['created_at'] == pytest.approx(3.0)
|
||||
@@ -0,0 +1,167 @@
|
||||
import time
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from thor.config import Settings
|
||||
from thor.web.app import create_app
|
||||
from thor.web.mcp import CLIENT_ID, ISSUER, READ, WRITE
|
||||
|
||||
from .fakes import Clock, FakeStore
|
||||
|
||||
T = 1_795_412_400.0
|
||||
KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
OTHER = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
|
||||
|
||||
class StaticJWKS:
|
||||
"""Stands in for PyJWKClient: always returns our test public key."""
|
||||
|
||||
class _K:
|
||||
key = KEY.public_key()
|
||||
|
||||
def get_signing_key_from_jwt(self, token):
|
||||
return self._K()
|
||||
|
||||
|
||||
def token(*, scopes=(READ, WRITE), groups=('admin',), aud='https://thor.example/mcp', client=CLIENT_ID,
|
||||
typ='at+jwt', signer=KEY, exp_in=600, user='jared'):
|
||||
now = int(time.time())
|
||||
claims = {'iss': ISSUER, 'sub': 'uuid-1', 'aud': aud, 'exp': now + exp_in, 'iat': now, 'client_id': client,
|
||||
'scp': list(scopes), 'groups': list(groups), 'preferred_username': user}
|
||||
return jwt.encode(claims, signer, algorithm='RS256', headers={'typ': typ})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app():
|
||||
store = FakeStore()
|
||||
store.incidents['host:compute-storage-01:oom'] = {
|
||||
'key': 'host:compute-storage-01:oom', 'kind': 'oom', 'subject': 'compute-storage-01', 'state': 'open',
|
||||
'priority': 1, 'mode': 'shadow', 'ticket': True, 'summary': 'Out of memory', 'first_seen': T - 600,
|
||||
'last_seen': T - 60, 'symptoms': {}, 'events': [], 'facts': {}}
|
||||
store.incidents['maintenance:gandalf:2'] = dict(store.incidents['host:compute-storage-01:oom'],
|
||||
key='maintenance:gandalf:2', ticket=False)
|
||||
s = Settings()
|
||||
s.public_url = 'https://thor.example'
|
||||
a = create_app(s, store, 'abc123', clock=Clock(T))
|
||||
a.config['THOR_JWKS'] = StaticJWKS()
|
||||
return a
|
||||
|
||||
|
||||
def rpc(app, method, params=None, tok=None, rid=1):
|
||||
body = {'jsonrpc': '2.0', 'method': method, 'params': params or {}}
|
||||
if rid is not None:
|
||||
body['id'] = rid
|
||||
return app.test_client().post('/mcp', json=body, headers={'Authorization': f'Bearer {tok or token()}'})
|
||||
|
||||
|
||||
def call(app, name, args=None, tok=None):
|
||||
r = rpc(app, 'tools/call', {'name': name, 'arguments': args or {}}, tok)
|
||||
res = r.get_json()['result']
|
||||
return res['isError'], res['content'][0]['text']
|
||||
|
||||
|
||||
def test_protected_resource_metadata(app):
|
||||
for path in ('/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource'):
|
||||
d = app.test_client().get(path).get_json()
|
||||
assert d['resource'] == 'https://thor.example/mcp'
|
||||
assert d['authorization_servers'] == [ISSUER] and d['scopes_supported'] == [READ, WRITE]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [
|
||||
token(aud='https://wiki.lotusguild.org/mcp'), token(client='tinker-tickets-mcp'), token(typ='JWT'),
|
||||
token(signer=OTHER), token(exp_in=-60), token(scopes=('wiki:read',)), 'not-a-jwt',
|
||||
])
|
||||
def test_bad_tokens_get_401_with_resource_metadata(app, bad):
|
||||
r = rpc(app, 'ping', tok=bad)
|
||||
assert r.status_code == 401
|
||||
assert 'resource_metadata="https://thor.example/.well-known/oauth-protected-resource/mcp"' in \
|
||||
r.headers['WWW-Authenticate']
|
||||
|
||||
|
||||
def test_no_token_and_wrong_group(app):
|
||||
r = app.test_client().post('/mcp', json={'jsonrpc': '2.0', 'id': 1, 'method': 'ping'},
|
||||
headers={'Remote-User': 'jared'}) # headers are never trusted
|
||||
assert r.status_code == 401
|
||||
assert rpc(app, 'ping', tok=token(groups=('employee',))).status_code == 403
|
||||
|
||||
|
||||
def test_initialize_ping_and_notifications(app):
|
||||
r = rpc(app, 'initialize', {'protocolVersion': '2025-03-26'}).get_json()['result']
|
||||
assert r['protocolVersion'] == '2025-03-26' and r['serverInfo']['name'] == 'thor'
|
||||
assert rpc(app, 'initialize', {'protocolVersion': '1999'}).get_json()['result']['protocolVersion'] == '2025-06-18'
|
||||
assert rpc(app, 'ping').get_json()['result'] == {}
|
||||
assert rpc(app, 'notifications/initialized', rid=None).status_code == 202
|
||||
assert rpc(app, 'nope').get_json()['error']['code'] == -32601
|
||||
|
||||
|
||||
def test_tools_list_follows_scopes(app):
|
||||
full = {t['name'] for t in rpc(app, 'tools/list').get_json()['result']['tools']}
|
||||
assert {'list_incidents', 'add_known_condition', 'attach_ticket'} <= full
|
||||
read = {t['name'] for t in rpc(app, 'tools/list', tok=token(scopes=(READ,))).get_json()['result']['tools']}
|
||||
assert 'add_known_condition' not in read and 'what_covers' in read
|
||||
err = rpc(app, 'tools/call', {'name': 'add_known_condition', 'arguments': {}}, token(scopes=(READ,)))
|
||||
assert err.get_json()['error']['code'] == -32001
|
||||
|
||||
|
||||
def test_read_tools(app):
|
||||
assert not call(app, 'list_incidents', {'include_recent': False})[0]
|
||||
is_err, text = call(app, 'get_incident', {'key': 'host:compute-storage-01:oom'})
|
||||
assert not is_err and '"links": []' in text
|
||||
assert call(app, 'get_incident', {'key': 'nope'})[0]
|
||||
is_err, text = call(app, 'what_covers', {'host': 'large1'})
|
||||
assert not is_err and '693930698' in text and 'compute-storage-02' in text
|
||||
assert call(app, 'what_covers', {})[0]
|
||||
assert not call(app, 'thor_status')[0]
|
||||
assert '693930698' in call(app, 'list_known_conditions')[1]
|
||||
unknown = rpc(app, 'tools/call', {'name': 'nope'}).get_json()
|
||||
assert unknown['error']['code'] == -32602
|
||||
|
||||
|
||||
def test_known_condition_tools_validate_and_record_who(app):
|
||||
store = app.config['THOR_STORE']
|
||||
assert call(app, 'add_known_condition', {'kind': 'Reboot!', 'subject': 'pbs', 'reason': 'long enough'})[0]
|
||||
assert call(app, 'add_known_condition', {'kind': 'reboot', 'subject': 'pbs', 'reason': 'short'})[0]
|
||||
assert call(app, 'add_known_condition', {'kind': 'reboot', 'subject': 'pbs', 'ticket_id': 'abc',
|
||||
'reason': 'long enough reason'})[0]
|
||||
is_err, text = call(app, 'add_known_condition', {'kind': 'reboot', 'subject': 'micro1', 'ticket_id': '12345',
|
||||
'reason': 'flaky NIC, tracked in 12345'})
|
||||
assert not is_err
|
||||
added = store.known[-1]
|
||||
assert (added['subject'], added['created_by'], added['ticket_id']) == ('monitor-01', 'jared', '12345')
|
||||
assert not call(app, 'end_known_condition', {'id': added['id']})[0]
|
||||
assert call(app, 'end_known_condition', {'id': added['id']})[0] # already ended
|
||||
assert call(app, 'end_known_condition', {'id': 'x'})[0]
|
||||
|
||||
|
||||
def test_attach_and_detach(app):
|
||||
store = app.config['THOR_STORE']
|
||||
is_err, text = call(app, 'attach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'})
|
||||
assert not is_err and 'shadow' in text
|
||||
assert store.links[0]['added_by'] == 'jared'
|
||||
a = store.actions[-1]
|
||||
assert a['kind'] == 'attach' and a['status'] == 'shadow' and a['payload']['ticket_id'] == '615797777'
|
||||
assert call(app, 'attach_ticket', {'key': 'maintenance:gandalf:2', 'ticket_id': '1'})[0]
|
||||
assert call(app, 'attach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': 'x'})[0]
|
||||
assert call(app, 'attach_ticket', {'key': 'nope', 'ticket_id': '1'})[0]
|
||||
assert not call(app, 'detach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'})[0]
|
||||
assert call(app, 'detach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'})[0]
|
||||
|
||||
|
||||
def test_database_away_is_a_tool_error_not_a_crash(app):
|
||||
app.config['THOR_STORE'].down = True
|
||||
is_err, text = call(app, 'list_incidents')
|
||||
assert is_err and 'database' in text
|
||||
|
||||
|
||||
def test_batches_get_and_garbage(app):
|
||||
c = app.test_client()
|
||||
auth = {'Authorization': f'Bearer {token()}'}
|
||||
r = c.post('/mcp', json=[{'jsonrpc': '2.0', 'id': 1, 'method': 'ping'},
|
||||
{'jsonrpc': '2.0', 'method': 'notifications/initialized'}], headers=auth)
|
||||
assert len(r.get_json()) == 1
|
||||
assert c.post('/mcp', json=[{'jsonrpc': '2.0', 'method': 'x'}], headers=auth).status_code == 202
|
||||
assert c.post('/mcp', data='{', headers=dict(auth, **{'Content-Type': 'application/json'})).status_code == 400
|
||||
assert c.post('/mcp', json='just a string', headers=auth).status_code == 400
|
||||
assert c.get('/mcp').status_code == 405
|
||||
+30
@@ -148,6 +148,19 @@ MIGRATIONS: List[str] = [
|
||||
'The 2017 UPS battery reports replace-battery and a short runtime but works (Grafana silences until 2029).',
|
||||
'thor#1', UTC_TIMESTAMP(3));
|
||||
""",
|
||||
# 4: tickets from other apps attached to an incident (MCP attach_ticket)
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS incident_links (
|
||||
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
incident_key VARCHAR(191) NOT NULL,
|
||||
ticket_id VARCHAR(16) NOT NULL,
|
||||
added_by VARCHAR(64) NOT NULL,
|
||||
added_at DATETIME(3) NOT NULL,
|
||||
removed_by VARCHAR(64) NULL,
|
||||
removed_at DATETIME(3) NULL,
|
||||
KEY idx_links_incident (incident_key, removed_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
""",
|
||||
]
|
||||
|
||||
|
||||
@@ -411,3 +424,20 @@ class Store:
|
||||
r['created_at'], r['sent_at'] = from_dt(r['created_at']), from_dt(r['sent_at'])
|
||||
r['payload'] = json.loads(r['payload'] or '{}')
|
||||
return rows
|
||||
|
||||
# -- attached tickets ---------------------------------------------------------
|
||||
def add_incident_link(self, key: str, ticket_id: str, who: str, now: float) -> int:
|
||||
return self.db.execute("""INSERT INTO incident_links (incident_key, ticket_id, added_by, added_at)
|
||||
VALUES (%s, %s, %s, %s)""", (key, ticket_id, who, to_dt(now)))
|
||||
|
||||
def remove_incident_link(self, key: str, ticket_id: str, who: str, now: float) -> int:
|
||||
return self.db.execute("""UPDATE incident_links SET removed_by=%s, removed_at=%s
|
||||
WHERE incident_key=%s AND ticket_id=%s AND removed_at IS NULL""",
|
||||
(who, to_dt(now), key, ticket_id))
|
||||
|
||||
def incident_links(self, key: str) -> List[Dict[str, Any]]:
|
||||
rows = self.db.query("""SELECT ticket_id, added_by, added_at FROM incident_links
|
||||
WHERE incident_key=%s AND removed_at IS NULL ORDER BY id""", (key,))
|
||||
for r in rows:
|
||||
r['added_at'] = from_dt(r['added_at'])
|
||||
return rows
|
||||
+1
-1
@@ -54,7 +54,7 @@ class Outbox:
|
||||
if r.ok and a['kind'] == 'escalate' and p.get('comment'):
|
||||
self.tinker.comment(r.ticket_id, p['comment'])
|
||||
return r.ok, r.ticket_id, r.error
|
||||
if a['kind'] == 'known_note':
|
||||
if a['kind'] in ('known_note', 'attach'):
|
||||
ok = self.tinker.comment(p['ticket_id'], p['comment'])
|
||||
return ok, p['ticket_id'], '' if ok else 'comment failed'
|
||||
if a['kind'] in COMMENT_KINDS:
|
||||
|
||||
+2
-1
@@ -38,9 +38,10 @@ def create_app(settings: config_mod.Settings, store: Store, version: str,
|
||||
clock: Callable[[], float] = time.time) -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.config.update(THOR_SETTINGS=settings, THOR_STORE=store, THOR_VERSION=version, THOR_CLOCK=clock)
|
||||
from . import api, ui
|
||||
from . import api, mcp, ui
|
||||
app.register_blueprint(api.bp)
|
||||
app.register_blueprint(ui.bp)
|
||||
app.register_blueprint(mcp.bp)
|
||||
|
||||
@app.after_request
|
||||
def security_headers(resp):
|
||||
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
"""Thor's MCP server (thor#1; wiki: Architecture/mcp-servers).
|
||||
|
||||
Streamable HTTP at ``POST /mcp``, stateless JSON-RPC 2.0, like the Tinker, Wiki and Kuma
|
||||
servers. Claude Code signs in through Authelia (OAuth 2.1 + PKCE, two-factor) and sends the
|
||||
access token; Thor checks it itself against Authelia's JWKS: signature (RS256), ``iss``,
|
||||
``aud`` (this server's URL), ``exp``, ``typ: at+jwt``, ``client_id`` and the ``scp`` array.
|
||||
It never trusts ``Remote-*`` headers, and logs every tool call with the user.
|
||||
|
||||
Tools: read Thor's incidents, the covering check, Thor's own status and known conditions
|
||||
(``thor:read``); add or end a known condition and attach or detach another app's ticket to an
|
||||
incident (``thor:write``). Maintenance stays in Gandalf (thor#1).
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
import jwt
|
||||
from flask import Blueprint, Response, current_app, jsonify, request
|
||||
|
||||
from ..db import DatabaseError
|
||||
from ..hosts import HostRegistry
|
||||
from . import views
|
||||
|
||||
logger = logging.getLogger('thor.mcp')
|
||||
bp = Blueprint('mcp', __name__)
|
||||
|
||||
ISSUER = 'https://auth.lotusguild.org'
|
||||
JWKS_URL = f'{ISSUER}/jwks.json'
|
||||
CLIENT_ID = 'thor-mcp'
|
||||
READ, WRITE = 'thor:read', 'thor:write'
|
||||
ALLOWED_GROUPS = ('admin',)
|
||||
PROTOCOL_VERSIONS = ('2025-06-18', '2025-03-26', '2024-11-05')
|
||||
TICKET_RE = re.compile(r'^\d{1,16}$')
|
||||
KIND_RE = re.compile(r'^[a-z_*]{1,32}$')
|
||||
|
||||
|
||||
class AuthError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def resource_url(settings) -> str:
|
||||
return f'{settings.public_url.rstrip("/")}/mcp'
|
||||
|
||||
|
||||
def _jwks_client() -> jwt.PyJWKClient:
|
||||
client = current_app.config.get('THOR_JWKS')
|
||||
if client is None:
|
||||
client = jwt.PyJWKClient(JWKS_URL, cache_keys=True, lifespan=3600, timeout=10)
|
||||
current_app.config['THOR_JWKS'] = client
|
||||
return client
|
||||
|
||||
|
||||
def verify_token(token: str, settings, jwks=None) -> Dict[str, Any]:
|
||||
"""The token's claims, or AuthError. ``jwks`` is a PyJWKClient (or a test double)."""
|
||||
try:
|
||||
header = jwt.get_unverified_header(token)
|
||||
except jwt.PyJWTError as e:
|
||||
raise AuthError(f'malformed token: {e}') from e
|
||||
if str(header.get('typ', '')).lower() not in ('at+jwt', 'application/at+jwt'):
|
||||
raise AuthError('not an access token')
|
||||
try:
|
||||
key = (jwks or _jwks_client()).get_signing_key_from_jwt(token).key
|
||||
claims = jwt.decode(token, key, algorithms=['RS256'], audience=resource_url(settings), issuer=ISSUER,
|
||||
options={'require': ['exp', 'iss', 'aud', 'sub']})
|
||||
except jwt.PyJWTError as e:
|
||||
raise AuthError(str(e)) from e
|
||||
if claims.get('client_id') != CLIENT_ID:
|
||||
raise AuthError('token was issued to another client')
|
||||
scopes = claims.get('scp') or []
|
||||
if isinstance(scopes, str):
|
||||
scopes = scopes.split()
|
||||
claims['scopes'] = set(scopes)
|
||||
if not claims['scopes'] & {READ, WRITE}:
|
||||
raise AuthError('token has no thor scope')
|
||||
groups = claims.get('groups') or []
|
||||
if not any(g in groups for g in ALLOWED_GROUPS):
|
||||
raise AuthError('requires group: admin')
|
||||
return claims
|
||||
|
||||
|
||||
def _unauthorized(settings, error: str, description: str):
|
||||
meta = f'{settings.public_url.rstrip("/")}/.well-known/oauth-protected-resource/mcp'
|
||||
resp = jsonify({'error': error, 'error_description': description})
|
||||
resp.status_code = 401 if error != 'insufficient_scope' else 403
|
||||
resp.headers['WWW-Authenticate'] = (f'Bearer resource_metadata="{meta}", scope="{READ} {WRITE}", '
|
||||
f'error="{error}"')
|
||||
return resp
|
||||
|
||||
|
||||
@bp.route('/.well-known/oauth-protected-resource', methods=['GET'])
|
||||
@bp.route('/.well-known/oauth-protected-resource/mcp', methods=['GET'])
|
||||
def protected_resource():
|
||||
settings = current_app.config['THOR_SETTINGS']
|
||||
return jsonify({'resource': resource_url(settings), 'authorization_servers': [ISSUER],
|
||||
'scopes_supported': [READ, WRITE], 'bearer_methods_supported': ['header'],
|
||||
'resource_name': 'Thor'})
|
||||
|
||||
|
||||
# -- tools ----------------------------------------------------------------------
|
||||
def _now() -> float:
|
||||
clock: Callable[[], float] = current_app.config.get('THOR_CLOCK', time.time)
|
||||
return clock()
|
||||
|
||||
|
||||
def _store():
|
||||
return current_app.config['THOR_STORE']
|
||||
|
||||
|
||||
def _hosts() -> HostRegistry:
|
||||
return current_app.config.get('THOR_HOSTS') or HostRegistry()
|
||||
|
||||
|
||||
def t_list_incidents(args, user):
|
||||
data = views.incidents(_store(), _now(), current_app.config['THOR_SETTINGS'].public_url)
|
||||
if not args.get('include_recent', True):
|
||||
data['recent'] = []
|
||||
return data
|
||||
|
||||
|
||||
def t_get_incident(args, user):
|
||||
key = str(args.get('key') or '')
|
||||
detail = views.incident_detail(_store(), key, current_app.config['THOR_SETTINGS'].public_url)
|
||||
if detail is None:
|
||||
raise ToolError(f'No incident with key {key!r}.')
|
||||
detail['links'] = _store().incident_links(key)
|
||||
return detail
|
||||
|
||||
|
||||
def t_covering(args, user):
|
||||
host, scope = args.get('host'), args.get('scope')
|
||||
if not host and not scope:
|
||||
raise ToolError('Give host or scope.')
|
||||
return views.covering(_store(), _hosts(), host, scope, current_app.config['THOR_SETTINGS'].public_url)
|
||||
|
||||
|
||||
def t_status(args, user):
|
||||
return views.thor_status(_store(), current_app.config['THOR_SETTINGS'], _now())
|
||||
|
||||
|
||||
def t_list_known(args, user):
|
||||
return {'known_conditions': _store().known_conditions()}
|
||||
|
||||
|
||||
def t_add_known(args, user):
|
||||
kind, subject = str(args.get('kind') or ''), str(args.get('subject') or '')
|
||||
ticket = args.get('ticket_id')
|
||||
reason = str(args.get('reason') or '').strip()
|
||||
if not KIND_RE.match(kind):
|
||||
raise ToolError('kind must be a check kind such as reboot, oom, ceph_flag (or * for any).')
|
||||
if subject != '*':
|
||||
canonical = _hosts().canonical(subject)
|
||||
subject = canonical or subject
|
||||
if not subject or len(subject) > 64:
|
||||
raise ToolError('subject must be a host name, a flag name, or *.')
|
||||
if ticket is not None and not TICKET_RE.match(str(ticket)):
|
||||
raise ToolError('ticket_id must be a Tinker ticket number.')
|
||||
if len(reason) < 10:
|
||||
raise ToolError('Give a reason of at least a few words; it goes into every note Thor adds.')
|
||||
new_id = _store().add_known_condition(kind, subject, str(ticket) if ticket else None, reason,
|
||||
user['name'], _now())
|
||||
return {'id': new_id, 'kind': kind, 'subject': subject, 'ticket_id': ticket,
|
||||
'note': 'The monitor picks this up on its next cycle (within 2 minutes).'}
|
||||
|
||||
|
||||
def t_end_known(args, user):
|
||||
try:
|
||||
cid = int(args.get('id'))
|
||||
except (TypeError, ValueError):
|
||||
raise ToolError('id must be the known condition id from list_known_conditions.') from None
|
||||
if not _store().end_known_condition(cid, user['name'], _now()):
|
||||
raise ToolError(f'No active known condition with id {cid}.')
|
||||
return {'id': cid, 'ended': True}
|
||||
|
||||
|
||||
def _incident_for_link(key: str) -> Dict[str, Any]:
|
||||
inc = _store().get_incident(key)
|
||||
if not inc:
|
||||
raise ToolError(f'No incident with key {key!r}.')
|
||||
if not inc.get('ticket', True):
|
||||
raise ToolError('That incident is timeline only (maintenance); it has no ticket to link to.')
|
||||
return inc
|
||||
|
||||
|
||||
def t_attach(args, user):
|
||||
key, ticket = str(args.get('key') or ''), str(args.get('ticket_id') or '')
|
||||
if not TICKET_RE.match(ticket):
|
||||
raise ToolError('ticket_id must be a Tinker ticket number.')
|
||||
inc = _incident_for_link(key)
|
||||
store = _store()
|
||||
store.add_incident_link(key, ticket, user['name'], _now())
|
||||
store.add_action({'incident_key': key, 'kind': 'attach', 'created': _now(), 'mode': inc.get('mode', 'shadow'),
|
||||
'payload': {'ticket_id': ticket, 'comment': (
|
||||
f'**Root cause: {inc.get("summary")}** (`{key}`), tracked by Thor. '
|
||||
f'Attached by {user["name"]}. Close this ticket when you are happy it is covered.')}})
|
||||
sent = 'recorded (shadow: nothing sent)' if inc.get('mode') != 'live' else 'queued: Thor comments on it'
|
||||
return {'incident': key, 'ticket_id': ticket, 'attached': True, 'tinker': sent}
|
||||
|
||||
|
||||
def t_detach(args, user):
|
||||
key, ticket = str(args.get('key') or ''), str(args.get('ticket_id') or '')
|
||||
if not _store().remove_incident_link(key, ticket, user['name'], _now()):
|
||||
raise ToolError(f'Ticket {ticket} is not attached to {key!r}.')
|
||||
return {'incident': key, 'ticket_id': ticket, 'attached': False}
|
||||
|
||||
|
||||
class ToolError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _schema(props: Dict[str, Any], required: List[str] = ()) -> Dict[str, Any]:
|
||||
return {'type': 'object', 'properties': props, 'required': list(required), 'additionalProperties': False}
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{'name': 'list_incidents', 'scope': READ, 'fn': t_list_incidents,
|
||||
'description': "Thor's active incidents (one per root cause) and the last 7 days, with priority, state, "
|
||||
'shadow or live mode and ticket numbers.',
|
||||
'inputSchema': _schema({'include_recent': {'type': 'boolean', 'description': 'Include the last 7 days.'}})},
|
||||
{'name': 'get_incident', 'scope': READ, 'fn': t_get_incident,
|
||||
'description': 'One incident: what happened, what is filed under it, every action Thor sent or would have '
|
||||
'sent, the ticket text, and attached tickets.',
|
||||
'inputSchema': _schema({'key': {'type': 'string', 'description': 'e.g. host:compute-storage-01:oom'}}, ['key'])},
|
||||
{'name': 'what_covers', 'scope': READ, 'fn': t_covering,
|
||||
'description': "What would Thor do for a host or scope: Gandalf's and hwmonDaemon's pre-check, showing "
|
||||
'which incident or known condition covers it and whether there is a ticket to comment on.',
|
||||
'inputSchema': _schema({'host': {'type': 'string'},
|
||||
'scope': {'type': 'string', 'description': 'cluster, or source:<name>'}})},
|
||||
{'name': 'thor_status', 'scope': READ, 'fn': t_status,
|
||||
'description': "Thor's own health: last cycle, whether it is catching up, each source answering or blind, "
|
||||
'and blind periods in the last 24 hours.',
|
||||
'inputSchema': _schema({})},
|
||||
{'name': 'list_known_conditions', 'scope': READ, 'fn': t_list_known,
|
||||
'description': 'Known conditions: things Thor notes on an existing ticket instead of opening a new one.',
|
||||
'inputSchema': _schema({})},
|
||||
{'name': 'add_known_condition', 'scope': WRITE, 'fn': t_add_known,
|
||||
'description': 'Tell Thor a condition is known and tracked, so it adds notes to that ticket instead of '
|
||||
'opening new ones. kind is the check kind (reboot, oom, fenced, ceph_flag, or *), subject a '
|
||||
'host (old names work), a flag, or *.',
|
||||
'inputSchema': _schema({'kind': {'type': 'string'}, 'subject': {'type': 'string'},
|
||||
'ticket_id': {'type': 'string', 'description': 'Tracking ticket (optional).'},
|
||||
'reason': {'type': 'string', 'description': 'Why it is known; shown in every note.'}},
|
||||
['kind', 'subject', 'reason'])},
|
||||
{'name': 'end_known_condition', 'scope': WRITE, 'fn': t_end_known,
|
||||
'description': 'End a known condition, so Thor tickets it again.',
|
||||
'inputSchema': _schema({'id': {'type': 'integer'}}, ['id'])},
|
||||
{'name': 'attach_ticket', 'scope': WRITE, 'fn': t_attach,
|
||||
'description': "Attach another app's ticket (a symptom) to a Thor incident: Thor comments 'Root cause' on "
|
||||
'it (only once the incident is live) and lists it on the incident. You close it.',
|
||||
'inputSchema': _schema({'key': {'type': 'string'}, 'ticket_id': {'type': 'string'}}, ['key', 'ticket_id'])},
|
||||
{'name': 'detach_ticket', 'scope': WRITE, 'fn': t_detach,
|
||||
'description': 'Remove a ticket attached with attach_ticket.',
|
||||
'inputSchema': _schema({'key': {'type': 'string'}, 'ticket_id': {'type': 'string'}}, ['key', 'ticket_id'])},
|
||||
]
|
||||
BY_NAME = {t['name']: t for t in TOOLS}
|
||||
|
||||
|
||||
def _rpc_result(rid, result):
|
||||
return {'jsonrpc': '2.0', 'id': rid, 'result': result}
|
||||
|
||||
|
||||
def _rpc_error(rid, code: int, message: str):
|
||||
return {'jsonrpc': '2.0', 'id': rid, 'error': {'code': code, 'message': message}}
|
||||
|
||||
|
||||
def _handle(msg: Dict[str, Any], claims: Dict[str, Any], user: Dict[str, str]) -> Optional[Dict[str, Any]]:
|
||||
rid, method, params = msg.get('id'), msg.get('method'), msg.get('params') or {}
|
||||
if method is None:
|
||||
return None # a response or something we don't take
|
||||
if rid is None:
|
||||
return None # notification (e.g. notifications/initialized): no reply
|
||||
if method == 'initialize':
|
||||
asked = params.get('protocolVersion')
|
||||
return _rpc_result(rid, {
|
||||
'protocolVersion': asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
|
||||
'capabilities': {'tools': {'listChanged': False}},
|
||||
'serverInfo': {'name': 'thor', 'version': current_app.config.get('THOR_VERSION', '')[:12] or 'dev'},
|
||||
'instructions': ("Thor watches the LotusGuild cluster from outside and keeps one incident per root cause. "
|
||||
"Everything is in shadow until a check goes live: Thor records what it would send to "
|
||||
"Tinker but sends nothing. Maintenance is declared in Gandalf, not here.")})
|
||||
if method == 'ping':
|
||||
return _rpc_result(rid, {})
|
||||
if method == 'tools/list':
|
||||
visible = [t for t in TOOLS if t['scope'] in claims['scopes']]
|
||||
return _rpc_result(rid, {'tools': [{'name': t['name'], 'description': t['description'],
|
||||
'inputSchema': t['inputSchema']} for t in visible]})
|
||||
if method == 'tools/call':
|
||||
name = params.get('name')
|
||||
tool = BY_NAME.get(name)
|
||||
if tool is None:
|
||||
return _rpc_error(rid, -32602, f'Unknown tool {name!r}.')
|
||||
if tool['scope'] not in claims['scopes']:
|
||||
return _rpc_error(rid, -32001, f'{name} needs the {tool["scope"]} scope; log in again and approve it.')
|
||||
args = params.get('arguments') or {}
|
||||
ok = True
|
||||
try:
|
||||
out = tool['fn'](args, user)
|
||||
text = json.dumps(out, default=str, indent=1)
|
||||
except ToolError as e:
|
||||
ok, text = False, str(e)
|
||||
except DatabaseError:
|
||||
ok, text = False, 'Thor cannot reach its database right now; try again in a minute.'
|
||||
logger.info(json.dumps({'mcp': name, 'user': user['name'], 'sub': claims.get('sub'),
|
||||
'args': args, 'ok': ok}, default=str))
|
||||
return _rpc_result(rid, {'content': [{'type': 'text', 'text': text}], 'isError': not ok})
|
||||
return _rpc_error(rid, -32601, f'Method {method!r} not found.')
|
||||
|
||||
|
||||
@bp.route('/mcp', methods=['POST'])
|
||||
def mcp_post():
|
||||
settings = current_app.config['THOR_SETTINGS']
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth.startswith('Bearer '):
|
||||
return _unauthorized(settings, 'invalid_request', 'Sign in through Authelia (claude mcp login thor).')
|
||||
try:
|
||||
claims = verify_token(auth[7:].strip(), settings, current_app.config.get('THOR_JWKS'))
|
||||
except AuthError as e:
|
||||
logger.warning('MCP token refused: %s', e)
|
||||
if 'group' in str(e):
|
||||
return jsonify({'error': 'forbidden', 'error_description': str(e)}), 403
|
||||
return _unauthorized(settings, 'invalid_token', str(e))
|
||||
user = {'name': claims.get('preferred_username') or claims.get('name') or claims.get('sub', '?')}
|
||||
try:
|
||||
body = request.get_json(force=True, silent=False)
|
||||
except Exception:
|
||||
return jsonify(_rpc_error(None, -32700, 'Parse error')), 400
|
||||
if isinstance(body, list):
|
||||
replies = [r for r in (_handle(m, claims, user) for m in body if isinstance(m, dict)) if r is not None]
|
||||
return (jsonify(replies), 200) if replies else Response(status=202)
|
||||
if not isinstance(body, dict):
|
||||
return jsonify(_rpc_error(None, -32600, 'Invalid request')), 400
|
||||
reply = _handle(body, claims, user)
|
||||
return (jsonify(reply), 200) if reply is not None else Response(status=202)
|
||||
|
||||
|
||||
@bp.route('/mcp', methods=['GET', 'DELETE'])
|
||||
def mcp_other():
|
||||
# Stateless server: no server-to-client stream and no sessions to end.
|
||||
return Response(status=405, headers={'Allow': 'POST'})
|
||||
@@ -20,6 +20,7 @@
|
||||
<dt>Last seen</dt><dd>{{ i.last_seen | utc }}</dd>
|
||||
{% if i.cleared_at %}<dt>Cleared</dt><dd>{{ i.cleared_at | utc }}</dd>{% endif %}
|
||||
{% for k, v in (d.facts.display or {}).items() %}<dt>{{ k }}</dt><dd>{{ v }}</dd>{% endfor %}
|
||||
{% if d.links %}<dt>Attached tickets</dt><dd>{% for l in d.links %}<a href="https://t.lotusguild.org/ticket/{{ l.ticket_id }}">#{{ l.ticket_id }}</a> (by {{ l.added_by }}){% if not loop.last %}, {% endif %}{% endfor %}</dd>{% endif %}
|
||||
{% if d.facts.escalation_reason and i.priority and i.priority < 3 %}<dt>Why this priority</dt><dd>{{ d.facts.escalation_reason }}</dd>{% endif %}
|
||||
</dl>
|
||||
{% if d.seen_after_the_fact %}<p class="t-note">Seen after the fact: Thor was away or blind while this happened and found it when it caught up.</p>{% endif %}
|
||||
|
||||
@@ -117,6 +117,8 @@ def incident_detail(store, key: str, public_url: str = '') -> Optional[Dict[str,
|
||||
events = sorted(inc.get('events') or [], key=lambda e: e.get('at', 0))
|
||||
preview = next((a['payload'] for a in reversed(actions)
|
||||
if a['kind'] in ('open', 'escalate', 'refresh') and a['payload'].get('description')), None)
|
||||
links = store.incident_links(key)
|
||||
return {'incident': brief, 'facts': inc.get('facts') or {}, 'events': events, 'symptoms': symptoms,
|
||||
'links': links,
|
||||
'actions': actions, 'preview': preview, 'known_reason': inc.get('known_reason', ''),
|
||||
'seen_after_the_fact': inc.get('seen_after_the_fact', False)}
|
||||
Reference in new issue
Block a user