|
| 1 | +# Copyright Materialize, Inc. and contributors. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License in the LICENSE file at the |
| 6 | +# root of this repository, or online at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +""" |
| 16 | +Materialize MCP Server |
| 17 | +
|
| 18 | +A server that exposes Materialize indexes as "tools" over the Model Context |
| 19 | +Protocol (MCP). Each Materialize index that the connected role is allowed to |
| 20 | +`SELECT` from (and whose cluster it can `USAGE`) is surfaced as a tool whose |
| 21 | +inputs correspond to the indexed columns and whose output is the remaining |
| 22 | +columns of the underlying view. |
| 23 | +
|
| 24 | +The server supports two transports: |
| 25 | +
|
| 26 | +* stdio – lines of JSON over stdin/stdout (handy for local CLIs) |
| 27 | +* sse – server‑sent events suitable for web browsers |
| 28 | +
|
| 29 | +--------------- |
| 30 | +
|
| 31 | +1. ``list_tools`` executes a catalog query to derive the list of exposable |
| 32 | + indexes; the result is translated into MCP ``Tool`` objects. |
| 33 | +2. ``call_tool`` validates the requested tool, switches the session to the |
| 34 | + appropriate cluster, executes a parameterised ``SELECT`` against the |
| 35 | + indexed view, and returns the first matching row (minus any columns whose |
| 36 | + values were supplied as inputs). |
| 37 | +""" |
| 38 | + |
| 39 | +import asyncio |
| 40 | +import logging |
| 41 | +from collections.abc import AsyncIterator, Sequence |
| 42 | +from contextlib import asynccontextmanager |
| 43 | +from typing import Any |
| 44 | + |
| 45 | +import uvicorn |
| 46 | +from mcp import stdio_server |
| 47 | +from mcp.server import NotificationOptions, Server |
| 48 | +from mcp.server.sse import SseServerTransport |
| 49 | +from mcp.types import EmbeddedResource, ImageContent, TextContent, Tool |
| 50 | +from psycopg.rows import dict_row |
| 51 | +from psycopg_pool import AsyncConnectionPool |
| 52 | + |
| 53 | +from .config import load_config |
| 54 | +from .mz_client import MzClient |
| 55 | + |
| 56 | +logger = logging.getLogger("mz_mcp_server") |
| 57 | +logging.basicConfig( |
| 58 | + level=logging.INFO, |
| 59 | + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", |
| 60 | +) |
| 61 | + |
| 62 | + |
| 63 | +def get_lifespan(cfg): |
| 64 | + @asynccontextmanager |
| 65 | + async def lifespan(server) -> AsyncIterator[MzClient]: |
| 66 | + logger.info( |
| 67 | + "Initializing connection pool with min_size=%s, max_size=%s", |
| 68 | + cfg.pool_min_size, |
| 69 | + cfg.pool_max_size, |
| 70 | + ) |
| 71 | + |
| 72 | + async def configure(conn): |
| 73 | + await conn.set_autocommit(True) |
| 74 | + logger.debug("Configured new database connection") |
| 75 | + |
| 76 | + try: |
| 77 | + async with AsyncConnectionPool( |
| 78 | + conninfo=cfg.dsn, |
| 79 | + min_size=cfg.pool_min_size, |
| 80 | + max_size=cfg.pool_max_size, |
| 81 | + kwargs={"application_name": "mcp_materialize"}, |
| 82 | + configure=configure, |
| 83 | + ) as pool: |
| 84 | + try: |
| 85 | + logger.debug("Testing database connection...") |
| 86 | + async with pool.connection() as conn: |
| 87 | + await conn.set_autocommit(True) |
| 88 | + async with conn.cursor(row_factory=dict_row) as cur: |
| 89 | + await cur.execute( |
| 90 | + "SELECT" |
| 91 | + " mz_environment_id() AS env," |
| 92 | + " current_role AS role;" |
| 93 | + ) |
| 94 | + meta = await cur.fetchone() |
| 95 | + logger.info( |
| 96 | + "Connected to Materialize environment %s as user %s", |
| 97 | + meta["env"], |
| 98 | + meta["role"], |
| 99 | + ) |
| 100 | + logger.debug("Connection pool initialized successfully") |
| 101 | + async with MzClient(pool=pool) as client: |
| 102 | + yield client |
| 103 | + except Exception as e: |
| 104 | + logger.error(f"Failed to initialize connection pool: {str(e)}") |
| 105 | + raise |
| 106 | + finally: |
| 107 | + logger.info("Closing connection pool...") |
| 108 | + await pool.close() |
| 109 | + except Exception as e: |
| 110 | + logger.error(f"Failed to create connection pool: {str(e)}") |
| 111 | + raise |
| 112 | + |
| 113 | + return lifespan |
| 114 | + |
| 115 | + |
| 116 | +async def run(): |
| 117 | + cfg = load_config() |
| 118 | + server = Server("mcp_materialize", lifespan=get_lifespan(cfg)) |
| 119 | + |
| 120 | + @server.list_tools() |
| 121 | + async def list_tools() -> list[Tool]: |
| 122 | + logger.debug("Listing available tools...") |
| 123 | + tools = await server.request_context.lifespan_context.list_tools() |
| 124 | + return tools |
| 125 | + |
| 126 | + @server.call_tool() |
| 127 | + async def call_tool( |
| 128 | + name: str, arguments: dict[str, Any] |
| 129 | + ) -> Sequence[TextContent | ImageContent | EmbeddedResource]: |
| 130 | + logger.debug(f"Calling tool '{name}' with arguments: {arguments}") |
| 131 | + try: |
| 132 | + result = await server.request_context.lifespan_context.call_tool( |
| 133 | + name, arguments |
| 134 | + ) |
| 135 | + logger.debug(f"Tool '{name}' executed successfully") |
| 136 | + return result |
| 137 | + except Exception as e: |
| 138 | + logger.error(f"Error executing tool '{name}': {str(e)}") |
| 139 | + await server.request_context.session.send_tool_list_changed() |
| 140 | + raise |
| 141 | + |
| 142 | + options = server.create_initialization_options( |
| 143 | + notification_options=NotificationOptions(tools_changed=True) |
| 144 | + ) |
| 145 | + match cfg.transport: |
| 146 | + case "stdio": |
| 147 | + logger.info("Starting server in stdio mode...") |
| 148 | + async with stdio_server() as (read_stream, write_stream): |
| 149 | + await server.run( |
| 150 | + read_stream, |
| 151 | + write_stream, |
| 152 | + options, |
| 153 | + ) |
| 154 | + case "sse": |
| 155 | + logger.info(f"Starting SSE server on {cfg.host}:{cfg.port}...") |
| 156 | + from starlette.applications import Starlette |
| 157 | + from starlette.routing import Mount, Route |
| 158 | + |
| 159 | + sse = SseServerTransport("/messages/") |
| 160 | + |
| 161 | + async def handle_sse(request): |
| 162 | + logger.debug( |
| 163 | + "New SSE connection from %s", |
| 164 | + request.client.host if request.client else "unknown", |
| 165 | + ) |
| 166 | + try: |
| 167 | + async with sse.connect_sse( |
| 168 | + request.scope, request.receive, request._send |
| 169 | + ) as streams: |
| 170 | + await server.run( |
| 171 | + streams[0], |
| 172 | + streams[1], |
| 173 | + options, |
| 174 | + ) |
| 175 | + except Exception as e: |
| 176 | + logger.error(f"Error handling SSE connection: {str(e)}") |
| 177 | + raise |
| 178 | + |
| 179 | + starlette_app = Starlette( |
| 180 | + routes=[ |
| 181 | + Route("/sse", endpoint=handle_sse), |
| 182 | + Mount("/messages/", app=sse.handle_post_message), |
| 183 | + ], |
| 184 | + ) |
| 185 | + |
| 186 | + config = uvicorn.Config( |
| 187 | + starlette_app, |
| 188 | + host=cfg.host, |
| 189 | + port=cfg.port, |
| 190 | + log_level=cfg.log_level.upper(), |
| 191 | + ) |
| 192 | + server = uvicorn.Server(config) |
| 193 | + await server.serve() |
| 194 | + case t: |
| 195 | + raise ValueError(f"Unknown transport: {t}") |
| 196 | + |
| 197 | + |
| 198 | +def main(): |
| 199 | + """Synchronous wrapper for the async main function.""" |
| 200 | + try: |
| 201 | + logger.info("Starting Materialize MCP Server...") |
| 202 | + asyncio.run(run()) |
| 203 | + except KeyboardInterrupt: |
| 204 | + logger.info("Shutting down …") |
| 205 | + |
| 206 | + |
| 207 | +if __name__ == "__main__": |
| 208 | + main() |
0 commit comments