Claude Tools

Máy chủ MCP tùy chỉnh dành cho Claude: Xây dựng các phần mở rộng công cụ của riêng bạn với Node.js

Siêu tăng tốc Claude với các máy chủ MCP tùy chỉnh trong Node.js. Xây dựng các phần mở rộng công cụ độc quyền để truy cập dữ liệu riêng tư và APIs, mở khóa toàn bộ tiềm năng của Claude.

J

Jennifer Yu

Workflow Automation Specialist

December 6, 2025 min read
Share:

Giới thiệu

Claude AI từ Anthropic rất mạnh mẽ, nhưng các công cụ tích hợp sẵn của nó có giới hạn. Điều gì xảy ra nếu bạn cần truy vấn một cơ sở dữ liệu riêng tư, tích hợp với các API nội bộ, hoặc xử lý các tệp độc quyền? Hãy giới thiệu Model Context Protocol (MCP) servers—các máy chủ HTTP nhẹ nhàng expose các công cụ tùy chỉnh cho Claude qua các endpoint chuẩn hóa. Các máy chủ này cho phép Claude gọi các công cụ của bạn một cách động trong các cuộc trò chuyện, tất cả được xử lý phía client trong tích hợp Anthropic SDK của bạn.

Trong hướng dẫn này, chúng ta sẽ xây dựng một MCP server đầy đủ sử dụng Node.js và Express. Bạn sẽ nhận được các mẫu code hoàn chỉnh cho các công cụ như file reader, weather API caller, và CRM query simulator. Đến cuối, bạn sẽ tích hợp nó với Claude's Messages API để sử dụng công cụ liền mạch. Hoàn hảo cho các lập trình viên mở rộng Claude Code, API workflows, hoặc agents.

Tại sao MCP?

  • Claude-specific: Được tối ưu hóa cho định dạng tool calling của Anthropic (JSON schemas).
  • Scalable: Host cục bộ hoặc trên Vercel/AWS.
  • Secure: Thêm auth cho sử dụng enterprise.
  • Extensible: Kết hợp với Claude Opus/Sonnet cho các agents phức tạp.

(Số từ đến nay: ~150)

Vấn đề: Giới hạn của các công cụ Claude gốc

Claude 3.5 Sonnet xuất sắc trong việc sử dụng công cụ, nhưng:

  • Các công cụ tích hợp sẵn (ví dụ: computer use trong Claude Code) không truy cập dữ liệu của bạn.
  • Các tích hợp độc quyền yêu cầu logic tùy chỉnh.
  • Mở rộng công cụ qua các đội ngũ cần một máy chủ trung tâm.

Ví dụ các điểm đau:

  • Engineering: Truy vấn Jira/GitHub repos.
  • Sales: Lấy CRM leads (Salesforce/HubSpot).
  • HR: Truy cập danh bạ nhân viên.
  • Marketing: Phân tích dữ liệu chiến dịch.

MCP giải quyết điều này bằng cách cung cấp một tool registry (/tools) và execution endpoint (/tools/call), mô phỏng protocol tool_use của Anthropic.

(Số từ: ~300)

Yêu cầu trước

  • Node.js 18+
  • Anthropic API key (miễn phí tại console.anthropic.com)
  • Kiến thức cơ bản về Express
  • Tùy chọn: ngrok cho kiểm tra công khai

Cài đặt toàn cục:

npm init -y
npm install express cors axios dotenv
npm install -D nodemon

Tạo .env:

ANTHROPIC_API_KEY=your_key_here
MCP_PORT=3000

(Số từ: ~350)

Bước 1: Cấu trúc dự án

my-mcp-server/
├── server.js
├── tools/
│   ├── fileReader.js
│   ├── weather.js
│   └── crmQuery.js
├── .env
└── package.json

(Số từ: ~360)

Bước 2: Thiết lập MCP Server cốt lõi

server.js khởi động Express với các endpoint MCP.

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const fileReader = require('./tools/fileReader');
const weather = require('./tools/weather');
const crmQuery = require('./tools/crmQuery');

const app = express();
app.use(cors());
app.use(express.json());

const PORT = process.env.MCP_PORT || 3000;

// MCP Standard: GET /tools - List tools with JSON schemas
app.get('/tools', (req, res) => {
  const tools = [
    fileReader.schema,
    weather.schema,
    crmQuery.schema
  ];
  res.json({ tools });
});

// MCP Standard: POST /tools/call - Execute tool
app.post('/tools/call', async (req, res) => {
  const { name, arguments: args } = req.body;
  try {
    let result;
    switch (name) {
      case 'file_reader':
        result = await fileReader.execute(args);
        break;
      case 'get_weather':
        result = await weather.execute(args);
        break;
      case 'crm_query':
        result = await crmQuery.execute(args);
        break;
      default:
        throw new Error(`Unknown tool: ${name}`);
    }
    res.json({ content: [{ type: 'text', text: JSON.stringify(result) }] });
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

app.listen(PORT, () => {
  console.log(`MCP Server running at http://localhost:${PORT}`);
});

Các quy ước MCP chính:

  • /tools trả về mảng các định nghĩa công cụ tương thích với anthropic.tools.
  • /tools/call mô phỏng định dạng tool_result của Claude.
  • Args là các đối tượng JSON.

Chạy: nodemon server.js

Kiểm tra: curl http://localhost:3000/tools

(Số từ: ~650)

Bước 3: Triển khai các công cụ tùy chỉnh

Công cụ 1: File Reader (Tệp cục bộ)

tools/fileReader.js - Đọc tệp văn bản một cách an toàn.

const fs = require('fs').promises;
const path = require('path');

const schema = {
  name: 'file_reader',
  description: 'Read content from a local text file. Use for code/docs.',
  inputSchema: {
    type: 'object',
    properties: {
      file_path: {
        type: 'string',
        description: 'Relative path to file, e.g., ./data/report.txt'
      }
    },
    required: ['file_path']
  }
};

async function execute({ file_path }) {
  try {
    const fullPath = path.resolve(__dirname, '..', file_path);
    const content = await fs.readFile(fullPath, 'utf8');
    return { content, path: fullPath };
  } catch (error) {
    throw new Error(`File read failed: ${error.message}`);
  }
}

module.exports = { schema, execute };

Công cụ 2: Weather API (Tích hợp bên ngoài)

Sử dụng OpenWeatherMap (lấy key miễn phí).

tools/weather.js:

const axios = require('axios');

const OPENWEATHER_KEY = 'your_openweather_key'; // Add to .env

const schema = {
  name: 'get_weather',
  description: 'Get current weather for a city.',
  inputSchema: {
    type: 'object',
    properties: {
      city: { type: 'string' }
    },
    required: ['city']
  }
};

async function execute({ city }) {
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${OPENWEATHER_KEY}&units=metric`;
  const response = await axios.get(url);
  const { main, weather } = response.data;
  return {
    temperature: main.temp,
    condition: weather[0].description,
    city
  };
}

module.exports = { schema, execute };

Công cụ 3: CRM Query (Mô phỏng dữ liệu độc quyền)

Mô phỏng truy vấn Salesforce—thay thế bằng SDK thực.

tools/crmQuery.js:

// Mock CRM data
const mockLeads = [
  { id: 1, name: 'John Doe', email: 'john@ex.com', status: 'lead' },
  { id: 2, name: 'Jane Smith', email: 'jane@ex.com', status: 'qualified' }
];

const schema = {
  name: 'crm_query',
  description: 'Query CRM leads by status or name.',
  inputSchema: {
    type: 'object',
    properties: {
      query: {
        type: 'string',
        description: 'e.g., "status:qualified" or "name:John"'
      }
    },
    required: ['query']
  }
};

function execute({ query }) {
  const results = mockLeads.filter(lead =>
    lead.status.includes(query) || lead.name.toLowerCase().includes(query.toLowerCase())
  );
  return { leads: results };
}

module.exports = { schema, execute };

Mẹo chuyên nghiệp: Đối với CRM thực, sử dụng salesforce-js-sdk hoặc tương tự. Giới hạn truy vấn để tránh lạm dụng.

(Số từ: ~1250)

Bước 4: Tích hợp client với Anthropic SDK

Cài đặt SDK: npm install @anthropic-ai/sdk

client.js - Lặp công cụ qua MCP server.

import Anthropic from '@anthropic-ai/sdk';
import axios from 'axios';

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
const MCP_URL = 'http://localhost:3000';

async function getTools() {
  const { data } = await axios.get(`${MCP_URL}/tools`);
  return data.tools;
}

async function callTool(toolName, args) {
  const { data } = await axios.post(`${MCP_URL}/tools/call`, { name: toolName, arguments: args });
  return data.content[0].text;
}

async function chatWithTools(prompt) {
  const tools = await getTools();
  let message = await anthropic.messages.create({
    model: 'claude-3-5-sonnet-20241022',
    max_tokens: 1024,
    messages: [{ role: 'user', content: prompt }],
    tools
  });

  while (message.content[0].type === 'tool_use') {
    const { name, input } = message.content[0];
    const toolResult = await callTool(name, input);
    message = await anthropic.messages.create({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 1024,
      messages: [
        { role: 'user', content: prompt },
        message,
        {
          role: 'user',
          content: [{
            type: 'tool_result',
            tool_use_id: message.content[0].id,
            content: toolResult
          }]
        }
      ],
      tools
    });
  }

  console.log(message.content[0].text);
}

// Test
chatWithTools('What\'s the weather in NYC? Then query CRM for qualified leads.');

Chạy server, sau đó node client.js. Claude lấy công cụ, gọi chúng qua MCP của bạn!

Ví dụ output: "NYC weather: 22°C, partly cloudy. Qualified leads: Jane Smith (jane@ex.com)."

(Số từ: ~1550)

Bước 5: Bảo mật & Triển khai

  • Auth: Thêm kiểm tra header API key trong server.
app.use((req, res, next) => {
  if (req.headers['x-api-key'] !== process.env.MCP_SECRET) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});
  • Rate Limiting: Sử dụng express-rate-limit.
  • Deploy: Vercel (serverless) hoặc Heroku. Sử dụng ngrok cho kiểm tra Claude Desktop cục bộ.
  • HTTPS: Bắt buộc cho prod.

Tích hợp với Claude Code CLI: Đặt CLAUDE_MCP_URL=http://your-server/tools (kiểm tra docs).

Nâng cao: AI Agents & n8n/Zapier

Chuỗi MCP với agents:

  • Sử dụng Sonnet cho reasoning + Haiku cho công cụ nhanh.
  • n8n workflow: Claude → MCP call → Slack notify.

Ví dụ prompt: "Act as sales agent: Check weather, query CRM, draft email."

Kết luận

Bạn đã xây dựng một MCP server sẵn sàng sản xuất! Mở rộng Claude cho các workflow thực tế—dữ liệu riêng tư, API, tệp. Fork repo, thêm công cụ, triển khai. Chia sẻ các build của bạn trong phần bình luận Claude Directory.

Các bước tiếp theo:

  • So sánh với các lib MCP (ví dụ: Python FastMCP).
  • Enterprise: Truy cập chỉ VPC.
  • Theo dõi cập nhật Anthropic cho hỗ trợ MCP gốc.

Full code: GitHub template (imagine link).

(Số từ: ~1750)

The #1 Newsletter in AI

Stay ahead of the AI curve

The most important updates, news, and content — delivered in one weekly newsletter.

No spam. Unsubscribe anytime. Privacy policy

MCP Máy chủ
Công cụ Claude
Node.js
Anthropic SDK
Công cụ Tùy chỉnh
ai-agents
J

About Jennifer Yu

Workflow Automation Specialist

Jennifer covers workflow strategy, no-code platforms, and clear implementation guidance for teams adopting automation.

Comments (0)