test_mcp_server.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. #!/usr/bin/env python3
  2. """
  3. Comprehensive test suite for Skill Seeker MCP Server
  4. Tests all MCP tools and server functionality
  5. """
  6. import sys
  7. import os
  8. import unittest
  9. import json
  10. import tempfile
  11. import shutil
  12. import asyncio
  13. from pathlib import Path
  14. from unittest.mock import Mock, patch, AsyncMock, MagicMock
  15. # CRITICAL: Import MCP package BEFORE adding project to path
  16. # to avoid shadowing the installed mcp package with our local mcp/ directory
  17. # WORKAROUND for shadowing issue: Temporarily change to /tmp to import external mcp
  18. # This avoids our local mcp/ directory being in the import path
  19. _original_dir = os.getcwd()
  20. try:
  21. os.chdir('/tmp') # Change away from project directory
  22. from mcp.server import Server
  23. from mcp.types import Tool, TextContent
  24. MCP_AVAILABLE = True
  25. except ImportError:
  26. MCP_AVAILABLE = False
  27. print("Warning: MCP package not available, skipping MCP tests")
  28. finally:
  29. os.chdir(_original_dir) # Restore original directory
  30. # NOW add parent directory to path for importing our local modules
  31. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  32. # Import our local MCP server module
  33. if MCP_AVAILABLE:
  34. # Import from installed package (new src/ layout)
  35. try:
  36. from skill_seekers.mcp import server as skill_seeker_server
  37. except ImportError as e:
  38. print(f"Warning: Could not import skill_seeker server: {e}")
  39. skill_seeker_server = None
  40. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  41. class TestMCPServerInitialization(unittest.TestCase):
  42. """Test MCP server initialization"""
  43. def test_server_import(self):
  44. """Test that server module can be imported"""
  45. from mcp import server as mcp_server_module
  46. self.assertIsNotNone(mcp_server_module)
  47. def test_server_initialization(self):
  48. """Test server initializes correctly"""
  49. import mcp.server
  50. app = mcp.server.Server("test-skill-seeker")
  51. self.assertEqual(app.name, "test-skill-seeker")
  52. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  53. class TestListTools(unittest.IsolatedAsyncioTestCase):
  54. """Test list_tools functionality"""
  55. async def test_list_tools_returns_tools(self):
  56. """Test that list_tools returns all expected tools"""
  57. tools = await skill_seeker_server.list_tools()
  58. self.assertIsInstance(tools, list)
  59. self.assertGreater(len(tools), 0)
  60. # Check all expected tools are present
  61. tool_names = [tool.name for tool in tools]
  62. expected_tools = [
  63. "generate_config",
  64. "estimate_pages",
  65. "scrape_docs",
  66. "package_skill",
  67. "list_configs",
  68. "validate_config"
  69. ]
  70. for expected in expected_tools:
  71. self.assertIn(expected, tool_names, f"Missing tool: {expected}")
  72. async def test_tool_schemas(self):
  73. """Test that all tools have valid schemas"""
  74. tools = await skill_seeker_server.list_tools()
  75. for tool in tools:
  76. self.assertIsInstance(tool.name, str)
  77. self.assertIsInstance(tool.description, str)
  78. self.assertIn("inputSchema", tool.__dict__)
  79. # Verify schema has required structure
  80. schema = tool.inputSchema
  81. self.assertEqual(schema["type"], "object")
  82. self.assertIn("properties", schema)
  83. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  84. class TestGenerateConfigTool(unittest.IsolatedAsyncioTestCase):
  85. """Test generate_config tool"""
  86. async def asyncSetUp(self):
  87. """Set up test environment"""
  88. self.temp_dir = tempfile.mkdtemp()
  89. self.original_cwd = os.getcwd()
  90. os.chdir(self.temp_dir)
  91. async def asyncTearDown(self):
  92. """Clean up test environment"""
  93. os.chdir(self.original_cwd)
  94. shutil.rmtree(self.temp_dir, ignore_errors=True)
  95. async def test_generate_config_basic(self):
  96. """Test basic config generation"""
  97. args = {
  98. "name": "test-framework",
  99. "url": "https://test-framework.dev/",
  100. "description": "Test framework skill"
  101. }
  102. result = await skill_seeker_server.generate_config_tool(args)
  103. self.assertIsInstance(result, list)
  104. self.assertGreater(len(result), 0)
  105. self.assertIsInstance(result[0], TextContent)
  106. self.assertIn("✅", result[0].text)
  107. # Verify config file was created
  108. config_path = Path("configs/test-framework.json")
  109. self.assertTrue(config_path.exists())
  110. # Verify config content
  111. with open(config_path) as f:
  112. config = json.load(f)
  113. self.assertEqual(config["name"], "test-framework")
  114. self.assertEqual(config["base_url"], "https://test-framework.dev/")
  115. self.assertEqual(config["description"], "Test framework skill")
  116. async def test_generate_config_with_options(self):
  117. """Test config generation with custom options"""
  118. args = {
  119. "name": "custom-framework",
  120. "url": "https://custom.dev/",
  121. "description": "Custom skill",
  122. "max_pages": 200,
  123. "rate_limit": 1.0
  124. }
  125. result = await skill_seeker_server.generate_config_tool(args)
  126. # Verify config has custom options
  127. config_path = Path("configs/custom-framework.json")
  128. with open(config_path) as f:
  129. config = json.load(f)
  130. self.assertEqual(config["max_pages"], 200)
  131. self.assertEqual(config["rate_limit"], 1.0)
  132. async def test_generate_config_defaults(self):
  133. """Test that default values are applied correctly"""
  134. args = {
  135. "name": "default-test",
  136. "url": "https://test.dev/",
  137. "description": "Test defaults"
  138. }
  139. result = await skill_seeker_server.generate_config_tool(args)
  140. config_path = Path("configs/default-test.json")
  141. with open(config_path) as f:
  142. config = json.load(f)
  143. self.assertEqual(config["max_pages"], 100) # Default
  144. self.assertEqual(config["rate_limit"], 0.5) # Default
  145. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  146. class TestEstimatePagesTool(unittest.IsolatedAsyncioTestCase):
  147. """Test estimate_pages tool"""
  148. async def asyncSetUp(self):
  149. """Set up test environment"""
  150. self.temp_dir = tempfile.mkdtemp()
  151. self.original_cwd = os.getcwd()
  152. os.chdir(self.temp_dir)
  153. # Create a test config
  154. os.makedirs("configs", exist_ok=True)
  155. self.config_path = Path("configs/test.json")
  156. config_data = {
  157. "name": "test",
  158. "base_url": "https://example.com/",
  159. "selectors": {
  160. "main_content": "article",
  161. "title": "h1",
  162. "code_blocks": "pre"
  163. },
  164. "rate_limit": 0.5,
  165. "max_pages": 50
  166. }
  167. with open(self.config_path, 'w') as f:
  168. json.dump(config_data, f)
  169. async def asyncTearDown(self):
  170. """Clean up test environment"""
  171. os.chdir(self.original_cwd)
  172. shutil.rmtree(self.temp_dir, ignore_errors=True)
  173. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  174. async def test_estimate_pages_success(self, mock_streaming):
  175. """Test successful page estimation"""
  176. # Mock successful subprocess run with streaming
  177. # Returns (stdout, stderr, returncode)
  178. mock_streaming.return_value = ("Estimated 50 pages", "", 0)
  179. args = {
  180. "config_path": str(self.config_path)
  181. }
  182. result = await skill_seeker_server.estimate_pages_tool(args)
  183. self.assertIsInstance(result, list)
  184. self.assertIsInstance(result[0], TextContent)
  185. self.assertIn("50 pages", result[0].text)
  186. # Should also have progress message
  187. self.assertIn("Estimating page count", result[0].text)
  188. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  189. async def test_estimate_pages_with_max_discovery(self, mock_streaming):
  190. """Test page estimation with custom max_discovery"""
  191. # Mock successful subprocess run with streaming
  192. mock_streaming.return_value = ("Estimated 100 pages", "", 0)
  193. args = {
  194. "config_path": str(self.config_path),
  195. "max_discovery": 500
  196. }
  197. result = await skill_seeker_server.estimate_pages_tool(args)
  198. # Verify subprocess was called with correct args
  199. mock_streaming.assert_called_once()
  200. call_args = mock_streaming.call_args[0][0]
  201. self.assertIn("--max-discovery", call_args)
  202. self.assertIn("500", call_args)
  203. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  204. async def test_estimate_pages_error(self, mock_streaming):
  205. """Test error handling in page estimation"""
  206. # Mock failed subprocess run with streaming
  207. mock_streaming.return_value = ("", "Config file not found", 1)
  208. args = {
  209. "config_path": "nonexistent.json"
  210. }
  211. result = await skill_seeker_server.estimate_pages_tool(args)
  212. self.assertIn("Error", result[0].text)
  213. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  214. class TestScrapeDocsTool(unittest.IsolatedAsyncioTestCase):
  215. """Test scrape_docs tool"""
  216. async def asyncSetUp(self):
  217. """Set up test environment"""
  218. self.temp_dir = tempfile.mkdtemp()
  219. self.original_cwd = os.getcwd()
  220. os.chdir(self.temp_dir)
  221. # Create test config
  222. os.makedirs("configs", exist_ok=True)
  223. self.config_path = Path("configs/test.json")
  224. config_data = {
  225. "name": "test",
  226. "base_url": "https://example.com/",
  227. "selectors": {
  228. "main_content": "article",
  229. "title": "h1",
  230. "code_blocks": "pre"
  231. }
  232. }
  233. with open(self.config_path, 'w') as f:
  234. json.dump(config_data, f)
  235. async def asyncTearDown(self):
  236. """Clean up test environment"""
  237. os.chdir(self.original_cwd)
  238. shutil.rmtree(self.temp_dir, ignore_errors=True)
  239. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  240. async def test_scrape_docs_basic(self, mock_streaming):
  241. """Test basic documentation scraping"""
  242. # Mock successful subprocess run with streaming
  243. mock_streaming.return_value = ("Scraping completed successfully", "", 0)
  244. args = {
  245. "config_path": str(self.config_path)
  246. }
  247. result = await skill_seeker_server.scrape_docs_tool(args)
  248. self.assertIsInstance(result, list)
  249. self.assertIn("success", result[0].text.lower())
  250. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  251. async def test_scrape_docs_with_skip_scrape(self, mock_streaming):
  252. """Test scraping with skip_scrape flag"""
  253. # Mock successful subprocess run with streaming
  254. mock_streaming.return_value = ("Using cached data", "", 0)
  255. args = {
  256. "config_path": str(self.config_path),
  257. "skip_scrape": True
  258. }
  259. result = await skill_seeker_server.scrape_docs_tool(args)
  260. # Verify --skip-scrape was passed
  261. call_args = mock_streaming.call_args[0][0]
  262. self.assertIn("--skip-scrape", call_args)
  263. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  264. async def test_scrape_docs_with_dry_run(self, mock_streaming):
  265. """Test scraping with dry_run flag"""
  266. # Mock successful subprocess run with streaming
  267. mock_streaming.return_value = ("Dry run completed", "", 0)
  268. args = {
  269. "config_path": str(self.config_path),
  270. "dry_run": True
  271. }
  272. result = await skill_seeker_server.scrape_docs_tool(args)
  273. call_args = mock_streaming.call_args[0][0]
  274. self.assertIn("--dry-run", call_args)
  275. @patch('skill_seekers.mcp.server.run_subprocess_with_streaming')
  276. async def test_scrape_docs_with_enhance_local(self, mock_streaming):
  277. """Test scraping with local enhancement"""
  278. # Mock successful subprocess run with streaming
  279. mock_streaming.return_value = ("Scraping with enhancement", "", 0)
  280. args = {
  281. "config_path": str(self.config_path),
  282. "enhance_local": True
  283. }
  284. result = await skill_seeker_server.scrape_docs_tool(args)
  285. call_args = mock_streaming.call_args[0][0]
  286. self.assertIn("--enhance-local", call_args)
  287. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  288. class TestPackageSkillTool(unittest.IsolatedAsyncioTestCase):
  289. """Test package_skill tool"""
  290. async def asyncSetUp(self):
  291. """Set up test environment"""
  292. self.temp_dir = tempfile.mkdtemp()
  293. self.original_cwd = os.getcwd()
  294. os.chdir(self.temp_dir)
  295. # Create a mock skill directory
  296. self.skill_dir = Path("output/test-skill")
  297. self.skill_dir.mkdir(parents=True)
  298. (self.skill_dir / "SKILL.md").write_text("# Test Skill")
  299. (self.skill_dir / "references").mkdir()
  300. (self.skill_dir / "references/index.md").write_text("# Index")
  301. async def asyncTearDown(self):
  302. """Clean up test environment"""
  303. os.chdir(self.original_cwd)
  304. shutil.rmtree(self.temp_dir, ignore_errors=True)
  305. @patch('subprocess.run')
  306. async def test_package_skill_success(self, mock_run):
  307. """Test successful skill packaging"""
  308. mock_result = MagicMock()
  309. mock_result.returncode = 0
  310. mock_result.stdout = "Package created: test-skill.zip"
  311. mock_run.return_value = mock_result
  312. args = {
  313. "skill_dir": str(self.skill_dir)
  314. }
  315. result = await skill_seeker_server.package_skill_tool(args)
  316. self.assertIsInstance(result, list)
  317. self.assertIn("test-skill", result[0].text)
  318. @patch('subprocess.run')
  319. async def test_package_skill_error(self, mock_run):
  320. """Test error handling in skill packaging"""
  321. mock_result = MagicMock()
  322. mock_result.returncode = 1
  323. mock_result.stderr = "Directory not found"
  324. mock_run.return_value = mock_result
  325. args = {
  326. "skill_dir": "nonexistent-dir"
  327. }
  328. result = await skill_seeker_server.package_skill_tool(args)
  329. self.assertIn("Error", result[0].text)
  330. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  331. class TestListConfigsTool(unittest.IsolatedAsyncioTestCase):
  332. """Test list_configs tool"""
  333. async def asyncSetUp(self):
  334. """Set up test environment"""
  335. self.temp_dir = tempfile.mkdtemp()
  336. self.original_cwd = os.getcwd()
  337. os.chdir(self.temp_dir)
  338. # Create test configs
  339. os.makedirs("configs", exist_ok=True)
  340. configs = [
  341. {
  342. "name": "test1",
  343. "description": "Test 1 skill",
  344. "base_url": "https://test1.dev/"
  345. },
  346. {
  347. "name": "test2",
  348. "description": "Test 2 skill",
  349. "base_url": "https://test2.dev/"
  350. }
  351. ]
  352. for config in configs:
  353. path = Path(f"configs/{config['name']}.json")
  354. with open(path, 'w') as f:
  355. json.dump(config, f)
  356. async def asyncTearDown(self):
  357. """Clean up test environment"""
  358. os.chdir(self.original_cwd)
  359. shutil.rmtree(self.temp_dir, ignore_errors=True)
  360. async def test_list_configs_success(self):
  361. """Test listing all configs"""
  362. result = await skill_seeker_server.list_configs_tool({})
  363. self.assertIsInstance(result, list)
  364. self.assertIsInstance(result[0], TextContent)
  365. self.assertIn("test1", result[0].text)
  366. self.assertIn("test2", result[0].text)
  367. self.assertIn("https://test1.dev/", result[0].text)
  368. self.assertIn("https://test2.dev/", result[0].text)
  369. async def test_list_configs_empty(self):
  370. """Test listing configs when directory is empty"""
  371. # Remove all configs
  372. for config_file in Path("configs").glob("*.json"):
  373. config_file.unlink()
  374. result = await skill_seeker_server.list_configs_tool({})
  375. self.assertIn("No config files found", result[0].text)
  376. async def test_list_configs_no_directory(self):
  377. """Test listing configs when directory doesn't exist"""
  378. # Remove configs directory
  379. shutil.rmtree("configs")
  380. result = await skill_seeker_server.list_configs_tool({})
  381. self.assertIn("No configs directory", result[0].text)
  382. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  383. class TestValidateConfigTool(unittest.IsolatedAsyncioTestCase):
  384. """Test validate_config tool"""
  385. async def asyncSetUp(self):
  386. """Set up test environment"""
  387. self.temp_dir = tempfile.mkdtemp()
  388. self.original_cwd = os.getcwd()
  389. os.chdir(self.temp_dir)
  390. os.makedirs("configs", exist_ok=True)
  391. async def asyncTearDown(self):
  392. """Clean up test environment"""
  393. os.chdir(self.original_cwd)
  394. shutil.rmtree(self.temp_dir, ignore_errors=True)
  395. async def test_validate_valid_config(self):
  396. """Test validating a valid config"""
  397. # Create valid config
  398. config_path = Path("configs/valid.json")
  399. valid_config = {
  400. "name": "valid-test",
  401. "base_url": "https://example.com/",
  402. "selectors": {
  403. "main_content": "article",
  404. "title": "h1",
  405. "code_blocks": "pre"
  406. },
  407. "rate_limit": 0.5,
  408. "max_pages": 100
  409. }
  410. with open(config_path, 'w') as f:
  411. json.dump(valid_config, f)
  412. args = {
  413. "config_path": str(config_path)
  414. }
  415. result = await skill_seeker_server.validate_config_tool(args)
  416. self.assertIsInstance(result, list)
  417. self.assertIn("✅", result[0].text)
  418. self.assertIn("valid", result[0].text.lower())
  419. async def test_validate_invalid_config(self):
  420. """Test validating an invalid config"""
  421. # Create invalid config (missing required fields)
  422. config_path = Path("configs/invalid.json")
  423. invalid_config = {
  424. "description": "Missing name field",
  425. "sources": [
  426. {"type": "invalid_type", "url": "https://example.com"} # Invalid source type
  427. ]
  428. }
  429. with open(config_path, 'w') as f:
  430. json.dump(invalid_config, f)
  431. args = {
  432. "config_path": str(config_path)
  433. }
  434. result = await skill_seeker_server.validate_config_tool(args)
  435. # Should show error for invalid source type
  436. self.assertIn("❌", result[0].text)
  437. async def test_validate_nonexistent_config(self):
  438. """Test validating a nonexistent config"""
  439. args = {
  440. "config_path": "configs/nonexistent.json"
  441. }
  442. result = await skill_seeker_server.validate_config_tool(args)
  443. self.assertIn("Error", result[0].text)
  444. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  445. class TestCallToolRouter(unittest.IsolatedAsyncioTestCase):
  446. """Test call_tool routing"""
  447. async def test_call_tool_unknown(self):
  448. """Test calling an unknown tool"""
  449. result = await skill_seeker_server.call_tool("unknown_tool", {})
  450. self.assertIsInstance(result, list)
  451. self.assertIn("Unknown tool", result[0].text)
  452. async def test_call_tool_exception_handling(self):
  453. """Test that exceptions are caught and returned as errors"""
  454. # Call with invalid arguments that should cause an exception
  455. result = await skill_seeker_server.call_tool("generate_config", {})
  456. self.assertIsInstance(result, list)
  457. self.assertIn("Error", result[0].text)
  458. @unittest.skipUnless(MCP_AVAILABLE, "MCP package not installed")
  459. class TestMCPServerIntegration(unittest.IsolatedAsyncioTestCase):
  460. """Integration tests for MCP server"""
  461. async def test_full_workflow_simulation(self):
  462. """Test complete workflow: generate config -> validate -> estimate"""
  463. temp_dir = tempfile.mkdtemp()
  464. original_cwd = os.getcwd()
  465. os.chdir(temp_dir)
  466. try:
  467. # Step 1: Generate config using skill_seeker_server
  468. generate_args = {
  469. "name": "workflow-test",
  470. "url": "https://workflow-test.dev/",
  471. "description": "Workflow test skill"
  472. }
  473. result1 = await skill_seeker_server.generate_config_tool(generate_args)
  474. self.assertIn("✅", result1[0].text)
  475. # Step 2: Validate config
  476. validate_args = {
  477. "config_path": "configs/workflow-test.json"
  478. }
  479. result2 = await skill_seeker_server.validate_config_tool(validate_args)
  480. self.assertIn("✅", result2[0].text)
  481. # Step 3: List configs
  482. result3 = await skill_seeker_server.list_configs_tool({})
  483. self.assertIn("workflow-test", result3[0].text)
  484. finally:
  485. os.chdir(original_cwd)
  486. shutil.rmtree(temp_dir, ignore_errors=True)
  487. if __name__ == '__main__':
  488. unittest.main()