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 {
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
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 {
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 {
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
