关注公众号:weelinking | 访问官网:weelinking.com

📅 发布日期:2026年02月14日
🏷️ 标签:Claude | 安装 | 电脑端
⏱️ 阅读时长:15分钟
📚 系列文章:手机指挥电脑干活系列 - 第5篇


📄 文章摘要

上一篇打通了手机与电脑的通信,但 Claude 还只是"能聊天"的状态——就像请了个专家顾问,却只让他在电话里说说话。本文教你为 Claude 添加真正的工具调用能力:读写文件、执行系统命令、运行 Python 代码、操作 Git。改造完成后,你的 Claude 就从"聊天机器人"进化成了真正能操作电脑的 AI 助手。

关键词: #Claude #工具调用 #文件操作 #代码执行 #weelinking


一、前言:从"能聊天"到"能干活"

上一篇我们打通了手机与电脑的通信,但 Claude 还只是"能聊天"的状态。

这一篇我们要让 Claude 真正拥有"操作电脑"的能力:

  • ✅ 可以读写本地文件
  • ✅ 可以执行系统命令
  • ✅ 可以运行代码和测试
  • ✅ 可以使用各种开发工具

💡 本文所有操作均在 weelinking 上完成——国内直连 Claude,无需魔法,按量付费,新用户注册即送额度。

二、Claude Desktop 简介

Claude Desktop 是 Anthropic 官方推出的桌面客户端,但实际上目前(2026年2月)还在内测阶段。

所以我们采用更实用的方案:扩展上一篇的 Flask 服务,让 Claude 拥有工具调用能力

三、升级服务端:添加工具能力

3.1 工具系统设计

我们为 Claude 提供以下工具:

📁 文件操作:
├─ read_file    - 读取文件
├─ write_file   - 写入文件
├─ list_files   - 列出目录

🖥️ 系统操作:
├─ execute_command - 执行命令
├─ get_system_info - 获取系统信息

💻 开发工具:
├─ run_python   - 运行 Python 代码
├─ git_操作     - Git 命令封装

3.2 创建增强版服务端

创建新文件 server_advanced.py:

from flask import Flask, request, jsonify
from flask_cors import CORS
import anthropic
import os
import subprocess
import json
from pathlib import Path

app = Flask(__name__)
CORS(app)

# 配置
API_KEY = "你的API_KEY"  # 替换为你的 Weelinking API Key
BASE_URL = "https://api.weelinking.com/v1"

client = anthropic.Anthropic(api_key=API_KEY, base_url=BASE_URL)

# 工作目录(安全限制)
WORK_DIR = os.path.expanduser("~/claude_workspace")
os.makedirs(WORK_DIR, exist_ok=True)

# 定义工具
TOOLS = [
    {
        "name": "read_file",
        "description": "读取文件内容",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "文件路径"}
            },
            "required": ["path"]
        }
    },
    {
        "name": "write_file",
        "description": "写入文件内容",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "文件路径"},
                "content": {"type": "string", "description": "文件内容"}
            },
            "required": ["path", "content"]
        }
    },
    {
        "name": "list_files",
        "description": "列出目录下的文件",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "目录路径"}
            },
            "required": ["path"]
        }
    },
    {
        "name": "execute_command",
        "description": "执行系统命令",
        "input_schema": {
            "type": "object",
            "properties": {
                "command": {"type": "string", "description": "要执行的命令"}
            },
            "required": ["command"]
        }
    },
    {
        "name": "run_python",
        "description": "运行 Python 代码",
        "input_schema": {
            "type": "object",
            "properties": {
                "code": {"type": "string", "description": "Python 代码"}
            },
            "required": ["code"]
        }
    }
]

# 工具实现
def tool_read_file(path):
    """读取文件"""
    try:
        full_path = os.path.join(WORK_DIR, path)
        with open(full_path, 'r', encoding='utf-8') as f:
            content = f.read()
        return {"success": True, "content": content}
    except Exception as e:
        return {"success": False, "error": str(e)}

def tool_write_file(path, content):
    """写入文件"""
    try:
        full_path = os.path.join(WORK_DIR, path)
        os.makedirs(os.path.dirname(full_path), exist_ok=True)
        with open(full_path, 'w', encoding='utf-8') as f:
            f.write(content)
        return {"success": True, "message": f"文件已写入: {path}"}
    except Exception as e:
        return {"success": False, "error": str(e)}

def tool_list_files(path):
    """列出文件"""
    try:
        full_path = os.path.join(WORK_DIR, path)
        files = os.listdir(full_path)
        return {"success": True, "files": files}
    except Exception as e:
        return {"success": False, "error": str(e)}

def tool_execute_command(command):
    """执行命令"""
    try:
        result = subprocess.run(
            command,
            shell=True,
            cwd=WORK_DIR,
            capture_output=True,
            text=True,
            timeout=30
        )
        return {
            "success": True,
            "stdout": result.stdout,
            "stderr": result.stderr,
            "returncode": result.returncode
        }
    except Exception as e:
        return {"success": False, "error": str(e)}

def tool_run_python(code):
    """运行 Python 代码"""
    try:
        # 创建临时文件
        temp_file = os.path.join(WORK_DIR, "_temp_exec.py")
        with open(temp_file, 'w', encoding='utf-8') as f:
            f.write(code)

        # 执行
        result = subprocess.run(
            ['python', temp_file],
            capture_output=True,
            text=True,
            timeout=30
        )

        # 删除临时文件
        os.remove(temp_file)

        return {
            "success": True,
            "output": result.stdout,
            "error": result.stderr
        }
    except Exception as e:
        return {"success": False, "error": str(e)}

# 工具路由
def execute_tool(tool_name, tool_input):
    """执行工具"""
    if tool_name == "read_file":
        return tool_read_file(tool_input["path"])
    elif tool_name == "write_file":
        return tool_write_file(tool_input["path"], tool_input["content"])
    elif tool_name == "list_files":
        return tool_list_files(tool_input["path"])
    elif tool_name == "execute_command":
        return tool_execute_command(tool_input["command"])
    elif tool_name == "run_python":
        return tool_run_python(tool_input["code"])
    else:
        return {"success": False, "error": "未知工具"}

@app.route('/')
def home():
    return '''
    <h1>Claude Advanced Server</h1>
    <p>✅ 工具支持: 文件操作、命令执行、代码运行</p>
    <p>📁 工作目录: ~/claude_workspace</p>
    '''

@app.route('/api/chat', methods=['POST'])
def chat():
    """处理聊天请求(支持工具调用)"""
    try:
        data = request.json
        user_message = data.get('message', '')

        messages = [{"role": "user", "content": user_message}]

        # 循环处理工具调用
        while True:
            response = client.messages.create(
                model="claude-sonnet-4-20250514",
                max_tokens=4096,
                tools=TOOLS,
                messages=messages
            )

            # 检查是否需要调用工具
            if response.stop_reason == "tool_use":
                # 添加 assistant 的响应
                messages.append({
                    "role": "assistant",
                    "content": response.content
                })

                # 执行所有工具调用
                tool_results = []
                for block in response.content:
                    if block.type == "tool_use":
                        result = execute_tool(block.name, block.input)
                        tool_results.append({
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": json.dumps(result, ensure_ascii=False)
                        })

                # 添加工具结果
                messages.append({
                    "role": "user",
                    "content": tool_results
                })

            else:
                # 没有更多工具调用,返回最终结果
                final_text = ""
                for block in response.content:
                    if hasattr(block, 'text'):
                        final_text += block.text

                return jsonify({
                    'success': True,
                    'response': final_text
                })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/workspace', methods=['GET'])
def get_workspace():
    """获取工作目录信息"""
    return jsonify({
        'workspace': WORK_DIR,
        'exists': os.path.exists(WORK_DIR)
    })

if __name__ == '__main__':
    import socket
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)

    print("=" * 60)
    print("🚀 Claude Advanced Server 启动成功!")
    print("=" * 60)
    print(f"本地访问: http://localhost:5000")
    print(f"局域网访问: http://{local_ip}:5000")
    print(f"工作目录: {WORK_DIR}")
    print("=" * 60)
    print("支持的工具:")
    for tool in TOOLS:
        print(f"  ✓ {tool['name']}: {tool['description']}")
    print("=" * 60)

    app.run(host='0.0.0.0', port=5000, debug=False)

3.3 启动增强版服务

# 停止之前的服务(Ctrl+C)

# 启动新服务
python server_advanced.py

四、实战测试

4.1 测试文件操作

手机端发送:

创建一个文件 hello.txt,内容是 "Hello from Claude!"

Claude 会:

  1. 调用 write_file 工具
  2. 创建文件
  3. 返回确认消息

验证:

# 电脑上查看
cat ~/claude_workspace/hello.txt

4.2 测试代码运行

手机端发送:

写一个 Python 程序计算 1 到 100 的和,并运行它

Claude 会:

  1. 生成 Python 代码
  2. 调用 run_python 工具
  3. 返回运行结果: 5050

4.3 测试命令执行

查看工作目录下有哪些文件

Claude 会:

  1. 调用 list_files 工具
  2. 返回文件列表

4.4 复杂任务测试

创建一个网页 index.html,包含标题"我的博客"和一个文章列表,
然后列出工作目录的所有文件确认创建成功

Claude 会:

  1. 调用 write_file 创建 index.html
  2. 调用 list_files 列出文件
  3. 返回创建确认和文件列表

五、Git 操作支持

添加 Git 快捷工具:

# 在 TOOLS 列表中添加
{
    "name": "git_status",
    "description": "查看 Git 状态",
    "input_schema": {"type": "object", "properties": {}}
},
{
    "name": "git_commit",
    "description": "提交 Git 更改",
    "input_schema": {
        "type": "object",
        "properties": {
            "message": {"type": "string", "description": "提交信息"}
        },
        "required": ["message"]
    }
}

# 添加工具实现
def tool_git_status():
    return tool_execute_command("git status")

def tool_git_commit(message):
    commands = [
        "git add .",
        f'git commit -m "{message}"'
    ]
    results = []
    for cmd in commands:
        results.append(tool_execute_command(cmd))
    return {"success": True, "results": results}

现在可以用自然语言操作 Git 了:

查看当前 Git 状态
提交所有更改,message 写 "添加博客首页"

六、安全配置

6.1 工作目录限制

所有文件操作都限制在 ~/claude_workspace 目录下,防止误操作系统文件。

6.2 命令白名单

对于生产环境,建议添加命令白名单:

ALLOWED_COMMANDS = [
    'ls', 'dir', 'pwd', 'cat', 'git status', 'git log',
    'python', 'node', 'npm'
]

def is_command_safe(command):
    """检查命令是否安全"""
    cmd_base = command.split()[0]
    return cmd_base in ALLOWED_COMMANDS

def tool_execute_command(command):
    if not is_command_safe(command):
        return {"success": False, "error": f"不允许执行命令: {command}"}
    # ... 原有代码

6.3 操作日志

记录所有操作:

import logging

logging.basicConfig(
    filename='claude_operations.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s'
)

def execute_tool(tool_name, tool_input):
    logging.info(f"Tool: {tool_name}, Input: {tool_input}")
    result = # ... 执行工具
    logging.info(f"Result: {result}")
    return result

七、完整使用示例

示例1:创建一个完整的 Python 项目

手机端发送:

帮我创建一个 Python 项目:
1. 创建 main.py,实现一个简单的计算器(加减乘除)
2. 创建 test_main.py,包含单元测试
3. 运行测试
4. 创建 README.md,说明如何使用

Claude 会自动:

  1. 创建 main.py
  2. 创建 test_main.py
  3. 运行测试
  4. 创建 README.md
  5. 返回完整的执行报告

示例2:代码审查和优化

读取 main.py 文件,分析代码质量,提出改进建议并实施

Claude 会:

  1. 读取文件
  2. 分析代码
  3. 提出建议
  4. (可选)直接修改代码

看到这里,是不是想自己试试?

现在就可以开始——点击注册 weelinking,国内直连 Claude,新用户有免费额度,够你把今天的内容完整跑一遍。


八、常见问题

问题1:工具调用失败

检查:

  • 工作目录权限
  • Python 环境是否正确
  • 命令是否在 PATH 中

问题2:文件找不到

确保文件路径相对于工作目录:

# ✓ 正确
read_file("hello.txt")

# ✗ 错误
read_file("/home/user/hello.txt")

问题3:代码执行超时

调整 timeout 参数:

subprocess.run(..., timeout=60)  # 增加到 60 秒

九、总结与下期预告

本期完成的内容

  • ✅ 为 Claude 添加文件操作能力
  • ✅ 支持命令执行和代码运行
  • ✅ Git 操作集成
  • ✅ 安全限制和日志记录

系统现状

✅ 手机端客户端
✅ 电脑端服务器
✅ 通信链路
✅ Claude 工具能力
⏸️ 实战场景待演练

下期预告

第6篇:第一次远程指挥——手机发消息,电脑自动跑代码

  • 5 个真实任务演示
  • 从简单到复杂的渐进式体验
  • 最佳实践和使用技巧

现在,你的 Claude 已经是一个真正能"干活"的 AI 助手了!


🔗 开始使用 Claude

文中的所有操作,你现在就可以上手。

推荐使用 weelinking 访问 Claude:

优势 说明
🇨🇳 国内直连 无需任何网络配置,打开即用
💰 按量付费 用多少花多少,不浪费
🎁 新用户福利 注册即送体验额度
⚡ 稳定可靠 账号池技术,不掉线

👉 立即注册,免费开始


🔜 下期预告

「第一次远程指挥!手机发消息,电脑自动跑代码」

Claude 大脑已就绪,下一篇通过 5 个递进式实战任务,让你亲身体验手机指挥电脑干活的震撼效果——创建网页、运行代码、批量处理文件、Git 操作、构建完整应用!

👉 点击关注,下篇第一时间通知你。


📖 推荐阅读

如果这篇对你有帮助,以下文章你也会喜欢:

  • [Claude Skill 实战案例精选(上):开发类技能] — 实战学习 Claude 的开发类技能配置
  • [Claude Skill 高级技巧:模块化与可维护性] — 让你的 Claude 配置更专业
  • [数据分析师用 Claude 提效] — 用 Claude 搞定 SQL 和 Python 数据分析

📦 本篇配套资源

  • ✅ 增强版服务端完整代码(server_advanced.py)
  • ✅ 工具定义模板(5 个基础工具)
  • ✅ 安全配置指南
  • 📷 需补充:工具调用全过程截图

📌 系列导航: 手机+OpenClaw+Claude实现远程AI编程系列大纲

上一篇: 第4篇:打通任督二脉——手机与电脑的首次“握手“通信
下一篇: 第6篇:第一次远程指挥_手机发消息电脑自动跑代码

💡 本系列全程使用 weelinking 访问 Claude,国内可稳定使用
🚀 整个系列的核心理念:你不需要变成程序员,你只需要从"找人做"变成"自己能做"。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐