""" Тесты живого пути ОТВЕТОВ нижестоящего MCP-сервера: MCPSentinel.process_outgoing_jsonrpc(). Проверяется напрямую, без подпроцесса (в отличие от полного run_stdio_proxy). """ import json import os import shutil import tempfile import unittest from mcp_sentinel import MCPSentinel class TestProcessOutgoingJsonRpc(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp() self.ledger_path = os.path.join(self.test_dir, "outgoing_audit.jsonl") self.sentinel = MCPSentinel(ledger_path=self.ledger_path) def tearDown(self): shutil.rmtree(self.test_dir, ignore_errors=True) def _response_line(self, text: str, msg_id=1) -> str: resp = { "jsonrpc": "2.0", "id": msg_id, "result": { "content": [{"type": "text", "text": text}], "isError": False, }, } return json.dumps(resp) + "\n" def test_blocks_response_leaking_private_key(self): line = self._response_line( "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA PRIVATE KEY-----", msg_id=7, ) out_line = self.sentinel.process_outgoing_jsonrpc(line, agent_id="cursor-bot", tool_name="read_file") resp = json.loads(out_line) self.assertTrue(resp["result"]["isError"]) self.assertEqual(resp["id"], 7) self.assertIn("CIRCUIT BREAKER", resp["result"]["content"][0]["text"]) # Заблокированный ответ фиксируется в журнале is_valid, count, _msg = self.sentinel.ledger.verify() self.assertTrue(is_valid) self.assertEqual(count, 1) self.assertEqual(self.sentinel.ledger.get_stats()["blocks"], 1) def test_permits_ordinary_text_response(self): line = self._response_line("Отчёт успешно сформирован, ошибок не обнаружено.", msg_id=8) out_line = self.sentinel.process_outgoing_jsonrpc(line, agent_id="cursor-bot", tool_name="read_file") self.assertEqual(out_line, line, "Обычный текст должен пройти без изменений") def test_passes_through_non_jsonrpc_lines_unchanged(self): # Не-JSON строка self.assertEqual(self.sentinel.process_outgoing_jsonrpc("not json at all\n", "a", "t"), "not json at all\n") # Пустая строка self.assertEqual(self.sentinel.process_outgoing_jsonrpc("\n", "a", "t"), "\n") # JSON без result.content (например, обычное уведомление) notice = json.dumps({"jsonrpc": "2.0", "method": "notifications/progress"}) + "\n" self.assertEqual(self.sentinel.process_outgoing_jsonrpc(notice, "a", "t"), notice) if __name__ == "__main__": unittest.main()