Trong phần 1 chúng ta đã triển khai máy chủ MCP remote với giao thức cũ SSE. Phần 2 này tiếp tục triển khai giao thức mới hơn: MCP.
Cách triển khai rất đơn giản tương tự như SSE, chỉ có điều cần triển khai 3 điểm cuối cùng tên.
Đầu tiên khai báo một biến transports để lưu lại trạng thái của các kết nối đến dựa vào sessionID.
const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
Triển khai giao thức POST cho /mcp. Đây là điểm cuối tương tác chính giữa máy chủ và máy khách.
app.post('/mcp', async (req, res) => {
// Check for existing session ID
const sessionId = req.headers['mcp-session-id'] as string | undefined;
let transport: StreamableHTTPServerTransport;
if (sessionId && transports[sessionId]) {
// Reuse existing transport
transport = transports[sessionId];
} else if (!sessionId && isInitializeRequest(req.body)) {
// New initialization request
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sessionId) => {
// Store the transport by session ID
transports[sessionId] = transport;
},
});
// Clean up transport when closed
transport.onclose = () => {
if (transport.sessionId) {
delete transports[transport.sessionId];
}
};
await server.connect(transport);
} else {
res.status(400).json({
jsonrpc: '2.0',
error: {
code: -32000,
message: 'Bad Request: No valid session ID provided',
},
id: null,
});
return;
}
await transport.handleRequest(req, res, req.body);
});
Triển khai thêm 2 giao thức GET và DELETE cho /mcp để máy khách nhận dữ liệu từ máy chủ hoặc đóng phiên kết nối.
const handleSessionRequest = async (req: express.Request, res: express.Response) => {
const sessionId = req.headers['mcp-session-id'] as string | undefined;
if (!sessionId || !transports[sessionId]) {
res.status(400).send('Invalid or missing session ID');
return;
}
const transport = transports[sessionId];
await transport.handleRequest(req, res);
};
// Handle GET requests for server-to-client notifications via SSE
app.get('/mcp', handleSessionRequest);
// Handle DELETE requests for session termination
app.delete('/mcp', handleSessionRequest);
Đặt chúng lại với nhau, sửa tệp mcp.json trong LM Studio và thử ra lệnh cho nó.

Chúc mừng bạn đã hoàn thành. Tham khảo mã nguồn trong ví dụ tại Github. Trong bài viết tiếp theo chúng ta sẽ cùng nhau triển khai thêm xác thực cho máy chủ MCP remote nhé.