MCP服务器数据库工具

一个基于TypeScript的MCP服务器,提供数据库访问工具和资源管理功能,适用于本地数据库操作和LLM集成。

  • by loickaczmarek
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 loickaczmarek/mcp-fantasy-library

使用说明

MCP服务器打字教程

本教程的目的是创建第一个MCP服务器 stdio 在TypeScript中,它提供对本地数据库的访问。

有关MCP协议的更多信息:https://modelcontextprotocol.io/introduction

Prérequis

  • 避免使用javascript
  • Avoir Node.js
  • 拥有Docker

初始化

我们不会开始启动这个项目。为此,我们可以从浏览文件开始 package.json.

我们缺少输入文件 src/index.ts :所以你必须创造它

我们可以启动安装我们选择的软件包的命令。

使用npm: npm install

总理帕斯

我们将添加运行MCP服务器所需的最小值。 为此,在 index.ts,添加以下内容:

const server = new Server(
    {
        name: "Fantasy Library Database",
        version: "0.1.0",
    },
    {
        capabilities: {
            resources: {},
            tools: {},
        },
    },
);

async function runServer() {
    const transport = new StdioServerTransport();
    console.log("Starting MCP Fantasy Library server")
    await server.connect(transport);
}

runServer().catch(console.error);

我们将构建并启动应用程序:

npm run build && npm run dev

如果一切顺利,您将看到以下消息: Starting MCP Fantasy Library server

一些概念

MCP服务器允许公开工具、资源、提示等。…(见文件 这里 )

在本练习中,我们将重点讨论两个概念:

  • 工具:允许您在有或没有参数的情况下执行精确操作。使用是无状态的,用于一次性使用,例如,不需要保持连接活动。这类似于API的精确调用。
  • 资源:提供访问权限。使用是有状态的,使用是为了保持连接打开。这类似于API声明。

为了使用MCP服务器,我们将以JSON RPC格式注入JSON,这是MCP协议使用的格式。

使用结果

设置

我们需要一个数据库,为此,我们将使用 docker-compose.yml

枪兵 docker-compose up -d

检查数据库是否可通过任何工具访问(工具示例: 海狸)

工具的创建

阐述

首先,我们将使服务器的工具可见。 因此,必须添加工具列表查询处理程序。

我们还将借此机会声明我们的第一个工具:检索一本书的描述

在 index.ts应添加:

// au niveau des imports
import {
    ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";

...

// avant de lancer la fonction runServer()
server.setRequestHandler(ListToolsRequestSchema, async () => {
    return {
        tools: [
            {
                name: "get-book-description",
                description: "Get the book description from fantasy library",
                inputSchema: {
                    type: "object",
                    properties: {
                        name: { type: "string" },
                    },
                },
            },
        ],
    };
});

启动构建: npm run build

然后,检查它是否与方法一起工作 tools\list :

( cat <<\EOF
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"example-client","version":"1.0.0"},"capabilities":{}}}
{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}
EOF
) | npm run dev

在工具列表中,图书恢复工具应在结果中可见。 工具描述很重要:LLM将使用该描述来识别正确的工具!

使用

现在工具已经列出,我们将使用它。

让我们添加以下内容:

// import
import {
    CallToolRequestSchema,
    ListToolsRequestSchema
} from "@modelcontextprotocol/sdk/types.js";

// code
server.setRequestHandler(CallToolRequestSchema, async (request) => {
    if (request.params.name === "get-book-description") {
        return {
            content: [{ type: "text", text: "Hello World !" }],
            isError: false,
        };
    }
    throw new Error(`Unknown tool: ${request.params.name}`);
});

构建代码并使用方法启动 tools\call :

( cat <<\EOF
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"example-client","version":"1.0.0"},"capabilities":{}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get-book-description", "arguments" : {}}}
EOF
      ) | npm run dev

如果一切顺利,输出应显示消息“你好,世界!”。

与基地的连接

是时候将服务器连接到数据库了。

为此,我们将添加必要的:

  • 传递本地URL的参数
  • 连接管理
  • 要执行的请求

首先,我们将添加:

// import
import * as pg from "pg";

// code
const args = process.argv.slice(2);
if (args.length === 0) {
    console.error("Please provide a database URL as a command-line argument");
    process.exit(1);
}

const databaseUrl = args[0];

const resourceBaseUrl = new URL(databaseUrl);
resourceBaseUrl.protocol = "postgres:";
resourceBaseUrl.password = "";

const pool = new pg.Pool({
    connectionString: databaseUrl,
});

此部分用于打开与数据库的连接。

此外,让我们创建一个工具将使用的方法:

async function getBookDescription(request : any) {
    const bookName = request.params.arguments?.name as string;

    const client = await pool.connect();
    try {
        await client.query("BEGIN TRANSACTION READ ONLY");
        const result = await client.query(`SELECT description FROM livres WHERE titre = '${bookName}'`);
        return {
            content: [{ type: "text", text: JSON.stringify(result.rows, null, 2) }],
            isError: false,
        };
    } catch (error) {
        throw error;
    } finally {
        client
            .query("ROLLBACK")
            .catch((error) =>
                console.warn("Could not roll back transaction:", error),
            );

        client.release();
    }
}

让我们替换该方法:

// avant
server.setRequestHandler(CallToolRequestSchema, async (request) => {
    if (request.params.name === "get-book-description") {
        return {
            content: [{ type: "text", text: "Hello World !" }],
            isError: false,
        };
    }
    throw new Error(`Unknown tool: ${request.params.name}`);
});

// après
server.setRequestHandler(CallToolRequestSchema, async (request) => {
    if (request.params.name === "get-book-description") {
        return await this.getBookDescription(request);
    }
    throw new Error(`Unknown tool: ${request.params.name}`);
});

然后,您必须使用该方法进行构建和验证 tools\call :

( cat <<\EOF
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"example-client","version":"1.0.0"},"capabilities":{}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get-book-description", "arguments" : {"name":"Culture Code"}}}
EOF
    ) | npm run dev -- postgresql://admin:password@localhost:5432/bibliotheque

应该会出现文化代码的简要描述!

为了更进一步

添加工具以:

  • 可用书籍列表
  • 确定借阅给定书籍的人

资源利用

阐述

与工具一样,您需要能够识别可用的资源 因此,必须添加资源列表请求处理程序。

// imports
import {
    CallToolRequestSchema,
    ListToolsRequestSchema,
    ListResourcesRequestSchema
} from "@modelcontextprotocol/sdk/types.js";

...

// code
const SCHEMA_PATH = "schema";

server.setRequestHandler(ListResourcesRequestSchema, async () => {
    const client = await pool.connect();
    try {
        const result = await client.query(
            "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'",
        );
        return {
            resources: result.rows.map((row) => ({
                uri: new URL(`${row.table_name}/${SCHEMA_PATH}`, resourceBaseUrl).href,
                mimeType: "application/json",
                name: `"${row.table_name}" database schema`,
            })),
        };
    } finally {
        client.release();
    }
});

启动构建: npm run build

然后,检查它是否有效,我们将使用方法进行查询 resources/list :

( cat <<\EOF
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"example-client","version":"1.0.0"},"capabilities":{}}}
{"jsonrpc":"2.0","id":2,"method":"resources/list","params":{}}
EOF
   ) | npm run dev -- postgresql://admin:password@localhost:5432/bibliotheque

使用

我们将添加资源使用处理程序:

// import
import {
    CallToolRequestSchema,
    ListResourcesRequestSchema,
    ListToolsRequestSchema,
    ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

// code
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
    const resourceUrl = new URL(request.params.uri);

    const pathComponents = resourceUrl.pathname.split("/");
    const schema = pathComponents.pop();
    const tableName = pathComponents.pop();

    if (schema !== SCHEMA_PATH) {
        throw new Error("Invalid resource URI");
    }

    const client = await pool.connect();
    try {
        const result = await client.query(
            "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = $1",
            [tableName],
        );

        return {
            contents: [
                {
                    uri: request.params.uri,
                    mimeType: "application/json",
                    text: JSON.stringify(result.rows, null, 2),
                },
            ],
        };
    } finally {
        client.release();
    }
});

让我们启动构建,检查它是否与方法一起工作 resources/read :

( cat <<\EOF
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"example-client","version":"1.0.0"},"capabilities":{}}}
{"jsonrpc":"2.0","id":2,"method":"resources/read","params":{"uri":"postgres://admin@localhost:5432/clients/schema"}}
EOF
    ) | npm run dev -- postgresql://admin:password@localhost:5432/bibliotheque

结果应该是数据库的模式信息

为了更进一步

本教程基于Postgres MCP服务器( 这里 )

要在实际条件下测试它,最好将其插入MCP客户端。 列表在这里:https://modelcontextprotocol.io/clients

该服务器已使用Claude Code客户端进行了测试和验证,并返回了令人满意的结果,如 donnes moi la description du livre Culture Code