[Python] Postgresql MCP server not running. Tool showing error

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    Here is the code I am running for mcp-server on cursor -

    from contextlib import asynccontextmanager
    from collections.abc import AsyncIterator
    from dataclasses import dataclass

    import asyncpg
    from mcp.server.fastmcp import FastMCP, Context

    # Async PostgreSQL wrapper using asyncpg
    class Database:
    def __init__(self, pool: asyncpg.Pool):
    self.pool = pool

    @classmethod
    async def connect(cls) -> "Database":
    pool = await asyncpg.create_pool(
    user="postgres",
    password="rohan",
    database="company",
    host="localhost",
    port=5432,
    )
    return cls(pool)

    async def disconnect(self):
    await self.pool.close()

    async def query(self, query: str) -> list:
    async with self.pool.acquire() as conn:
    try:
    return await conn.fetch(query)
    except Exception as e:
    print(f"Query error: {e}")
    return []

    async def fetch_schema(self) -> list:
    query = """
    SELECT table_name FROM information_schema.tables
    WHERE table_schema = 'public'
    """
    return await self.query(query)


    @dataclass
    class AppContext:
    db: Database


    @asynccontextmanager
    async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
    db = await Database.connect()
    try:
    yield AppContext(db=db)
    finally:
    await db.disconnect()


    mcp = FastMCP("PostgresMCPServer", lifespan=app_lifespan)

    @mcp.tool("fetch_schema")
    async def fetch_schema(ctx: Context) -> str:
    db = ctx.request_context.lifespan_context.db
    schema = await db.fetch_schema()
    return str([record["table_name"] for record in schema])


    @mcp.tool("fetch_all_tables")
    async def fetch_all_tables(ctx: Context) -> str:
    db = ctx.request_context.lifespan_context.db
    query = "SELECT * FROM information_schema.tables WHERE table_schema='public'"
    tables = await db.query(query)
    return str(tables)


    @mcp.tool("run_query")
    async def run_query(ctx: Context, query: str) -> str:
    db = ctx.request_context.lifespan_context.db
    result = await db.query(query)
    return str(result)

    if __name__ == "__main__":
    # Initialize and run the server
    mcp.run()


    Here are the libraries i have installed and they are showing up on pyproject.toml file as well -

    mcp
    httpx
    mcp[cli]
    asyncpg


    Here is how i am adding the mcp to use as a tool -

    "PostgresMCPServer": {
    "command": "uv",
    "args": [
    "run",
    "--with",
    "mcp[cli]",
    "mcp",
    "run",
    "C:/mylocalpath/server.py"
    ]
    }


    When I run the server.py, the tool shows error on cursor as well as claude desktop. Here are some error logs from claude -

    2025-07-21T12:05:43.760Z [PostgresMCPServer] [info] Initializing server... { metadata: undefined }
    2025-07-21T12:05:43.801Z [PostgresMCPServer] [info] Using MCP server command: C:\Users\Rohan\AppData\Local\com.Langflow\uv\uv.exe with args and path: {
    metadata: {
    args: [
    'run',
    '--with',
    'mcp[cli]',
    'mcp',
    'run',
    'C:/Users/Rohan/Desktop/MCP_newProjects/postgress-mcp/server.py',
    [length]: 6
    ],
    paths: [
    'C:\\Program Files\\nodejs',
    'C:\\Python312\\Scripts\\',
    'C:\\Python312\\',
    'C:\\WINDOWS\\system32',
    'C:\\WINDOWS',
    'C:\\WINDOWS\\System32\\Wbem',
    'C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\',
    'C:\\WINDOWS\\System32\\OpenSSH\\',
    'C:\\Program Files\\nodejs\\',
    'C:\\ProgramData\\chocolatey\\bin',
    'C:\\Terraform',
    'C:\\Program Files\\Amazon\\AWSCLIV2\\',
    'C:\\Program Files\\PuTTY\\',
    'C:\\Program Files\\Git\\cmd',
    'C:\\ProgramData\\miniconda3\\Library\\bin\\conda.bat',
    'C:\\ProgramData\\miniconda3\\Scripts\\conda.exe',
    'C:\\ProgramData\\miniconda3\\condabin\\conda.bat',
    'C:\\ProgramData\\miniconda3',
    'C:\\ProgramData\\miniconda3\\Library\\bin',
    'C:\\ProgramData\\miniconda3\\Scripts',
    '',
    'c:\\Users\\Rohan\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin',
    'c:\\Users\\Rohan\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin',
    'C:\\Users\\Rohan\\AppData\\Local\\com.Langflow\\uv',
    'C:\\Users\\Rohan\\.local\\bin',
    'C:\\Users\\Rohan\\AppData\\Local\\Microsoft\\WindowsApps',
    'C:\\Users\\Rohan\\AppData\\Roaming\\npm',
    'C:\\Users\\Rohan\\AppData\\Local\\Programs\\Microsoft VS Code\\bin',
    'C:\\Terraform',
    'C:\\ProgramData\\miniconda3\\Library\\bin\\conda.bat',
    'C:\\ProgramData\\miniconda3\\Scripts\\conda.exe',
    'C:\\ProgramData\\miniconda3\\condabin\\conda.bat',
    'C:\\ProgramData\\miniconda3',
    'C:\\ProgramData\\miniconda3\\Library\\bin',
    'C:\\ProgramData\\miniconda3\\Scripts',
    'C:\\Users\\Rohan\\AppData\\Local\\Programs\\Ollama',
    'C:\\Users\\Rohan\\AppData\\Local\\Programs\\cursor\\resources\\app\\bin',
    [length]: 37
    ]
    }
    } %o
    2025-07-21T12:05:43.812Z [PostgresMCPServer] [info] Server started and connected successfully { metadata: undefined }
    2025-07-21T12:05:43.861Z [PostgresMCPServer] [info] Message from client: {"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"claude-ai","version":"0.1.0"}},"jsonrpc":"2.0","id":0} { metadata: undefined }
    Failed to run server
    Traceback (most recent call last):
    File "C:\Users\Rohan\AppData\Local\uv\cache\archive-v0\PQBi79xgW5oSnoZKAozUC\Lib\site-packages\mcp\cli\cli.py", line 343, in run
    server = _import_server(file, server_object)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\Rohan\AppData\Local\uv\cache\archive-v0\PQBi79xgW5oSnoZKAozUC\Lib\site-packages\mcp\cli\cli.py", line 141, in _import_server
    spec.loader.exec_module(module)
    File "<frozen importlib._bootstrap_external>", line 999, in exec_module
    File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
    File "C:\Users\Rohan\Desktop\MCP_newProjects\postgress-mcp\server.py", line 5, in <module>
    import asyncpg
    ModuleNotFoundError: No module named 'asyncpg'
    2025-07-21T12:05:48.536Z [PostgresMCPServer] [info] Server transport closed { metadata: undefined }
    2025-07-21T12:05:48.537Z [PostgresMCPServer] [info] Client transport closed { metadata: undefined }
    2025-07-21T12:05:48.538Z [PostgresMCPServer] [info] Server transport closed unexpectedly, this is likely due to the process exiting early. If you are developing this MCP server you can add output to stderr (i.e. `console.error('...')` in JavaScript, `print('...', file=sys.stderr)` in python) and it will appear in this log. { metadata: undefined }
    2025-07-21T12:05:48.539Z [PostgresMCPServer] [error] Server disconnected. For troubleshooting guidance, please visit our [debugging documentation](https://modelcontextprotocol.io/docs/tools/debugging) { metadata: { context: 'connection', stack: undefined } }
    2025-07-21T12:05:48.541Z [PostgresMCPServer] [info] Client transport closed { metadata: undefined }


    In the error log, I can see issue with asyncpg import but its already installed and there no error on IDE as well, only when i try to add it as mcp tool. Here is pyproject.toml file -

    [project]
    name = "postgress-mcp"
    version = "0.1.0"
    description = "Add your description here"
    readme = "README.md"
    requires-python = ">=3.12"
    dependencies = [
    "asyncpg>=0.30.0",
    "httpx>=0.28.1",
    "mcp[cli]>=1.12.0",
    ]


    Can someone please help in identifying the mistake.

    I ran the code in server.py and expected that the mcp tool would work but instead its showing connection error everywhere.

    Continue reading...

Compartilhe esta Página