247 lines
12 KiB
Python
247 lines
12 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 == '/compatible/api/v1/chat':
|
|
valid = (self.headers.get('Authorization') == 'Bearer fixture-token'
|
|
and message.get('integrations') == ['mcp/fixture']
|
|
and message.get('system_prompt') == 'Silent instruction'
|
|
and message.get('input') == 'Previous conversation for reference:\nuser: Earlier question\n\nassistant: Earlier answer\n\nLatest message:\nUse the fixture'
|
|
and message.get('stream') is True and message.get('store') is False)
|
|
if not valid:
|
|
self.reply(400)
|
|
return
|
|
frames = [
|
|
{'type': 'tool_call.start'},
|
|
{'type': 'reasoning.delta', 'content': 'Checking'},
|
|
{'type': 'message.delta', 'content': 'Plugin response'},
|
|
{'type': 'chat.end', 'result': {'stats': {'total_output_tokens': 2}}},
|
|
]
|
|
payload = ''.join(f"event: {frame['type']}\ndata: {json.dumps(frame)}\n\n" for frame in frames)
|
|
self.reply(200, payload.encode(), 'text/event-stream')
|
|
return
|
|
if self.path == '/chat-rag-off/api/chat':
|
|
if any('Cobalt river trail' in item['content'] for item in message['messages']):
|
|
self.reply(400)
|
|
return
|
|
self.reply(200, b'{"message":{"content":"RAG is off."},"done":true}\n', 'application/x-ndjson')
|
|
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 == '/agent-prompt/api/chat':
|
|
messages = message['messages']
|
|
system, latest = messages[0]['content'], messages[-1]['content']
|
|
if 'You are the Planning' in system:
|
|
valid = (messages[1:-1] == [
|
|
{'role': 'user', 'content': 'Translate red'},
|
|
{'role': 'assistant', 'content': 'rouge'}
|
|
] and latest == 'Translate Translate the word blue' and
|
|
message.get('options', {}).get('num_predict') == 32)
|
|
answer = 'Draft translation.'
|
|
else:
|
|
valid = ('You are the Reviewer' in system and len(messages) == 2 and
|
|
latest.startswith('Translate the word blue') and 'Draft translation.' in latest and
|
|
'[D1] Glossary' in latest and 'blue means bleu' in latest)
|
|
answer = 'Bleu [D1].'
|
|
if not valid:
|
|
self.reply(400)
|
|
return
|
|
payload = json.dumps({'message': {'content': answer}, 'done': True}) + '\n'
|
|
self.reply(200, payload.encode(), 'application/x-ndjson')
|
|
return
|
|
if self.path == '/chat-document/api/chat':
|
|
user = message['messages'][-1]
|
|
valid = (user['role'] == 'user' and
|
|
user['content'].startswith('Tell me about this\n\n') and
|
|
'brief.txt' in user['content'] and 'Cobalt river trail' in user['content'])
|
|
if not valid:
|
|
self.reply(400)
|
|
return
|
|
self.reply(200, b'{"message":{"content":"Document 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 and search the knowledge base for guidance'})
|
|
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']
|
|
if message['messages'][-1]['content'] == 'hello':
|
|
assert message['think'] is False
|
|
assert not any('unrelated.pdf' in item['content'] for item in message['messages'])
|
|
payload = b'{"message":{"content":"Hello!"},"done":false}\n{"done":true}\n'
|
|
self.reply(200, payload, 'application/x-ndjson')
|
|
return
|
|
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/copy':
|
|
assert message['source'] in self.server.models
|
|
self.server.models.add(message['destination'])
|
|
self.reply(200)
|
|
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.startswith('/search-relevance?'):
|
|
assert 'teh' not in self.path
|
|
base = f'http://127.0.0.1:{self.server.server_port}'
|
|
self.reply(200, {'results': [
|
|
{'url': base + '/typo-page', 'title': 'Urban Dictionary: teh', 'content': 'A spelling entry.'},
|
|
{'url': base + '/prompt-page', 'title': 'Prompt engineering examples', 'content': 'Examples of using prompts.'}
|
|
]})
|
|
return
|
|
if self.path == '/typo-page':
|
|
self.reply(500)
|
|
return
|
|
if self.path == '/prompt-page':
|
|
self.reply(200, b'<title>Prompt examples</title><p>Describe the desired task and output.</p>', 'text/html')
|
|
return
|
|
if self.path.startswith('/search-blocked?'):
|
|
page = f'http://127.0.0.1:{self.server.server_port}/blocked-article'
|
|
self.reply(200, {'results': [{'url': page, 'title': 'Fusion facts', 'content': 'Fusion combines nuclei.'}]})
|
|
return
|
|
if self.path == '/blocked-article':
|
|
self.reply(403)
|
|
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()
|