|
| 1 | +""" |
| 2 | +An FastMCP server that provides Todo management tools with authentication and authorization. |
| 3 | +
|
| 4 | +This server demonstrates more complex authentication scenarios with different permission scopes: |
| 5 | +- create-todo: Create a new todo (requires 'create:todos' scope) |
| 6 | +- get-todos: List todos (requires 'read:todos' scope for all todos, otherwise only own todos) |
| 7 | +- delete-todo: Delete a todo (requires 'delete:todos' scope for others' todos) |
| 8 | +
|
| 9 | +This server is compatible with OpenID Connect (OIDC) providers and uses the `mcpauth` library |
| 10 | +to handle authorization. Please check https://mcp-auth.dev/docs/tutorials/todo-manager for more |
| 11 | +information on how to use this server. |
| 12 | +""" |
| 13 | + |
| 14 | +import os |
| 15 | +from typing import Any, List, Optional |
| 16 | +from mcp.server.fastmcp import FastMCP |
| 17 | +from starlette.applications import Starlette |
| 18 | +from starlette.routing import Mount |
| 19 | +from starlette.middleware import Middleware |
| 20 | + |
| 21 | +from mcpauth import MCPAuth |
| 22 | +from mcpauth.config import AuthServerType |
| 23 | +from mcpauth.exceptions import ( |
| 24 | + MCPAuthBearerAuthException, |
| 25 | + BearerAuthExceptionCode, |
| 26 | +) |
| 27 | +from mcpauth.types import AuthInfo, ResourceServerConfig, ResourceServerMetadata |
| 28 | +from mcpauth.utils import fetch_server_config |
| 29 | +from .service import TodoService |
| 30 | + |
| 31 | +# Initialize the FastMCP server |
| 32 | +mcp = FastMCP("Todo Manager") |
| 33 | + |
| 34 | +# Initialize the todo service |
| 35 | +todo_service = TodoService() |
| 36 | + |
| 37 | +# Authorization server configuration |
| 38 | +issuer_placeholder = "https://replace-with-your-issuer-url.com" |
| 39 | +auth_issuer = os.getenv("MCP_AUTH_ISSUER", issuer_placeholder) |
| 40 | + |
| 41 | +if auth_issuer == issuer_placeholder: |
| 42 | + raise ValueError( |
| 43 | + "MCP_AUTH_ISSUER environment variable is not set. Please set it to your authorization server's issuer URL." |
| 44 | + ) |
| 45 | + |
| 46 | +auth_server_config = fetch_server_config(auth_issuer, AuthServerType.OIDC) |
| 47 | +mcp_auth = MCPAuth(server=auth_server_config) |
| 48 | + |
| 49 | +def assert_user_id(auth_info: Optional[AuthInfo]) -> str: |
| 50 | + """Assert that auth_info contains a valid user ID and return it.""" |
| 51 | + if not auth_info or not auth_info.subject: |
| 52 | + raise Exception("Invalid auth info") |
| 53 | + return auth_info.subject |
| 54 | + |
| 55 | + |
| 56 | +def has_required_scopes(user_scopes: List[str], required_scopes: List[str]) -> bool: |
| 57 | + """Check if user has all required scopes.""" |
| 58 | + return all(scope in user_scopes for scope in required_scopes) |
| 59 | + |
| 60 | + |
| 61 | +@mcp.tool() |
| 62 | +def create_todo(content: str) -> dict[str, Any]: |
| 63 | + """Create a new todo. Requires 'create:todos' scope.""" |
| 64 | + auth_info = mcp_auth.auth_info |
| 65 | + user_id = assert_user_id(auth_info) |
| 66 | + |
| 67 | + # Only users with 'create:todos' scope can create todos |
| 68 | + user_scopes = auth_info.scopes if auth_info else [] |
| 69 | + if not has_required_scopes(user_scopes, ["create:todos"]): |
| 70 | + raise MCPAuthBearerAuthException(BearerAuthExceptionCode.MISSING_REQUIRED_SCOPES) |
| 71 | + |
| 72 | + created_todo = todo_service.create_todo(content=content, owner_id=user_id) |
| 73 | + return created_todo |
| 74 | + |
| 75 | + |
| 76 | +@mcp.tool() |
| 77 | +def get_todos() -> dict[str, Any]: |
| 78 | + """ |
| 79 | + List todos. Users with 'read:todos' scope can see all todos, |
| 80 | + otherwise they can only see their own todos. |
| 81 | + """ |
| 82 | + auth_info = mcp_auth.auth_info |
| 83 | + user_id = assert_user_id(auth_info) |
| 84 | + |
| 85 | + # If user has 'read:todos' scope, they can access all todos |
| 86 | + # If user doesn't have 'read:todos' scope, they can only access their own todos |
| 87 | + user_scopes = auth_info.scopes if auth_info else [] |
| 88 | + todo_owner_id = None if has_required_scopes(user_scopes, ["read:todos"]) else user_id |
| 89 | + |
| 90 | + todos = todo_service.get_all_todos(todo_owner_id) |
| 91 | + return {"todos": todos} |
| 92 | + |
| 93 | + |
| 94 | +@mcp.tool() |
| 95 | +def delete_todo(id: str) -> dict[str, Any]: |
| 96 | + """ |
| 97 | + Delete a todo by id. Users can delete their own todos. |
| 98 | + Users with 'delete:todos' scope can delete any todo. |
| 99 | + """ |
| 100 | + auth_info = mcp_auth.auth_info |
| 101 | + user_id = assert_user_id(auth_info) |
| 102 | + |
| 103 | + todo = todo_service.get_todo_by_id(id) |
| 104 | + |
| 105 | + if not todo: |
| 106 | + return {"error": "Failed to delete todo"} |
| 107 | + |
| 108 | + # Users can only delete their own todos |
| 109 | + # Users with 'delete:todos' scope can delete any todo |
| 110 | + user_scopes = auth_info.scopes if auth_info else [] |
| 111 | + if todo.owner_id != user_id and not has_required_scopes(user_scopes, ["delete:todos"]): |
| 112 | + return {"error": "Failed to delete todo"} |
| 113 | + |
| 114 | + deleted_todo = todo_service.delete_todo(id) |
| 115 | + |
| 116 | + if deleted_todo: |
| 117 | + return { |
| 118 | + "message": f"Todo {id} deleted", |
| 119 | + "details": deleted_todo |
| 120 | + } |
| 121 | + else: |
| 122 | + return {"error": "Failed to delete todo"} |
| 123 | + |
| 124 | +# Create the middleware and app |
| 125 | +bearer_auth = Middleware(mcp_auth.bearer_auth_middleware('jwt')) |
| 126 | +app = Starlette( |
| 127 | + routes=[ |
| 128 | + # Add the metadata route (`/.well-known/oauth-authorization-server`) |
| 129 | + mcp_auth.metadata_route(), # pyright: ignore[reportDeprecated] |
| 130 | + Mount("/", app=mcp.sse_app(), middleware=[bearer_auth]), |
| 131 | + ], |
| 132 | +) |
0 commit comments