|
| 1 | +# PG-MCP Model Context Protocol Server for CrateDB |
| 2 | +# https://github.com/stuzero/pg-mcp |
| 3 | +# https://github.com/crate-workbench/pg-mcp |
| 4 | +# |
| 5 | +# Derived from: |
| 6 | +# https://github.com/modelcontextprotocol/python-sdk?tab=readme-ov-file#writing-mcp-clients |
| 7 | +from cratedb_toolkit.util import DatabaseAdapter |
| 8 | +from mcp import ClientSession, StdioServerParameters |
| 9 | +from mcp.client.stdio import stdio_client |
| 10 | +import where |
| 11 | + |
| 12 | +from mcp_utils import McpDatabaseConversation |
| 13 | + |
| 14 | + |
| 15 | +async def run(): |
| 16 | + # Create server parameters for stdio connection. |
| 17 | + server_params = StdioServerParameters( |
| 18 | + command=where.first("python"), |
| 19 | + args=["example_pg_mcp_server.py"], |
| 20 | + env={}, |
| 21 | + ) |
| 22 | + |
| 23 | + async with stdio_client(server_params) as (read, write): |
| 24 | + async with ClientSession( |
| 25 | + read, write |
| 26 | + ) as session: |
| 27 | + # Initialize the connection. |
| 28 | + await session.initialize() |
| 29 | + |
| 30 | + client = McpDatabaseConversation(session) |
| 31 | + await client.inquire() |
| 32 | + |
| 33 | + print("## MCP server conversations") |
| 34 | + print() |
| 35 | + |
| 36 | + # Provision database content. |
| 37 | + db = DatabaseAdapter("crate://crate@localhost:4200/") |
| 38 | + db.run_sql("CREATE TABLE IF NOT EXISTS mcp_pg_mcp (id INT, data TEXT)") |
| 39 | + db.run_sql("INSERT INTO mcp_pg_mcp (id, data) VALUES (42, 'Hotzenplotz')") |
| 40 | + db.refresh_table("mcp_pg_mcp") |
| 41 | + |
| 42 | + # Call a few tools. |
| 43 | + connection_string = "postgresql://crate@localhost/doc" |
| 44 | + |
| 45 | + # Connect to the database, receiving the connection UUID. |
| 46 | + response = await client.call_tool("connect", arguments={"connection_string": connection_string}) |
| 47 | + conn_id = client.decode_json_text(response)["conn_id"] |
| 48 | + |
| 49 | + # Query and explain, using the connection id. |
| 50 | + await client.call_tool("pg_query", arguments={ |
| 51 | + "query": "SELECT * FROM sys.summits ORDER BY height DESC LIMIT 3", |
| 52 | + "conn_id": conn_id, |
| 53 | + }) |
| 54 | + await client.call_tool("pg_explain", arguments={ |
| 55 | + "query": "SELECT * FROM mcp_pg_mcp", |
| 56 | + "conn_id": conn_id, |
| 57 | + }) |
| 58 | + |
| 59 | + # Read a few resources. |
| 60 | + await client.read_resource(f"pgmcp://{conn_id}/schemas") |
| 61 | + await client.read_resource(f"pgmcp://{conn_id}/schemas/sys/tables") |
| 62 | + |
| 63 | + # Disconnect again. |
| 64 | + await client.call_tool("disconnect", arguments={"conn_id": conn_id,}) |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + import asyncio |
| 69 | + |
| 70 | + asyncio.run(run()) |
0 commit comments