"""MCP Server for the Context Course project. Demonstrates Unit 2 (Model Context Protocol): building an MCP server with tools, resources, and prompts using the official Python SDK. Run with: python mcp-server/server.py Or via stdio transport for any MCP-compatible agent. """ import json from pathlib import Path from mcp.server.fastmcp import FastMCP mcp = FastMCP("context-course-tools") # --------------------------------------------------------------------------- # Tools # --------------------------------------------------------------------------- @mcp.tool() def list_skills(directory: str = "skills") -> str: """List all SKILL.md files found under the given directory.""" root = Path(directory) if not root.exists(): return f"Directory '{directory}' not found." skills = sorted(root.rglob("SKILL.md")) if not skills: return "No SKILL.md files found." return "\n".join(str(p) for p in skills) @mcp.tool() def read_skill(path: str) -> str: """Read the contents of a SKILL.md file.""" p = Path(path) if not p.exists(): return f"File '{path}' not found." return p.read_text(encoding="utf-8") @mcp.tool() def search_skills(query: str, directory: str = "skills") -> str: """Search SKILL.md files for a keyword and return matching snippets.""" root = Path(directory) if not root.exists(): return f"Directory '{directory}' not found." results = [] for p in root.rglob("SKILL.md"): text = p.read_text(encoding="utf-8") if query.lower() in text.lower(): # Find the line containing the query for line in text.splitlines(): if query.lower() in line.lower(): results.append(f"{p}: {line.strip()}") break if not results: return f"No skills matching '{query}'." return "\n".join(results) @mcp.tool() def echo(message: str) -> str: """Echo a message back. Useful for testing MCP connectivity.""" return f"Echo: {message}" # --------------------------------------------------------------------------- # Resources # --------------------------------------------------------------------------- @mcp.resource("skills://list") def skills_resource() -> str: """A resource listing all available skills.""" return list_skills("skills") @mcp.resource("config://project") def project_config() -> str: """Project configuration and metadata.""" config = { "name": "context-course-project", "version": "1.0.0", "units_covered": [1, 2, 3, 4, 5], "skills_count": len(list(Path("skills").rglob("SKILL.md"))), } return json.dumps(config, indent=2) # --------------------------------------------------------------------------- # Prompts # --------------------------------------------------------------------------- @mcp.prompt() def review_code(code: str) -> str: """Generate a code review prompt for the given code snippet.""" return ( "Review the following code for correctness, readability, security, " "performance, and style. Provide a summary, issues list, suggestions, " "and a verdict (Approve/Request Changes/Comment).\n\n" f"```\n{code}\n```" ) if __name__ == "__main__": mcp.run()