MCP v1: Thor's tools for Claude Code, behind Authelia OAuth (thor#1)
CI / Test (pytest) (pull_request) Successful in 1m13s
CI / Integration (MariaDB) (pull_request) Successful in 2m36s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m25s
CI / UI (screenshots) (pull_request) Failing after 8s
CI / Lint (flake8, house style) (pull_request) Successful in 58s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Failing after 1m26s
CI / Deploy (pull_request) Skipped
CI / Test (pytest) (pull_request) Successful in 1m13s
CI / Integration (MariaDB) (pull_request) Successful in 2m36s
CI / Security (bandit, pip-audit) (pull_request) Successful in 1m25s
CI / UI (screenshots) (pull_request) Failing after 8s
CI / Lint (flake8, house style) (pull_request) Successful in 58s
CI / Scan (secrets, workflows, shell, patterns) (pull_request) Failing after 1m26s
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
ab4b20d15f
commit
9f993dabf1
10 files changed
+593
-3
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user