Claude + MCP 构建 AI 工作站:让大模型直接操作你的电脑和服务器

阿里云上云采购季 2核2G云服务器99元/年 续费同价

MCP(Model Context Protocol)正在改变 AI 工具的玩法。以前 AI 只能聊天,现在它能直接操作文件、执行命令、查数据库。本文带你用 Claude + MCP,搭一个能干活的 AI 工作站。


什么是 MCP?为什么它很重要?

MCP(Model Context Protocol)是 Anthropic 在 2024 年底发布的开放协议,解决了 AI 模型与外部工具连接的标准化问题。

传统方式的痛点:

LangChain 工具 ←→ 只兼容 LangChain
AutoGPT 插件  ←→ 只兼容 AutoGPT
Claude 工具   ←→ 只兼容 Claude API

MCP 的价值:

任何 MCP Server ←→ 任何 MCP Client(Claude/Cursor/Zed/自研 Agent)

相当于 AI 界的 USB 接口标准——一次开发,到处可用。

MCP 架构

┌─────────────────────────────────────────┐
│           MCP Client(Claude Desktop)   │
│  - 发起工具调用请求                       │
│  - 解析工具返回结果                       │
└─────────────┬───────────────────────────┘
              │ MCP Protocol(stdio/SSE)
    ┌─────────▼──────────┐
    │   MCP Server        │
    │  ┌──────────────┐   │
    │  │ 文件系统工具   │   │
    │  │ 数据库工具    │   │
    │  │ Shell工具    │   │
    │  │ HTTP工具     │   │
    │  └──────────────┘   │
    └────────────────────┘

第1步:安装 MCP 基础环境

# 安装 Node.js(MCP Server 主要用 TypeScript 开发)
node -v  # 需要 v18+

# 安装 Python(Python MCP SDK)
pip install mcp anthropic

# 安装 Claude Desktop(macOS/Windows)
# 下载地址:https://claude.ai/download

# 查看 Claude Desktop 配置文件位置
# macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
# Windows: %APPDATA%\Claude\claude_desktop_config.json

第2步:接入官方 MCP Server

2.1 文件系统 Server

// claude_desktop_config.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/yourname/workspace",
        "/Users/yourname/Documents"
      ]
    }
  }
}

配置后,Claude 就能直接读写你指定目录下的文件了。

2.2 数据库 Server(SQLite)

{
  "mcpServers": {
    "sqlite": {
      "command": "uvx",
      "args": [
        "mcp-server-sqlite",
        "--db-path",
        "/Users/yourname/data/mydb.sqlite"
      ]
    }
  }
}

2.3 完整配置示例(多 Server)

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"]
    },
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "/data/app.db"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_your_token_here"
      }
    },
    "puppeteer": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
    }
  }
}

第3步:自己开发 MCP Server

内置 Server 不够用?来开发自己的 MCP Server。

用 Python 开发一个服务器监控 MCP Server

# server_monitor_mcp.py
import asyncio
import subprocess
import psutil
from datetime import datetime
from mcp.server import Server
from mcp.server.models import InitializationOptions
from mcp.server.stdio import stdio_server
from mcp.types import (
    Tool,
    TextContent,
    CallToolResult,
)

# 初始化 MCP Server
app = Server("server-monitor")

@app.list_tools()
async def list_tools() -> list[Tool]:
    """声明本 Server 提供的工具列表"""
    return [
        Tool(
            name="get_system_status",
            description="获取服务器系统状态(CPU、内存、磁盘、网络)",
            inputSchema={
                "type": "object",
                "properties": {},
                "required": []
            }
        ),
        Tool(
            name="run_command",
            description="在服务器上执行 Shell 命令(仅限安全命令)",
            inputSchema={
                "type": "object",
                "properties": {
                    "command": {
                        "type": "string",
                        "description": "要执行的 Shell 命令"
                    }
                },
                "required": ["command"]
            }
        ),
        Tool(
            name="check_process",
            description="检查指定进程是否在运行",
            inputSchema={
                "type": "object",
                "properties": {
                    "process_name": {
                        "type": "string",
                        "description": "进程名称,如 nginx、mysql"
                    }
                },
                "required": ["process_name"]
            }
        ),
    ]

@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    """处理工具调用请求"""

    if name == "get_system_status":
        # 收集系统状态
        cpu_percent = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        disk = psutil.disk_usage('/')
        net_io = psutil.net_io_counters()

        status = f"""
## 服务器状态报告
**时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

### CPU
- 使用率: {cpu_percent}%
- 核心数: {psutil.cpu_count()} 核

### 内存
- 总量: {memory.total / 1024**3:.1f} GB
- 使用: {memory.used / 1024**3:.1f} GB ({memory.percent}%)
- 可用: {memory.available / 1024**3:.1f} GB

### 磁盘 (/)
- 总量: {disk.total / 1024**3:.1f} GB
- 使用: {disk.used / 1024**3:.1f} GB ({disk.percent}%)
- 可用: {disk.free / 1024**3:.1f} GB

### 网络 (累计)
- 接收: {net_io.bytes_recv / 1024**3:.2f} GB
- 发送: {net_io.bytes_sent / 1024**3:.2f} GB
"""
        return [TextContent(type="text", text=status)]

    elif name == "run_command":
        command = arguments.get("command", "")
        # 安全白名单(仅允许查看类命令)
        ALLOWED_PREFIXES = ["ls", "cat", "df", "du", "ps", "top", "netstat",
                           "docker ps", "kubectl get", "nginx -t", "systemctl status"]

        if not any(command.strip().startswith(p) for p in ALLOWED_PREFIXES):
            return [TextContent(type="text",
                text=f"❌ 命令被拒绝:{command}\n仅允许查看类命令")]

        try:
            result = subprocess.run(
                command, shell=True, capture_output=True,
                text=True, timeout=30
            )
            output = result.stdout or result.stderr
            return [TextContent(type="text",
                text=f"```\n$ {command}\n{output}\n```")]
        except subprocess.TimeoutExpired:
            return [TextContent(type="text", text="命令执行超时(30s)")]
        except Exception as e:
            return [TextContent(type="text", text=f"执行失败: {str(e)}")]

    elif name == "check_process":
        process_name = arguments.get("process_name", "")
        running_processes = [p.name() for p in psutil.process_iter(['name'])]
        is_running = any(process_name.lower() in p.lower()
                        for p in running_processes)

        status = "✅ 运行中" if is_running else "❌ 未运行"
        return [TextContent(type="text",
            text=f"进程 **{process_name}**: {status}")]

    return [TextContent(type="text", text=f"未知工具: {name}")]


async def main():
    async with stdio_server() as (read_stream, write_stream):
        await app.run(
            read_stream,
            write_stream,
            InitializationOptions(
                server_name="server-monitor",
                server_version="1.0.0",
            ),
        )

if __name__ == "__main__":
    asyncio.run(main())

注册到 Claude Desktop

{
  "mcpServers": {
    "server-monitor": {
      "command": "python",
      "args": ["/path/to/server_monitor_mcp.py"]
    }
  }
}

重启 Claude Desktop 后,你就可以这样和 Claude 对话:

你:帮我检查一下服务器状态,看看 MySQL 和 Nginx 是否正常运行,内存是否够用

Claude:好的,我来检查一下...
[调用 get_system_status 工具]
[调用 check_process:nginx]
[调用 check_process:mysql]

服务器状态报告:
- CPU 使用率:23%,内存使用:68%(还剩 5.2GB 可用),基本正常
- Nginx:✅ 运行中
- MySQL:✅ 运行中
目前服务器状态健康,无需操作。

第4步:用 Python API 调用 MCP Server(程序化)

# mcp_agent.py - 程序化使用 MCP
import asyncio
import anthropic
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def run_ai_agent_with_mcp():
    """启动 AI Agent,通过 MCP 调用服务器监控工具"""

    client = anthropic.Anthropic()

    # 连接到 MCP Server
    server_params = StdioServerParameters(
        command="python",
        args=["/path/to/server_monitor_mcp.py"]
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()

            # 获取工具列表
            tools_result = await session.list_tools()
            mcp_tools = tools_result.tools

            # 转换为 Claude API 格式
            claude_tools = [
                {
                    "name": tool.name,
                    "description": tool.description,
                    "input_schema": tool.inputSchema
                }
                for tool in mcp_tools
            ]

            messages = [
                {
                    "role": "user",
                    "content": "帮我全面检查服务器状态,特别关注 nginx 和 mysql 服务"
                }
            ]

            # 循环处理工具调用
            while True:
                response = client.messages.create(
                    model="claude-opus-4-5",
                    max_tokens=2048,
                    tools=claude_tools,
                    messages=messages
                )

                # 无工具调用,直接返回答案
                if response.stop_reason == "end_turn":
                    for block in response.content:
                        if hasattr(block, 'text'):
                            print(f"\n📊 AI 分析报告:\n{block.text}")
                    break

                # 处理工具调用
                if response.stop_reason == "tool_use":
                    messages.append({
                        "role": "assistant",
                        "content": response.content
                    })

                    tool_results = []
                    for block in response.content:
                        if block.type == "tool_use":
                            print(f"🔧 调用工具: {block.name}({block.input})")

                            # 通过 MCP 执行工具
                            result = await session.call_tool(
                                block.name,
                                arguments=block.input
                            )
                            tool_results.append({
                                "type": "tool_result",
                                "tool_use_id": block.id,
                                "content": result.content[0].text
                            })

                    messages.append({
                        "role": "user",
                        "content": tool_results
                    })

if __name__ == "__main__":
    asyncio.run(run_ai_agent_with_mcp())

实战效果展示

配置好 MCP 后,你可以对 Claude 说:

你的指令 Claude 的动作
“帮我把项目里所有 TODO 注释整理成文档” 读取文件 → 提取 TODO → 写入文档
“查一下数据库里昨天的订单数据有没有异常” 执行 SQL 查询 → 分析结果 → 生成报告
“帮我 review 这个 PR 的代码” 调用 GitHub MCP → 读取 diff → 给出建议
“检查服务器 CPU 为什么今天下午飙升” 查进程 → 看日志 → 分析原因

MCP 常用 Server 推荐

Server 功能 安装命令
@modelcontextprotocol/server-filesystem 文件读写 npx -y @mcp/server-filesystem
@modelcontextprotocol/server-github GitHub 操作 npx -y @mcp/server-github
@modelcontextprotocol/server-puppeteer 浏览器自动化 npx -y @mcp/server-puppeteer
mcp-server-sqlite SQLite 数据库 uvx mcp-server-sqlite
mcp-server-postgres PostgreSQL uvx mcp-server-postgres
mcp-server-kubernetes K8s 集群管理 uvx mcp-server-kubernetes
mcp-server-slack Slack 消息 uvx mcp-server-slack

踩坑指南

  1. MCP Server 启动失败:检查 Node.js/Python 版本,MCP SDK 要求 Node 18+ / Python 3.10+
  2. Claude Desktop 看不到工具:修改配置文件后必须完全退出重启,不能只关窗口
  3. 工具调用超时:MCP 默认超时 30s,长时间任务需要拆分或异步化
  4. 权限问题:文件系统 Server 只能访问配置时指定的目录,不能越权
  5. Windows 路径问题:配置文件中 Windows 路径需要用 \\ 或 / 转义

小结

MCP 打通了 AI 大模型与工具世界的最后一公里:

  • 标准化:一次开发,适配所有 MCP 兼容客户端
  • 安全可控:工具调用在本地运行,数据不出内网
  • 高度可扩展:官方 50+ Server,社区还在快速增长

用 Claude + MCP 打造一个专属 AI 工作站,从运维巡检到代码 Review 到数据分析,让 AI 真正帮你干活,而不仅仅是聊天。


👤 作者简介

一枚在大中原腹地(河南)卖公有云的男士,主营腾讯云/阿里云/华为云,曾踩坑无数,现专注AI大模型应用落地。关注公众号「AI热点日报」,围观AI前沿动态~

博客:y1cloud.cn

发表评论