### Project Setup and Dependency Installation (Bash/PowerShell) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This snippet covers creating a project directory, initializing an npm project, installing core SDK and utility dependencies, and creating source files. It is provided for both MacOS/Linux (Bash) and Windows (PowerShell). ```bash # Create a new directory for our project mkdir weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files mkdir src touch src/index.ts ``` ```powershell # Create a new directory for our project md weather cd weather # Initialize a new npm project npm init -y # Install dependencies npm install @modelcontextprotocol/sdk zod npm install -D @types/node typescript # Create our files md src new-item src\index.ts ``` -------------------------------- ### Running Python MCP Servers Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Examples of running Python-based MCP servers. It shows two methods: using uvx for streamlined execution and using pip for traditional package installation and module execution. This allows flexibility based on user preference and environment setup. ```bash # Using uvx uvx mcp-server-git # Using pip pip install mcp-server-git python -m mcp_server_git ``` -------------------------------- ### Initialize MCP Client Environment Setup (Bash) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This snippet outlines the bash commands to initialize a new Python project using 'uv', create a virtual environment, activate it, and install necessary packages for an MCP client. It also includes steps for removing boilerplate and creating the main client file. ```bash # Create project directory uv init mcp-client cd mcp-client # Create virtual environment uv venv # Activate virtual environment # On Windows: .venv\Scripts\activate # On Unix or MacOS: source .venv/bin/activate # Install required packages uv add mcp anthropic python-dotenv # Remove boilerplate files rm hello.py # Create our main file touch client.py ``` -------------------------------- ### Running TypeScript MCP Servers Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This command demonstrates how to execute a TypeScript-based MCP server directly using npx. It's a straightforward way to start a server without local installation. ```bash npx -y @modelcontextprotocol/server-memory ``` -------------------------------- ### Install NPM Globally Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Command to install NPM globally on a system. This is a prerequisite for using the `npx` command reliably, especially when troubleshooting server loading issues. ```bash npm install -g npm ``` -------------------------------- ### JSON Example Request for Sampling Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt An example of a JSON request to a client for sampling. This demonstrates how to structure the request, including the messages, system prompt, context inclusion method, and maximum token limit. ```json { "method": "sampling/createMessage", "params": { "messages": [ { "role": "user", "content": { "type": "text", "text": "What files are in the current directory?" } } ], "systemPrompt": "You are a helpful file system assistant.", "includeContext": "thisServer", "maxTokens": 100 } } ``` -------------------------------- ### Global Supabase MCP .env Configuration Example Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/README.md Example content for the global .env configuration file used by the Supabase MCP server. This file should contain key-value pairs for various Supabase and TheQuery API settings. ```env QUERY_API_KEY=your-api-key SUPABASE_PROJECT_REF=your-project-ref SUPABASE_DB_PASSWORD=your-db-password SUPABASE_REGION=us-east-1 SUPABASE_ACCESS_TOKEN=your-access-token SUPABASE_SERVICE_ROLE_KEY=your-service-role-key ``` -------------------------------- ### Set Up Python Project Environment with uv Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Initializes a new Python project named 'weather', creates and activates a virtual environment using `uv`, and installs necessary dependencies like `mcp[cli]` and `httpx`. It also creates the main server file `weather.py`. ```bash # Create a new directory for our project uv init weather cd weather # Create virtual environment and activate it uv venv source .venv/bin/activate # Install dependencies uv add "mcp[cli]" httpx # Create our server file touch weather.py ``` ```powershell # Create a new directory for our project uv init weather cd weather # Create virtual environment and activate it uv venv .venv\Scripts\activate # Install dependencies uv add mcp[cli] httpx # Create our server file new-item weather.py ``` -------------------------------- ### Python MCP Server Resource Implementation Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Provides an example of implementing resource listing and reading in an MCP server using Python. It utilizes decorators for defining resource handlers and asynchronously reads file content. The implementation includes starting the server with standard input/output streams. ```python app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="file:///logs/app.log", name="Application Logs", mimeType="text/plain" ) ] @app.read_resource() async def read_resource(uri: AnyUrl) -> str: if str(uri) == "file:///logs/app.log": log_contents = await read_log_file() return log_contents raise ValueError("Resource not found") # Start server async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Installs the `uv` package manager, a fast Python package installer and virtual environment manager. This is a prerequisite for setting up the Python project environment. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Verify Node.js and npm Installation (Bash) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt These bash commands are used to verify that Node.js and npm have been installed correctly on the system. Running these commands will display the installed versions of Node.js and npm. ```bash node --version npm --version ``` -------------------------------- ### Configure Filesystem MCP Server (Windows) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This JSON configuration snippet sets up the Filesystem MCP Server for Windows. It specifies the command to run (`npx`) and its arguments, including the server package and target directories. Ensure Node.js is installed and the paths are valid Windows-style paths. ```json { "mcpServers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "C:\\Users\\username\\Desktop", "C:\\Users\\username\\Downloads" ] } } } ``` -------------------------------- ### Implement MCP Server in Python Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This Python example demonstrates setting up an MCP server. It defines a server instance, uses a decorator to handle resource listing requests, and runs the server using stdio transport. This implementation is ideal for local inter-process communication. ```python import asyncio import mcp.types as types from mcp.server import Server from mcp.server.stdio import stdio_server app = Server("example-server") @app.list_resources() async def list_resources() -> list[types.Resource]: return [ types.Resource( uri="example://resource", name="Example Resource" ) ] async def main(): async with stdio_server() as streams: await app.run( streams[0], streams[1], app.create_initialization_options() ) if __name__ == "__main__": asyncio.run(main) ``` -------------------------------- ### Install Supabase MCP Server from Source (Editable Mode) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/README.md Guides users on how to install the supabase-mcp-server package in editable mode from its source code, typically for local development purposes. This involves creating a virtual environment and activating it. ```bash uv venv # On Mac source .venv/bin/activate # On Windows .venv\Scripts\activate # Install package in editable mode uv pip install -e . ``` -------------------------------- ### Verify Node.js Installation Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This bash command is used to verify if Node.js is installed on your system. Running `node --version` in the command line or terminal will output the installed Node.js version if it's properly set up. If not, Node.js needs to be downloaded and installed. ```bash node --version ``` -------------------------------- ### Install Supabase MCP Server via pipx Source: https://context7.com/alexander-zuev/supabase-mcp-server/llms.txt Installs the Supabase MCP Server using pipx, the recommended Python package installer. It also shows how to find the executable path on macOS/Linux and Windows. ```bash # Installation via pipx (recommended) pipx install supabase-mcp-server # Find executable path which supabase-mcp-server # macOS/Linux where supabase-mcp-server # Windows ``` -------------------------------- ### Configure Filesystem MCP Server (macOS/Linux) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This JSON configuration snippet sets up the Filesystem MCP Server for macOS and Linux. It specifies the command to run (`npx`) and its arguments, including the server package and target directories. Ensure Node.js is installed and the paths are valid. ```json { "mcpServers": { "filesystem": { "command": "npx", "args": [ "-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Desktop", "/Users/username/Downloads" ] } } } ``` -------------------------------- ### Install Supabase MCP Server using pipx or uv Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/README.md Instructions for installing the supabase-mcp-server package using either the pipx or uv package managers. pipx is recommended for creating isolated environments. ```bash # if pipx is installed (recommended) pipx install supabase-mcp-server # if uv is installed uv pip install supabase-mcp-server ``` -------------------------------- ### Inspect NPM Package Server (Bash) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Launches an MCP server from an NPM package using the MCP Inspector. This is a common way to start server packages for testing and debugging. It requires the package name and any necessary arguments for the server. ```bash npx -y @modelcontextprotocol/inspector npx # For example npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb ``` -------------------------------- ### Configure Environment Variables for Brave Search Server Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Example JSON configuration for the Brave Search server, demonstrating how to set environment variables like APPDATA and BRAVE_API_KEY. This is used when the server fails to load due to path expansion issues on Windows. ```json { "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "APPDATA": "C:\\Users\\user\\AppData\\Roaming\\", "BRAVE_API_KEY": "..." } } } ``` -------------------------------- ### Example Transport with Error Handling (Python) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Illustrates a Python example transport using `anyio` that incorporates robust error handling. It sets up task groups for message handling, uses streams for communication, and includes try-except blocks to catch and log various exceptions that may occur during transport initialization or operation. ```python @contextmanager async def example_transport(scope: Scope, receive: Receive, send: Send): try: # Create streams for bidirectional communication read_stream_writer, read_stream = anyio.create_memory_object_stream(0) write_stream, write_stream_reader = anyio.create_memory_object_stream(0) async def message_handler(): try: async with read_stream_writer: # Message handling logic pass except Exception as exc: logger.error(f"Failed to handle message: {exc}") raise exc async with anyio.create_task_group() as tg: tg.start_soon(message_handler) try: # Yield streams for communication yield read_stream, write_stream except Exception as exc: logger.error(f"Transport error: {exc}") raise exc finally: tg.cancel_scope.cancel() await write_stream.aclose() await read_stream.aclose() except Exception as exc: logger.error(f"Failed to initialize transport: {exc}") raise exc ``` -------------------------------- ### MCP Client Root Exposure Example Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates how a typical MCP client might expose a list of 'roots'. Roots specify relevant resources and locations for the server, aiding in organization and guidance. This JSON structure outlines URIs and names for different resources. ```json { "roots": [ { "uri": "file:///home/user/projects/frontend", "name": "Frontend Repository" }, { "uri": "https://api.example.com/v1", "name": "API Endpoint" } ] } ``` -------------------------------- ### Implement MCP Server in TypeScript Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This snippet shows a basic implementation of an MCP server in TypeScript. It initializes a server instance, sets up a request handler for listing resources, and connects to a stdio transport. This example is suitable for local communication. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // Handle requests server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "example://resource", name: "Example Resource" } ] }; }); // Connect transport const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Implement MCP Server Prompts in Python Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This Python code showcases how to establish an MCP server and implement prompt features. It defines prompts, sets up decorators for listing and retrieving prompts, and dynamically generates messages based on user input. This example utilizes the mcp library. ```python from mcp.server import Server import mcp.types as types # Define available prompts PROMPTS = { "git-commit": types.Prompt( name="git-commit", description="Generate a Git commit message", arguments=[ types.PromptArgument( name="changes", description="Git diff or description of changes", required=True ) ], ), "explain-code": types.Prompt( name="explain-code", description="Explain how code works", arguments=[ types.PromptArgument( name="code", description="Code to explain", required=True ), types.PromptArgument( name="language", description="Programming language", required=False ) ], ) } # Initialize server app = Server("example-prompts-server") @app.list_prompts() async def list_prompts() -> list[types.Prompt]: return list(PROMPTS.values()) @app.get_prompt() async def get_prompt( name: str, arguments: dict[str, str] | None = None ) -> types.GetPromptResult: if name not in PROMPTS: raise ValueError(f"Prompt not found: {name}") if name == "git-commit": changes = arguments.get("changes") if arguments else "" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", text=f"Generate a concise but descriptive commit message " f"for these changes:\n\n{changes}" ) ) ] ) if name == "explain-code": code = arguments.get("code") if arguments else "" language = arguments.get("language", "Unknown") if arguments else "Unknown" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent( type="text", ``` -------------------------------- ### Asynchronous MCP Client API Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Illustrates the asynchronous API for the MCP Client using reactive streams (Mono). This example shows client creation with custom configurations, including request timeouts and capabilities. It also demonstrates chaining asynchronous operations for initializing the connection, listing tools, calling tools, managing resources, and interacting with prompts, along with root management and graceful client closure. ```java McpAsyncClient client = McpClient.async(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // Enable roots capability .sampling() // Enable sampling capability .build()) .sampling(request -> Mono.just(new CreateMessageResult(response))) .toolsChangeConsumer(tools -> Mono.fromRunnable(() -> { logger.info("Tools updated: {}", tools); })) .resourcesChangeConsumer(resources -> Mono.fromRunnable(() -> { logger.info("Resources updated: {}", resources); })) .promptsChangeConsumer(prompts -> Mono.fromRunnable(() -> { logger.info("Prompts updated: {}", prompts); })) .build(); client.initialize() .flatMap(initResult -> client.listTools()) .flatMap(tools -> { return client.callTool(new CallToolRequest( "calculator", Map.of("operation", "add", "a", 2, "b", 3) )); }) .flatMap(result -> { return client.listResources() .flatMap(resources -> client.readResource(new ReadResourceRequest("resource://uri")) ); }) .flatMap(resource -> { return client.listPrompts() .flatMap(prompts -> client.getPrompt(new GetPromptRequest( "greeting", Map.of("name", "Spring") )) ); }) .flatMap(prompt -> { return client.addRoot(new Root("file:///path", "description")) .then(client.removeRoot("file:///path")); }) .doFinally(signalType -> { client.closeGracefully().subscribe(); }) .subscribe(); ``` -------------------------------- ### Configure Supabase MCP Server in Cursor Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/README.md Instructions for adding the Supabase MCP Server to the Cursor client. This involves specifying the command to run the server, which can vary based on installation method (pipx, uv, or full path). ```bash # can be set to any name name:supabase type: command # if you installed with pipx command: supabase-mcp-server # if you installed with uv command: uv run supabase-mcp-server # if the above doesn't work, use the full path (recommended) command: /full/path/to/supabase-mcp-server # Find with 'which supabase-mcp-server' (macOS/Linux) or 'where supabase-mcp-server' (Windows) ``` -------------------------------- ### Running MCP Client with Server Path (Bash) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This snippet demonstrates how to execute the MCP client with a specified server script path. It shows examples for both relative and absolute paths, including Windows-specific path formats. Ensure the server file has the correct extension (.py or .js). ```bash # Relative path uv run client.py ./server/weather.py # Absolute path uv run client.py /Users/username/projects/mcp-server/weather.py # Windows path (either format works) uv run client.py C:/projects/mcp-server/weather.py uv run client.py C:\projects\mcp-server\weather.py ``` -------------------------------- ### Create Global Supabase MCP Config Directory and .env File Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/README.md Commands to create the global configuration directory for Supabase MCP and its .env file. This method is recommended for global configuration and applies across all MCP server instances when using package installations. ```bash # On macOS/Linux mkdir -p ~/.config/supabase-mcp # On Windows (PowerShell) mkdir -Force "$env:APPDATA\supabase-mcp" ``` ```bash # On macOS/Linux nano ~/.config/supabase-mcp/.env # On Windows (PowerShell) notepad "$env:APPDATA\supabase-mcp\.env" ``` -------------------------------- ### Main Entry Point and Execution Flow (Python) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Sets up the main execution logic for the client application. It handles command-line arguments to specify the server script, initializes the `MCPClient`, connects to the server, runs the chat loop, and ensures cleanup of resources. It uses `asyncio.run` to execute the asynchronous main function. Dependencies include `sys` for arguments and `asyncio` for running the event loop. ```python async def main(): if len(sys.argv) < 2: print("Usage: python client.py ") sys.exit(1) client = MCPClient() try: await client.connect_to_server(sys.argv[1]) await client.chat_loop() finally: await client.cleanup() if __name__ == "__main__": import sys asyncio.run(main()) ``` -------------------------------- ### Configure and Initialize MCP Sync Server Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates how to create and initialize a synchronous MCP server with custom server information and capabilities. It also shows how to register tools, resources, and prompts, send logging notifications, and close the server. ```java McpSyncServer syncServer = McpServer.sync(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build(); // Initialize the server syncServer.initialize(); // Register tools, resources, and prompts syncServer.addTool(syncToolRegistration); syncServer.addResource(syncResourceRegistration); syncServer.addPrompt(syncPromptRegistration); // Send logging notifications syncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build()); // Close the server when done syncServer.close(); ``` -------------------------------- ### Configure and Initialize MCP Async Server Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Illustrates the creation and initialization of an asynchronous MCP server using a reactive approach. Includes steps for registering components, sending notifications, and managing server lifecycle within a reactive stream. ```java McpAsyncServer asyncServer = McpServer.async(transport) .serverInfo("my-server", "1.0.0") .capabilities(ServerCapabilities.builder() .resources(true) // Enable resource support .tools(true) // Enable tool support .prompts(true) // Enable prompt support .logging() // Enable logging support .build()) .build(); // Initialize the server asyncServer.initialize() .doOnSuccess(v -> logger.info("Server initialized")) .subscribe(); // Register tools, resources, and prompts asyncServer.addTool(asyncToolRegistration) .doOnSuccess(v -> logger.info("Tool registered")) .subscribe(); asyncServer.addResource(asyncResourceRegistration) .doOnSuccess(v -> logger.info("Resource registered")) .subscribe(); asyncServer.addPrompt(asyncPromptRegistration) .doOnSuccess(v -> logger.info("Prompt registered")) .subscribe(); // Send logging notifications asyncServer.loggingNotification(LoggingMessageNotification.builder() .level(LoggingLevel.INFO) .logger("custom-logger") .data("Server initialized") .build()); // Close the server when done asyncServer.close() .doOnSuccess(v -> logger.info("Server closed")) .subscribe(); ``` -------------------------------- ### Discover Prompts - TypeScript Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates how to discover available prompts via the `prompts/list` endpoint. The response includes prompt names, descriptions, and required arguments. ```typescript // Request { method: "prompts/list" } // Response { prompts: [ { name: "analyze-code", description: "Analyze code for potential improvements", arguments: [ { name: "language", description: "Programming language", required: true } ] } ] } ``` -------------------------------- ### Initialize and Run MCP Server (Python) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt This Python snippet shows how to initialize and run the MCP server using the `mcp.run()` method with 'stdio' transport. This is typically the main entry point for the server application. ```python if __name__ == "__main__": # Initialize and run the server mcp.run(transport='stdio') ``` -------------------------------- ### Install PostgreSQL on MacOS Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/README.md Command to install PostgreSQL version 16 on macOS using the Homebrew package manager. This is a prerequisite if running a local Supabase instance. ```bash brew install postgresql@16 ``` -------------------------------- ### Execute Supabase Management API Request (GET) Source: https://context7.com/alexander-zuev/supabase-mcp-server/llms.txt Executes a GET request to the Supabase Management API, automatically injecting the project reference. This is used for safe operations like listing resources. ```python # Example 1: List all edge functions (GET request - safe) result = await api_manager.execute_request( method="GET", path="/v1/projects/{ref}/functions", path_params={}, # {ref} auto-replaced with project_ref request_params={}, request_body=None ) ``` -------------------------------- ### Initialize FastMCP Server and Define Constants Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Sets up the FastMCP server instance and defines constants for interacting with the National Weather Service API. This includes the base URL and a user agent for requests. ```python from typing import Any import httpx from mcp.server.fastmcp import FastMCP # Initialize FastMCP server mcp = FastMCP("weather") # Constants NWS_API_BASE = "https://api.weather.gov" USER_AGENT = "weather-app/1.0" ``` -------------------------------- ### Implement Basic Tool Server in Python Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Shows how to implement a basic MCP server in Python. This includes defining tools using decorators for listing and calling them, and specifying the input schema for each tool. ```python app = Server("example-server") @app.list_tools() async def list_tools() -> list[types.Tool]: return [ types.Tool( name="calculate_sum", description="Add two numbers together", inputSchema={ "type": "object", "properties": { "a": {"type": "number"}, "b": {"type": "number"} }, "required": ["a", "b"] } ) ] @app.call_tool() async def call_tool( name: str, arguments: dict ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: if name == "calculate_sum": a = arguments["a"] b = arguments["b"] result = a + b return [types.TextContent(type="text", text=str(result))] raise ValueError(f"Tool not found: {name}") ``` -------------------------------- ### Implement Basic Tool Server in TypeScript Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates the implementation of a basic MCP server in TypeScript. It includes setting up the server, defining available tools with their schemas, and handling tool execution requests. ```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } }); // Define available tools server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [{ name: "calculate_sum", description: "Add two numbers together", inputSchema: { type: "object", properties: { a: { type: "number" }, b: { type: "number" } }, required: ["a", "b"] } }] }; }); // Handle tool execution server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "calculate_sum") { const { a, b } = request.params.arguments; return { content: [ { type: "text", text: String(a + b) } ] }; } throw new Error("Tool not found"); }); ``` -------------------------------- ### Get Weather Forecast by Coordinates - TypeScript Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Fetches and formats the weather forecast for a specific geographic location using latitude and longitude. It interacts with the NWS API to get grid point data and then the forecast data. Returns formatted forecast periods or error messages if data retrieval fails. Dependencies: NWS API, 'makeNWSRequest', 'PointsResponse', 'ForecastResponse', 'ForecastPeriod' types. ```typescript server.tool( "get-forecast", "Get weather forecast for a location", { latitude: z.number().min(-90).max(90).describe("Latitude of the location"), longitude: z.number().min(-180).max(180).describe("Longitude of the location"), }, async ({ latitude, longitude }) => { // Get grid point data const pointsUrl = `${NWS_API_BASE}/points/${latitude.toFixed(4)},${longitude.toFixed(4)}`; const pointsData = await makeNWSRequest(pointsUrl); if (!pointsData) { return { content: [ { type: "text", text: `Failed to retrieve grid point data for coordinates: ${latitude}, ${longitude}. This location may not be supported by the NWS API (only US locations are supported).`, }, ], }; } const forecastUrl = pointsData.properties?.forecast; if (!forecastUrl) { return { content: [ { type: "text", text: "Failed to get forecast URL from grid point data", }, ], }; } // Get forecast data const forecastData = await makeNWSRequest(forecastUrl); if (!forecastData) { return { content: [ { type: "text", text: "Failed to retrieve forecast data", }, ], }; } const periods = forecastData.properties?.periods || []; if (periods.length === 0) { return { content: [ { type: "text", text: "No forecast periods available", }, ], }; } // Format forecast periods const formattedForecast = periods.map((period: ForecastPeriod) => [ `${period.name || "Unknown"}: `, `Temperature: ${period.temperature || "Unknown"}°${period.temperatureUnit || "F"}`, `Wind: ${period.windSpeed || "Unknown"} ${period.windDirection || ""}`, `${period.shortForecast || "No forecast available"}`, "---", ].join("\n"), ); const forecastText = `Forecast for ${latitude}, ${longitude}:\n\n${formattedForecast.join("\n")}`; return { content: [ { type: "text", text: forecastText, }, ], }; }, ); ``` -------------------------------- ### Message Types Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Defines the different types of messages used in MCP: Requests, Results, Errors, and Notifications, with TypeScript interface examples. ```APIDOC ## Message Types ### Description Model Context Protocol (MCP) defines four primary message types for communication between parties. ### Message Definitions 1. **Requests** * Messages that expect a response from the receiving party. * **Interface**: `Request` ```typescript interface Request { method: string; params?: { ... }; } ``` 2. **Results** * Successful responses to `Request` messages. * **Interface**: `Result` ```typescript interface Result { [key: string]: unknown; } ``` 3. **Errors** * Messages indicating that a `Request` failed. * **Interface**: `Error` ```typescript interface Error { code: number; message: string; data?: unknown; } ``` 4. **Notifications** * One-way messages that do not expect a response. * **Interface**: `Notification` ```typescript interface Notification { method: string; params?: { ... }; } ``` ``` -------------------------------- ### List and Call Tools (Sync API) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates synchronous API usage for discovering available tools on the server and executing them with specified parameters. Tools are server-side functions accessible via the client. ```java // List available tools and their names var tools = client.listTools(); tools.forEach(tool -> System.out.println(tool.getName())); // Execute a tool with parameters var result = client.callTool("calculator", Map.of( "operation", "add", "a", 1, "b", 2 )); ``` -------------------------------- ### MCP Tool to Get Weather Forecast Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Defines a placeholder for an MCP tool `get_forecast` that is intended to retrieve weather forecasts based on latitude and longitude. The implementation for fetching the forecast grid endpoint is left as a comment. ```python @mcp.tool() async def get_forecast(latitude: float, longitude: float) -> str: """Get weather forecast for a location. Args: latitude: Latitude of the location longitude: Longitude of the location """ # First get the forecast grid endpoint ``` -------------------------------- ### Synchronous MCP Client API Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates the usage of the synchronous API for the MCP Client. This includes creating a client with custom configurations, initializing the connection, and performing operations such as listing tools, calling tools, managing resources, and interacting with prompts. It also shows how to manage roots and gracefully close the client. ```java McpSyncClient client = McpClient.sync(transport) .requestTimeout(Duration.ofSeconds(10)) .capabilities(ClientCapabilities.builder() .roots(true) // Enable roots capability .sampling() // Enable sampling capability .build()) .sampling(request -> new CreateMessageResult(response)) .build(); client.initialize(); ListToolsResult tools = client.listTools(); CallToolResult result = client.callTool( new CallToolRequest("calculator", Map.of("operation", "add", "a", 2, "b", 3)) ); ListResourcesResult resources = client.listResources(); ReadResourceResult resource = client.readResource( new ReadResourceRequest("resource://uri") ); ListPromptsResult prompts = client.listPrompts(); GetPromptResult prompt = client.getPrompt( new GetPromptRequest("greeting", Map.of("name", "Spring")) ); client.addRoot(new Root("file:///path", "description")); client.removeRoot("file:///path"); client.closeGracefully(); ``` -------------------------------- ### List and Call Tools (Async API) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates asynchronous API usage for discovering available tools and executing them. This uses reactive streams (e.g., Project Reactor) for non-blocking operations. ```java // List available tools asynchronously client.listTools() .doOnNext(tools -> tools.forEach(tool -> System.out.println(tool.getName()))) .subscribe(); // Execute a tool asynchronously client.callTool("calculator", Map.of( "operation", "add", "a", 1, "b", 2 )) .subscribe(); ``` -------------------------------- ### Helper Function for NWS API Requests Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Provides a utility function `make_nws_request` to handle asynchronous GET requests to the National Weather Service API. It includes error handling and sets necessary headers like 'User-Agent' and 'Accept'. ```python async def make_nws_request(url: str) -> dict[str, Any] | None: """Make a request to the NWS API with proper error handling.""" headers = { "User-Agent": USER_AGENT, "Accept": "application/geo+json" } async with httpx.AsyncClient() as client: try: response = await client.get(url, headers=headers, timeout=30.0) response.raise_for_status() return response.json() except Exception: return None ``` -------------------------------- ### Discover Prompts Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Clients can discover available prompts by making a `prompts/list` request. ```APIDOC ## POST prompts/list ### Description Retrieves a list of available prompts that can be used. ### Method POST ### Endpoint /prompts/list ### Request Body This endpoint does not require a request body, only the method identifier. ```json { "method": "prompts/list" } ``` ### Response #### Success Response (200) Returns a list of prompts, each with a name, description, and a list of required arguments. - **prompts** (array) - A list of available prompts. - **name** (string) - The unique name of the prompt. - **description** (string) - A description of what the prompt does. - **arguments** (array) - A list of arguments required by the prompt. - **name** (string) - The name of the argument. - **description** (string) - A description of the argument. - **required** (boolean) - Indicates if the argument is mandatory. #### Response Example ```json { "prompts": [ { "name": "analyze-code", "description": "Analyze code for potential improvements", "arguments": [ { "name": "language", "description": "Programming language", "required": true } ] } ] } ``` ``` -------------------------------- ### Supabase Auth: Get User by ID Source: https://context7.com/alexander-zuev/supabase-mcp-server/llms.txt Fetches a specific user's details from Supabase authentication using their unique user ID (UID). This operation requires an authenticated SDK client. ```python result = await sdk_client.call_auth_admin_method( method="get_user_by_id", params={ "uid": "550e8400-e29b-41d4-a716-446655440000" } ) ``` -------------------------------- ### MCP Client: Prompt System (Sync API - Java) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Shows how to interact with the prompt system using the synchronous MCP client API. This includes listing available prompt templates and executing them with specific parameters to generate dynamic text. Useful for straightforward prompt execution. ```java var prompts = client.listPrompts(); prompts.forEach(prompt -> System.out.println(prompt.getName())); var response = client.executePrompt("echo", Map.of( "text", "Hello, World!" )); ``` -------------------------------- ### Management API Access Source: https://context7.com/alexander-zuev/supabase-mcp-server/llms.txt Execute arbitrary requests to the Supabase Management API with automatic project reference injection and safety validation. Supports GET, POST, PATCH requests across various domains. ```APIDOC ## Management API Access ### Description Execute arbitrary requests to the Supabase Management API with automatic project reference injection and safety validation. Supports various HTTP methods and domains. ### Method GET, POST, PATCH ### Endpoint `/v1/projects/{ref}/functions` `/v1/projects/{ref}` `/v1/organizations/{slug}` ### Parameters #### Path Parameters - **ref** (string) - Required - Project reference - **slug** (string) - Required - Organization slug #### Query Parameters None #### Request Body - **name** (string) - Required - Name of the edge function - **slug** (string) - Required - Slug for the edge function - **verify_jwt** (boolean) - Optional - Whether to verify JWT - **import_map** (boolean) - Optional - Whether to import map - **name** (string) - Optional - Updated project name - **organization_id** (string) - Optional - ID of the organization ### Request Example ```python # Example: List all edge functions (GET request - safe) result = await api_manager.execute_request( method="GET", path="/v1/projects/{ref}/functions", path_params={}, # {ref} auto-replaced with project_ref request_params={}, request_body=None ) # Example: Create edge function (POST - requires unsafe mode) result = await api_manager.execute_request( method="POST", path="/v1/projects/{ref}/functions", path_params={}, request_params={}, request_body={ "name": "send-notification", "slug": "send-notification", "verify_jwt": True, "import_map": True } ) # Example: Get API specification for specific domain spec = await api_manager.handle_spec_request( path=None, method=None, domain="Functions", # Or: Projects, Auth, Storage, Database, etc. all_paths=False ) # Example: Get organization details result = await api_manager.execute_request( method="GET", path="/v1/organizations/{slug}", path_params={"slug": "my-organization"}, request_params={}, request_body=None ) # Example: Update project settings result = await api_manager.execute_request( method="PATCH", path="/v1/projects/{ref}", path_params={}, request_params={}, request_body={ "name": "My Updated Project Name", "organization_id": "org_abc123" } ) ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the resource - **name** (string) - Name of the resource - **slug** (string) - Slug for the resource - **status** (string) - Status of the resource - **version** (integer) - Version of the resource - **created_at** (string) - Timestamp of creation - **updated_at** (string) - Timestamp of last update #### Response Example ```json [ { "id": "func_abc123", "name": "process-payment", "slug": "process-payment", "status": "ACTIVE", "version": 2, "created_at": "2024-10-15T10:30:00Z", "updated_at": "2024-10-28T14:20:00Z" } ] ``` Available API domains: - Analytics, Auth, Database, Domains - Edge Functions, Environments, OAuth - Organizations, Projects, Rest - Secrets, Storage ``` -------------------------------- ### Configure Client Capabilities Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Configures client capabilities, including enabling filesystem roots support with notifications and LLM sampling support. This is done using a builder pattern. ```java var capabilities = ClientCapabilities.builder() .roots(true) // Enable filesystem roots support with list changes notifications .sampling() // Enable LLM sampling support .build(); ``` -------------------------------- ### Inspect PyPi Package Server (Bash) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Launches an MCP server from a PyPi package using the MCP Inspector. This command utilizes `uvx` to run the specified package and its arguments, facilitating testing and debugging of Python-based MCP servers. ```bash npx @modelcontextprotocol/inspector uvx # For example npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git ``` -------------------------------- ### Run MCP Inspector via npx (Bash) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Executes the MCP Inspector tool directly using npx without prior installation. This command is used for interactive testing and debugging of MCP servers. It can accept additional arguments for specific commands. ```bash npx @modelcontextprotocol/inspector ``` ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Tools API - Overview Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Information on how tools enable LLMs to perform actions by interacting with external systems through the MCP. ```APIDOC ## Tools API Tools allow servers to expose executable functions to clients, which LLMs can then invoke to perform actions. Tools are model-controlled, meaning an AI model can suggest their invocation, subject to human approval. ### Key Aspects * **Discovery**: Clients can list available tools using the `tools/list` endpoint. * **Invocation**: Tools are called via the `tools/call` endpoint, where the server executes the requested operation and returns the results. * **Identification**: Tools are identified by unique names and can include descriptions for guidance. * **Functionality**: Tools represent dynamic operations that can modify state or interact with external systems, unlike static resources. ``` -------------------------------- ### Example Transport Error Handling (TypeScript) Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Demonstrates error handling within a TypeScript `ExampleTransport` class that implements the `Transport` interface. It includes try-catch blocks for connection and sending logic, ensuring that errors are caught, logged via the `onerror` callback, and re-thrown. ```typescript class ExampleTransport implements Transport { async start() { try { // Connection logic } catch (error) { this.onerror?.(new Error(`Failed to connect: ${error}`)); throw error; } } async send(message: JSONRPCMessage) { try { // Sending logic } catch (error) { this.onerror?.(new Error(`Failed to send message: ${error}`)); throw error; } } } ``` -------------------------------- ### Build and Run Commands Source: https://github.com/alexander-zuev/supabase-mcp-server/blob/main/llms-full.txt Shell commands to build the Maven project and run the Spring Boot application as a JAR file or directly using Maven. ```bash ./mvnw clean install java -jar ./target/ai-mcp-brave-chatbot-0.0.1-SNAPSHOT.jar ``` ```bash ./mvnw spring-boot:run ```