160 lines
7.7 KiB
Python
160 lines
7.7 KiB
Python
import json
|
|
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
|
|
|
|
VERSION = '2026-07-28'
|
|
TOOL = {'name': 'echo', 'description': 'Echo text',
|
|
'inputSchema': {'type': 'object', 'properties': {'text': {'type': 'string'}}}}
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def reply(self, status, payload=b'', kind='application/json', headers=()):
|
|
if isinstance(payload, (dict, list)):
|
|
payload = json.dumps(payload).encode()
|
|
self.send_response(status)
|
|
self.send_header('Content-Type', kind)
|
|
self.send_header('Content-Length', str(len(payload)))
|
|
for key, value in headers:
|
|
self.send_header(key, value)
|
|
self.end_headers()
|
|
self.wfile.write(payload)
|
|
|
|
def body(self):
|
|
return json.loads(self.rfile.read(int(self.headers['Content-Length'])))
|
|
|
|
def do_POST(self):
|
|
message = self.body()
|
|
method = message.get('method')
|
|
args = message.get('params', {})
|
|
if self.path == '/compatible/v1/chat/completions':
|
|
if self.headers.get('Authorization') != 'Bearer fixture-token':
|
|
self.reply(401)
|
|
return
|
|
assert message['stream'] and message['model'] == 'fixture-model'
|
|
assert message['messages'][0] == {'role': 'system', 'content': 'Silent instruction'}
|
|
assert message['temperature'] == 0 and message['max_tokens'] == 32
|
|
assert 'options' not in message and 'think' not in message
|
|
frames = [
|
|
{'choices': [{'delta': {'reasoning_content': 'Thinking'}}]},
|
|
{'choices': [{'delta': {'content': 'Fixture response'}}]},
|
|
{'choices': [{'delta': {}, 'finish_reason': 'stop'}]},
|
|
]
|
|
payload = ''.join(f'data: {json.dumps(frame)}\n\n' for frame in frames)
|
|
self.reply(200, (payload + 'data: [DONE]\n\n').encode(), 'text/event-stream')
|
|
return
|
|
if self.path == '/chat-web/api/chat':
|
|
system, user = message['messages']
|
|
if system['role'] != 'system' or 'Test passage.' not in system['content'] or '/article' not in user['content']:
|
|
self.reply(400)
|
|
return
|
|
self.reply(200, b'{"message":{"content":"Page received."},"done":true}\n', 'application/x-ndjson')
|
|
return
|
|
if self.path == '/chat-tools/api/chat':
|
|
system, user = message['messages']
|
|
valid = (system['role'] == 'system' and 'fixture/visible-repo' in system['content']
|
|
and 'source: knowledge.md' in system['content']
|
|
and user == {'role': 'user', 'content': 'can you see my git repos'})
|
|
if not valid:
|
|
self.reply(400)
|
|
return
|
|
self.reply(200, b'{"message":{"content":"Repository and knowledge received."},"done":true}\n',
|
|
'application/x-ndjson')
|
|
return
|
|
if self.path == '/gateway/api/chat':
|
|
if self.headers.get('Authorization') != 'Bearer fixture-token':
|
|
self.reply(401)
|
|
return
|
|
assert message['model'] == 'fixture:latest' and message['stream']
|
|
payload = b'{"message":{"content":"fixture answer"},"done":false}\n{"done":true}\n'
|
|
self.reply(200, payload, 'application/x-ndjson')
|
|
return
|
|
if self.path == '/ollama/api/pull':
|
|
assert message['model'] == 'fixture:latest'
|
|
self.server.models.add(message['model'])
|
|
self.reply(200, b'{"status":"pulling","total":10,"completed":7}\n{"status":"success"}\n',
|
|
'application/x-ndjson')
|
|
return
|
|
if self.path == '/ollama/api/show':
|
|
assert message['model'] in self.server.models
|
|
self.reply(200, {'capabilities': ['completion']})
|
|
return
|
|
headers = ()
|
|
if self.path == '/legacy' and method == 'server/discover':
|
|
self.reply(400)
|
|
return
|
|
if self.path == '/modern':
|
|
assert self.headers['Mcp-Method'] == method
|
|
assert self.headers['MCP-Protocol-Version'] == VERSION
|
|
assert args['_meta']['io.modelcontextprotocol/protocolVersion'] == VERSION
|
|
elif method not in ('initialize', 'server/discover'):
|
|
assert self.headers['Mcp-Session-Id'] == 'fixture-session'
|
|
assert self.headers['MCP-Protocol-Version'] == '2025-06-18'
|
|
if method == 'initialize':
|
|
result = {'protocolVersion': '2025-06-18', 'capabilities': {'tools': {}}}
|
|
headers = [('Mcp-Session-Id', 'fixture-session')]
|
|
elif method == 'notifications/initialized':
|
|
self.reply(202)
|
|
return
|
|
elif method == 'server/discover':
|
|
result = {'supportedVersions': [VERSION], 'capabilities': {'tools': {}}}
|
|
elif method == 'tools/list':
|
|
result = {'tools': [] if 'cursor' not in args else [TOOL]}
|
|
if 'cursor' not in args:
|
|
result['nextCursor'] = 'second'
|
|
elif method == 'tools/call':
|
|
assert args['name'] == 'echo'
|
|
if self.path == '/modern':
|
|
assert self.headers['Mcp-Name'] == 'echo'
|
|
result = {'content': [{'type': 'text', 'text': args['arguments']['text']}]}
|
|
else:
|
|
raise ValueError(method)
|
|
envelope = {'jsonrpc': '2.0', 'id': message['id'], 'result': result}
|
|
if self.path == '/legacy' and method == 'tools/call':
|
|
payload = (': keepalive\r\n\r\ndata: ' + json.dumps(envelope) + '\r\n\r\n').encode()
|
|
self.reply(200, payload, 'text/event-stream')
|
|
else:
|
|
self.reply(200, envelope, headers=headers)
|
|
|
|
def do_GET(self):
|
|
if self.path == '/search?q=tides+%26+moon&format=json' or self.path == '/search?q=tides%20%26%20moon&format=json':
|
|
page = f'http://127.0.0.1:{self.server.server_port}/article'
|
|
self.reply(200, {'results': [
|
|
{'url': page, 'title': '<b>Moon and tides</b>', 'content': 'A fixture & summary'},
|
|
{'url': 'file:///etc/hosts', 'title': 'Invalid'},
|
|
{'url': page, 'title': 'Duplicate'}]})
|
|
return
|
|
if self.path == '/follow-root':
|
|
self.reply(200, b'<h1>Index</h1><a href="/follow-detail">Tides documentation</a>', 'text/html')
|
|
return
|
|
if self.path == '/follow-detail':
|
|
self.reply(200, b'<p>The tides documentation was followed.</p>', 'text/html')
|
|
return
|
|
if self.path == '/article':
|
|
self.reply(200, b'<h1>Moon and tides</h1><script>ignored()</script><p>Test passage.</p>', 'text/html')
|
|
return
|
|
if self.path == '/compatible/v1/models':
|
|
if self.headers.get('Authorization') != 'Bearer fixture-token':
|
|
self.reply(401)
|
|
return
|
|
self.reply(200, {'data': [{'id': 'fixture-model'}, {'id': 'fixture-model'}]})
|
|
return
|
|
if self.path == '/gateway/api/tags':
|
|
if self.headers.get('Authorization') != 'Bearer fixture-token':
|
|
self.reply(401)
|
|
return
|
|
self.reply(200, {'models': [{'name': 'fixture:latest'}]})
|
|
return
|
|
if self.path == '/redirect/api/tags':
|
|
self.reply(302, headers=[('Location', '/gateway/api/tags')])
|
|
return
|
|
assert self.path == '/ollama/api/tags'
|
|
self.reply(200, {'models': [{'name': model, 'size': 100} for model in self.server.models]})
|
|
|
|
def do_DELETE(self):
|
|
assert self.path == '/ollama/api/delete'
|
|
self.server.models.remove(self.body()['model'])
|
|
self.reply(200)
|
|
|
|
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
|
server.models = set()
|
|
print(server.server_port, flush=True)
|
|
server.serve_forever()
|