数据库MCP服务器

Prisma MCP Server是一个通过Model Context Protocol(MCP)提供数据库交互接口的服务,支持资源加载、工具执行和数据库操作,适用于AI助手和其他应用程序与Prisma ORM管理的数据库进行交互。

  • by nikomatt69
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 nikomatt69/cadcamfun-db-mcp-server

使用说明

Prisma MCP服务器

此软件包提供了一个模型上下文协议(MCP)服务器,作为Prisma ORM管理的数据库的接口。它允许MCP兼容的客户端(如AI助手或其他应用程序)通过查询资源和执行工具与您的数据库进行交互。

此服务器使用 fastmcp 公开Prisma模型和操作。

特性

  • 资源加载: 将Prisma模型作为可读MCP资源公开(例如。, resource://users/{user_id}, resource://projects).
  • 工具执行: 为Prisma模型上的常见CRUD(创建、读取、更新、删除)操作提供MCP工具(例如。, create_user, update_project).
  • 数据库交互: 处理MCP请求和Prisma客户端数据库查询之间的转换。
  • 可配置传输: 支持两者 stdio 和 sse (通过HTTP发送的服务器事件)传输模式。
  • 可扩展: 轻松添加自定义资源或工具,用于更复杂的操作或与其他应用程序服务的交互。

先决条件

  • Node.js: 最新版本(检查 package.json 发动机(如有规定)。
  • Yarn或npm: 包管理器。
  • Prisma客户: 您的消费项目必须具有 @prisma/client 已安装和a prisma/schema.prisma 为目标数据库配置的文件。
  • 数据库: Prisma支持的正在运行的数据库实例(例如PostgreSQL、MySQL、SQLite)。

安装

# Using yarn
yarn add cadcamfun-db-mcp-server @prisma/client

# Using npm
npm install cadcamfun-db-mcp-server @prisma/client

注: 你 必须 安装 @prisma/client 作为项目中的对等依赖 使用 此服务器包。

消费项目中的设置

  1. Prisma架构: 确保你有一个有效的 prisma/schema.prisma 项目根目录中定义数据库连接和模型的文件。
  2. 环境变量: 配置必要的环境变量(例如,在 .env 文件)。 不要提交敏感变量,如 DATABASE_URL 直接到版本控制。
    • DATABASE_URL: (必填) 数据库的连接字符串(例如。, postgresql://user:password@host:port/database).
    • TRANSPORT_TYPE:(可选)设置为 sse 使用HTTP上的服务器发送事件。 默认为 stdio.
    • PORT:(可选,必填 TRANSPORT_TYPE=sse)SSE服务器的端口。 默认为 8080.
    • MAIN_APP_URL:(可选)如果使用需要回调的工具(例如。, trigger_main_app_notification). 默认为 http://localhost:3000.
    • LOG_LEVEL:(可选)控制日志的详细程度。吃起来 DEBUG, INFO, WARN,或 ERROR。行为取决于包中的记录器实现(如果使用)。
  3. 生成Prisma客户端: 在运行服务器之前,您 必须 根据您的模式生成Prisma客户端:
    npx prisma generate
    
    这一步至关重要,因为服务器依赖于生成的客户端 node_modules/@prisma/client.

用法

// Example: index.ts in your consuming project

// Import the server creation function
import { createPrismaMcpServer } from 'prisma-mcp-server';
import { PrismaClient } from '@prisma/client'; // Make sure Prisma Client is installed

// Ensure required environment variables are set
if (!process.env.DATABASE_URL) {
  console.error("Error: DATABASE_URL environment variable is not set.");
  process.exit(1);
}

// Optional: Configure transport type and port via environment variables
// process.env.TRANSPORT_TYPE = 'sse';
// process.env.PORT = '8081';

async function main() {
  // Ensure Prisma Client is generated (Best done in a build step)
  try {
    // Check if client exists, generate if not (simple check)
    require.resolve('@prisma/client'); 
  } catch (e) {
      console.log('Prisma Client not found, attempting to generate...');
      try {
          const { execSync } = require('child_process');
          execSync('npx prisma generate', { stdio: 'inherit' });
          console.log('Prisma Client generated.');
      } catch (error) {
          console.error('Error generating Prisma Client:', error);
          process.exit(1);
      }
  }

  // Create the server instance
  const server = createPrismaMcpServer({
    // Optional: Override default server info if needed
    // name: "MyCustomServerName",
    // version: "2.0.0",
    // instructions: "Custom instructions..."
  });

  console.log(`Starting Prisma MCP Server...`);

  // Determine transport options based on environment variables
  const transportType = process.env.TRANSPORT_TYPE === 'sse' ? 'sse' : 'stdio';
  const port = parseInt(process.env.PORT || "8080");
  const sseEndpoint = "/sse"; // Assuming hardcoded endpoint

  const startOptions: any = { transportType }; // Use 'any' temporarily if exact type is complex
  if (transportType === 'sse') {
    startOptions.sse = { endpoint: sseEndpoint, port: port };
  }

  // Start the server using the options derived from environment variables
  server.start(startOptions);

  console.log(`Server started with transport: ${transportType}`);
  if (transportType === 'sse') {
      console.log(`SSE endpoint available at http://localhost:${port}${sseEndpoint}`);
  }
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});

现在,您可以使用配置的传输方法将MCP客户端连接到正在运行的服务器(stdio 或 /sse 端点)。

与Claude Desktop连接

Claude Desktop(或类似的MCP客户端)可以使用以下任一方式连接到此服务器 stdio 或 sse 运输方式。

  1. 配置传输:

    • 启动服务器之前,请设置 TRANSPORT_TYPE 消费项目环境中的环境变量(例如 .env 文件或系统环境):
      • TRANSPORT_TYPE=stdio (默认):服务器将通过标准输入和输出进行通信。
      • TRANSPORT_TYPE=sse:服务器将为服务器发送的事件启动HTTP服务器。
    • 如果使用 sse,您还可以设置 PORT 环境变量(默认为 8080).
  2. 启动服务器:

    • 运行您的消费应用程序的入口点(例如。, node your-app-entrypoint.js)其中包括创建和启动 prisma-mcp-server (如图所示 用法 部分)。
  3. 连接克劳德桌面:

    • 如果使用 stdio: 配置Claude Desktop以直接启动服务器进程。这通常涉及提供启动应用程序的命令(例如。, node /path/to/your-app-entrypoint.js 或 yarn start 如果你有一个开始脚本)。
    • 如果使用 sse: 配置Claude Desktop以连接到HTTP端点。默认URL为 http://localhost:8080/sse。如果您更改了 PORT,相应调整。
  4. 识别服务器:

    • 在Claude Desktop中,您可能需要识别服务器。默认情况下,它被命名为 PrismaAPI_Server (版本 1.1.0),但这可以在调用时被覆盖 createPrismaMcpServer.

示例 mcp.json Claude Desktop的片段:

  • 使用 stdio:

    {
      "mcpServers": {
        "prisma_api_stdio": {
          "name": "Prisma API Server (stdio)", // Optional display name
          // Option 1: Using npx with a script/package name
          "command": "npx",
          "args": [
            "cadcamfun-db-mcp-server" // Replace with your actual script/package name
          ],
          // Option 2: Using yarn/npm run script
          // "command": "yarn", 
          // "args": ["start:prisma-mcp"], // Assuming a script named 'start:prisma-mcp'
          "workingDirectory": "" // Replace with the path to your CONSUMING project root
        }
      }
    }
    
  • 使用 sse:

    {
      "mcpServers": {
        "prisma_api_sse": {
          "name": "Prisma API Server (SSE)", // Optional display name
          // Assumes the server is running and listening on port 8080 (default)
          // The port can be changed via the PORT environment variable when starting the server.
          "url": "http://localhost:8080/sse" 
        }
      }
    }
    

有关如何添加和配置新的MCP服务器连接的确切步骤,请参阅您特定的MCP客户端文档。

可用资源和工具

此服务器公开与其内部模式中定义的Prisma模型相对应的MCP资源和工具(prisma/schema.prisma 在包内,虽然它使用 消费项目 生成客户端)。

资源(示例):

  • resource://users
  • resource://users/{user_id}
  • resource://projects
  • resource://projects/{project_id}
  • resource://drawings?project_id={project_id}
  • resource://drawings/{drawing_id}
  • resource://components?project_id={project_id}
  • resource://components/{component_id}
  • resource://materials
  • resource://materials/{material_id}
  • resource://tools
  • resource://tools/{tool_id}
  • resource://machine-configs
  • resource://machine-configs/{machine_config_id}
  • resource://toolpaths?project_id={project_id}
  • resource://toolpaths/{toolpath_id}
  • resource://library-items
  • resource://library-items/{library_item_id}

(参见 src/resources.ts 完整列表和参数)

工具(示例):

  • create_user, update_user, delete_user
  • create_subscription, update_subscription, delete_subscription
  • create_organization, update_organization, delete_organization
  • create_project, update_project, delete_project
  • create_drawing, update_drawing, delete_drawing
  • create_component, update_component, delete_component
  • create_material, update_material, delete_material
  • create_tool_prisma, update_tool_prisma, delete_tool_prisma
  • create_machine_config, update_machine_config, delete_machine_config
  • create_toolpath, update_toolpath, delete_toolpath
  • create_library_item, update_library_item, delete_library_item
  • trigger_main_app_notification (自定义工具示例)

(参见 src/tools.ts 对于使用Zod定义的完整列表和参数)

延伸

您可以分叉此包或将其用作基础,通过修改来添加自己的自定义资源和工具 src/resources.ts 和 src/tools.ts.记得重建(yarn build)在做出改变之后。

部署

  1. 配置数据库: 确保您的生产 DATABASE_URL 在部署环境中正确设置了环境变量(例如,服务器环境变量、secrets管理器)。 不要将此提交到您的存储库。
  2. 环境变量: 集 TRANSPORT_TYPE (sse 或 stdio)并且可选 PORT 和 MAIN_APP_URL 在您的部署环境中。
  3. 构建和运行:
    # Navigate to your project directory (where prisma-mcp-server is a dependency)
    
    # Install dependencies
    yarn install --production # Or npm install --omit=dev
    
    # Generate Prisma Client (Important! Needs DATABASE_URL)
    npx prisma generate
    
    # Apply Migrations (Needs DATABASE_URL - Replace with your strategy)
    # Example:
    # npx prisma migrate deploy 
    
    # Build your application (which includes the server code)
    yarn build # Or your specific build command
    
    # Start your application (which starts the MCP server)
    # Use a process manager like pm2 in production
    # Example:
    # pm2 start your-app-entrypoint.js 
    # OR
    # node your-app-entrypoint.js 
    

许可证

[MIT]