|
| 1 | +# function/func.py |
| 2 | + |
| 3 | +# Function as an MCP Server implementation |
| 4 | +import logging |
| 5 | + |
| 6 | +from mcp.server.fastmcp import FastMCP |
| 7 | +import asyncio |
| 8 | + |
| 9 | +def new(): |
| 10 | + """ New is the only method that must be implemented by a Function. |
| 11 | + The instance returned can be of any name. |
| 12 | + """ |
| 13 | + return Function() |
| 14 | + |
| 15 | +class MCPServer: |
| 16 | + """MCP server that exposes tools, resources, and prompts via the MCP protocol.""" |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + # Create FastMCP instance with stateless HTTP for Kubernetes deployment |
| 20 | + self.mcp = FastMCP("Function MCP Server", stateless_http=True) |
| 21 | + |
| 22 | + self._register_tools() |
| 23 | + #self._register_resources() |
| 24 | + #self._register_prompts() |
| 25 | + |
| 26 | + # Get the ASGI app from FastMCP |
| 27 | + self._app = self.mcp.streamable_http_app() |
| 28 | + |
| 29 | + def _register_tools(self): |
| 30 | + """Register MCP tools.""" |
| 31 | + @self.mcp.tool() |
| 32 | + def hello_tool(name: str) -> str: |
| 33 | + """Say hello to someone.""" |
| 34 | + return f"Hey there {name}!" |
| 35 | + |
| 36 | + @self.mcp.tool() |
| 37 | + def add_numbers(a: int, b: int) -> int: |
| 38 | + """Add two numbers together.""" |
| 39 | + return a + b |
| 40 | + |
| 41 | +## Other MCP objects include resources and prompts. |
| 42 | +## Add them here to be registered in the same fashion as tools above. |
| 43 | +# def _register_resources(self): |
| 44 | +# """Register MCP resources.""" |
| 45 | +# @self.mcp.resource("echo://{message}") |
| 46 | +# def echo_resource(message: str) -> str: |
| 47 | +# """Echo the message as a resource.""" |
| 48 | +# return f"Echo: {message}" |
| 49 | +# |
| 50 | +# def _register_prompts(self): |
| 51 | +# """Register MCP prompts.""" |
| 52 | +# @self.mcp.prompt() |
| 53 | +# def greeting_prompt(name: str = "Big Dave"): |
| 54 | +# """Generate a greeting prompt.""" |
| 55 | +# return [ |
| 56 | +# { |
| 57 | +# "role": "user", |
| 58 | +# "content": f"Please write a friendly greeting for {name}" |
| 59 | +# } |
| 60 | +# ] |
| 61 | + |
| 62 | + async def handle(self, scope, receive, send): |
| 63 | + """Handle ASGI requests - both lifespan and HTTP.""" |
| 64 | + await self._app(scope, receive, send) |
| 65 | + |
| 66 | +class Function: |
| 67 | + def __init__(self): |
| 68 | + """ The init method is an optional method where initialization can be |
| 69 | + performed. See the start method for a startup hook which includes |
| 70 | + configuration. |
| 71 | + """ |
| 72 | + self.mcp_server = MCPServer() |
| 73 | + self._mcp_initialized = False |
| 74 | + |
| 75 | + async def handle(self, scope, receive, send): |
| 76 | + """ |
| 77 | + Main entry to your Function. |
| 78 | + This handles all the incoming requests. |
| 79 | + """ |
| 80 | + |
| 81 | + # Initialize MCP server on first request |
| 82 | + if not self._mcp_initialized: |
| 83 | + await self._initialize_mcp() |
| 84 | + |
| 85 | + # Route MCP requests |
| 86 | + if scope['path'].startswith('/mcp'): |
| 87 | + await self.mcp_server.handle(scope, receive, send) |
| 88 | + return |
| 89 | + |
| 90 | + # Default response for non-MCP requests |
| 91 | + await self._send_default_response(send) |
| 92 | + |
| 93 | + async def _initialize_mcp(self): |
| 94 | + """Initialize the MCP server by sending lifespan startup event.""" |
| 95 | + lifespan_scope = {'type': 'lifespan', 'asgi': {'version': '3.0'}} |
| 96 | + startup_sent = False |
| 97 | + |
| 98 | + async def lifespan_receive(): |
| 99 | + nonlocal startup_sent |
| 100 | + if not startup_sent: |
| 101 | + startup_sent = True |
| 102 | + return {'type': 'lifespan.startup'} |
| 103 | + await asyncio.Event().wait() # Wait forever for shutdown |
| 104 | + |
| 105 | + async def lifespan_send(message): |
| 106 | + if message['type'] == 'lifespan.startup.complete': |
| 107 | + self._mcp_initialized = True |
| 108 | + elif message['type'] == 'lifespan.startup.failed': |
| 109 | + logging.error(f"MCP startup failed: {message}") |
| 110 | + |
| 111 | + # Start lifespan in background |
| 112 | + asyncio.create_task(self.mcp_server.handle( |
| 113 | + lifespan_scope, lifespan_receive, lifespan_send |
| 114 | + )) |
| 115 | + |
| 116 | + # Brief wait for startup completion |
| 117 | + await asyncio.sleep(0.1) |
| 118 | + |
| 119 | + async def _send_default_response(self, send): |
| 120 | + """ |
| 121 | + Send default OK response. |
| 122 | + This is for your non MCP requests if desired. |
| 123 | + """ |
| 124 | + await send({ |
| 125 | + 'type': 'http.response.start', |
| 126 | + 'status': 200, |
| 127 | + 'headers': [[b'content-type', b'text/plain']], |
| 128 | + }) |
| 129 | + await send({ |
| 130 | + 'type': 'http.response.body', |
| 131 | + 'body': b'OK', |
| 132 | + }) |
| 133 | + |
| 134 | + def start(self, cfg): |
| 135 | + logging.info("Function starting") |
| 136 | + |
| 137 | + def stop(self): |
| 138 | + logging.info("Function stopping") |
| 139 | + |
| 140 | + def alive(self): |
| 141 | + return True, "Alive" |
| 142 | + |
| 143 | + def ready(self): |
| 144 | + return True, "Ready" |
0 commit comments