给claude desk写一个本地的mcp
本文主要是基于windows平台,基于claude desktop ,让他(自己给自己)写了一个pyhon实现的可获取到本地pc电脑配置的信息,细节之处包括python多环境管理配置、claude config的添加。 mcp的本质是协议层的约定。统一各大ai厂商的底层协议。这篇文章是ai写出了整体的代码,我这里记录下。 注意我以上的文件目录位置为 claude descktop配置文件位置 注意是增加 相关核心代码
1.test_hardware_info.py
#!/usr/bin/env python3
"""
硬件信息 MCP Server
提供读取电脑硬件配置信息的工具
"""
from mcp.server import Server
from mcp.types import Tool, TextContent
import mcp.server.stdio
import platform
import psutil
import socket
from datetime import datetime
import json
# 创建 MCP server 实例
server = Server("hardware-info-server")
def get_cpu_info() -> dict:
"""获取CPU信息"""
cpu_freq = psutil.cpu_freq()
return {
"处理器": platform.processor(),
"架构": platform.machine(),
"物理核心数": psutil.cpu_count(logical=False),
"逻辑核心数": psutil.cpu_count(logical=True),
"当前频率_MHz": round(cpu_freq.current, 2) if cpu_freq else "N/A",
"最大频率_MHz": round(cpu_freq.max, 2) if cpu_freq else "N/A",
"最小频率_MHz": round(cpu_freq.min, 2) if cpu_freq else "N/A",
"CPU使用率_%": psutil.cpu_percent(interval=1, percpu=False)
}
def get_memory_info() -> dict:
"""获取内存信息"""
mem = psutil.virtual_memory()
swap = psutil.swap_memory()
def bytes_to_gb(bytes_value):
return round(bytes_value / (1024**3), 2)
return {
"物理内存": {
"总量_GB": bytes_to_gb(mem.total),
"已用_GB": bytes_to_gb(mem.used),
"可用_GB": bytes_to_gb(mem.available),
"使用率_%": mem.percent
},
"交换内存": {
"总量_GB": bytes_to_gb(swap.total),
"已用_GB": bytes_to_gb(swap.used),
"空闲_GB": bytes_to_gb(swap.free),
"使用率_%": swap.percent
}
}
def get_disk_info() -> dict:
"""获取磁盘信息"""
partitions = psutil.disk_partitions()
disk_info = {}
def bytes_to_gb(bytes_value):
return round(bytes_value / (1024**3), 2)
for partition in partitions:
try:
usage = psutil.disk_usage(partition.mountpoint)
disk_info[partition.device] = {
"挂载点": partition.mountpoint,
"文件系统": partition.fstype,
"总容量_GB": bytes_to_gb(usage.total),
"已用_GB": bytes_to_gb(usage.used),
"空闲_GB": bytes_to_gb(usage.free),
"使用率_%": usage.percent
}
except PermissionError:
disk_info[partition.device] = {
"挂载点": partition.mountpoint,
"状态": "无访问权限"
}
return disk_info
def get_network_info() -> dict:
"""获取网络接口信息"""
net_if_addrs = psutil.net_if_addrs()
net_if_stats = psutil.net_if_stats()
network_info = {}
for interface_name, addresses in net_if_addrs.items():
interface_info = {
"地址列表": [],
"状态": "未知"
}
if interface_name in net_if_stats:
stats = net_if_stats[interface_name]
interface_info["状态"] = "启用" if stats.isup else "禁用"
interface_info["速度_Mbps"] = stats.speed
for addr in addresses:
addr_info = {
"地址族": str(addr.family),
"地址": addr.address
}
if addr.netmask:
addr_info["子网掩码"] = addr.netmask
if addr.broadcast:
addr_info["广播地址"] = addr.broadcast
interface_info["地址列表"].append(addr_info)
network_info[interface_name] = interface_info
return network_info
def get_system_info() -> dict:
"""获取系统基本信息"""
boot_time = datetime.fromtimestamp(psutil.boot_time())
return {
"系统": platform.system(),
"系统版本": platform.version(),
"系统发行版": platform.release(),
"主机名": socket.gethostname(),
"Python版本": platform.python_version(),
"开机时间": boot_time.strftime("%Y-%m-%d %H:%M:%S"),
"运行时长_小时": round((datetime.now() - boot_time).total_seconds() / 3600, 2)
}
def get_gpu_info() -> dict:
"""获取GPU信息"""
try:
import GPUtil
gpus = GPUtil.getGPUs()
if not gpus:
return {"消息": "未检测到GPU或无法访问GPU信息"}
gpu_info = {}
for i, gpu in enumerate(gpus):
gpu_info[f"GPU_{i}"] = {
"名称": gpu.name,
"显存总量_MB": gpu.memoryTotal,
"显存已用_MB": gpu.memoryUsed,
"显存空闲_MB": gpu.memoryFree,
"GPU负载_%": gpu.load * 100,
"温度_C": gpu.temperature
}
return gpu_info
except ImportError:
return {
"消息": "未安装GPUtil库",
"提示": "运行 'pip install gputil' 来获取GPU信息"
}
except Exception as e:
return {
"消息": "无法获取GPU信息",
"错误": str(e)
}
def get_battery_info() -> dict:
"""获取电池信息"""
if not hasattr(psutil, "sensors_battery"):
return {"消息": "当前平台不支持电池信息查询"}
battery = psutil.sensors_battery()
if battery is None:
return {"消息": "未检测到电池(可能是台式机)"}
return {
"电量_%": battery.percent,
"充电中": battery.power_plugged,
"剩余时间_分钟": round(battery.secsleft / 60, 2) if battery.secsleft != psutil.POWER_TIME_UNLIMITED else "充电中或无限"
}
def get_all_hardware_info() -> dict:
"""获取所有硬件信息的汇总"""
return {
"系统信息": get_system_info(),
"CPU信息": get_cpu_info(),
"内存信息": get_memory_info(),
"磁盘信息": get_disk_info(),
"网络信息": get_network_info(),
"GPU信息": get_gpu_info(),
"电池信息": get_battery_info()
}
@server.list_tools()
async def list_tools() -> list[Tool]:
"""列出所有可用工具"""
return [
Tool(
name="get_cpu_info",
description="获取CPU信息,包括核心数、频率、使用率等",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_memory_info",
description="获取内存信息,包括物理内存和交换内存的使用情况",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_disk_info",
description="获取磁盘信息,包括所有分区的容量和使用情况",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_network_info",
description="获取网络接口信息,包括IP地址、MAC地址等",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_system_info",
description="获取系统基本信息,包括操作系统、主机名、运行时长等",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_gpu_info",
description="获取GPU信息,包括显存、负载、温度等(需要NVIDIA GPU)",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_battery_info",
description="获取电池信息,包括电量、充电状态等(仅笔记本)",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="get_all_hardware_info",
description="获取所有硬件信息的完整汇总",
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
]
@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
"""执行工具调用"""
# 工具函数映射
tool_functions = {
"get_cpu_info": get_cpu_info,
"get_memory_info": get_memory_info,
"get_disk_info": get_disk_info,
"get_network_info": get_network_info,
"get_system_info": get_system_info,
"get_gpu_info": get_gpu_info,
"get_battery_info": get_battery_info,
"get_all_hardware_info": get_all_hardware_info,
}
if name not in tool_functions:
raise ValueError(f"未知工具: {name}")
try:
result = tool_functions[name]()
return [
TextContent(
type="text",
text=json.dumps(result, ensure_ascii=False, indent=2)
)
]
except Exception as e:
return [
TextContent(
type="text",
text=json.dumps({"错误": str(e)}, ensure_ascii=False)
)
]
async def main():
"""运行服务器"""
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options()
)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
"@ | Out-File -FilePath hardware_info_server.py -Encoding utf82.依赖配置requirements.txt
mcp>=1.0.0
psutil>=5.9.0
gputil>=1.4.0安装步骤
1.创建虚拟环境
python -m venv venv
# 激活虚拟环境
# Windows:
venv\Scripts\activate
# macOS/Linux:
source venv/bin/activate
# 安装依赖
pip install -r requirements.txt2. 配置文件更改
C:\Users\volvo\Downloads
windows为 C:\Users\volvo\AppData\Roaming\Claude,通用配置文件:%APPDATA%\Claude\claude_desktop_config.jsonmcpServers 字段配置{
"mcpServers": {
"hardware-info": {
"command": "C:\\Users\\volvo\\Downloads\\venv\\Scripts\\python.exe",
"args": [
"C:\\Users\\volvo\\Downloads\\hardware_info_server.py"
]
}
},
"preferences": {
"coworkScheduledTasksEnabled": false,
"sidebarMode": "chat"
}
}注意事项
node版本不能太低
(venv) PS C:\Users\volvo\Downloads> nvm list
22.12.0
18.18.2
16.20.2
16.18.0
* 14.15.0 (Currently using 64-bit executable)
(venv) PS C:\Users\volvo\Downloads> nvm use 22.12.0
Now using node v22.12.0 (64-bit)
(venv) PS C:\Users\volvo\Downloads> npx @modelcontextprotocol/inspector python hardware_info_server.py
Need to install the following packages:
@modelcontextprotocol/inspector@0.19.0
Ok to proceed? (y) y
npm warn deprecated node-domexception@1.0.0: Use your platform's native DOMException instead
Starting MCP inspector...
⚙️ Proxy server listening on localhost:6277
🔑 Session token: 6f5e50390c183e0382b034b144bf806ffe2a33caf18e44bcbb0167c3bb6b1ade
Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth
🚀 MCP Inspector is up and running at:
http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=6f5e50390c183e0382b034b144bf806ffe2a33caf18e44bcbb0167c3bb6b1ade
🌐 Opening browser...
New STDIO connection request
Query parameters: {"command":"python","args":"hardware_info_server.py","env":"{\"APPDATA\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\",\"HOMEDRIVE\":\"C:\",\"HOMEPATH\":\"\\\\Users\\\\volvo\",\"LOCALAPPDATA\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Local\",\"PATH\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\npm-cache\\\\_npx\\\\5a9d879542beca3a\\\\node_modules\\\\.bin;C:\\\\Users\\\\volvo\\\\Downloads\\\\node_modules\\\\.bin;C:\\\\Users\\\\volvo\\\\node_modules\\\\.bin;C:\\\\Users\\\\node_modules\\\\.bin;C:\\\\node_modules\\\\.bin;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\nvm\\\\v22.12.0\\\\node_modules\\\\npm\\\\node_modules\\\\@npmcli\\\\run-script\\\\lib\\\\node-gyp-bin;C:\\\\Users\\\\volvo\\\\Downloads\\\\venv\\\\Scripts;D:\\\\go\\\\bin;C:\\\\Python313\\\\Scripts\\\\;C:\\\\Python313\\\\;C:\\\\Program Files\\\\Eclipse Adoptium\\\\jdk-8.0.442.6-hotspot\\\\bin;C:\\\\Program Files\\\\Python310\\\\Scripts\\\\;C:\\\\Program Files\\\\Python310\\\\;C:\\\\Program Files (x86)\\\\Intel\\\\iCLS Client\\\\;C:\\\\Program Files\\\\Intel\\\\iCLS Client\\\\;C:\\\\Windows\\\\system32;C:\\\\Windows;C:\\\\Windows\\\\System32\\\\Wbem;C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\Program Files (x86)\\\\Intel\\\\Intel(R) Management Engine Components\\\\DAL;C:\\\\Program Files\\\\Intel\\\\Intel(R) Management Engine Components\\\\DAL;C:\\\\Program Files (x86)\\\\Intel\\\\Intel(R) Management Engine Components\\\\IPT;C:\\\\Program Files\\\\Intel\\\\Intel(R) Management Engine Components\\\\IPT;C:\\\\Program Files (x86)\\\\NVIDIA Corporation\\\\PhysX\\\\Common;C:\\\\Program Files\\\\Intel\\\\WiFi\\\\bin\\\\;C:\\\\Program Files\\\\Common Files\\\\Intel\\\\WirelessCommon\\\\;C:\\\\WINDOWS\\\\system32;C:\\\\WINDOWS;C:\\\\WINDOWS\\\\System32\\\\Wbem;C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\WINDOWS\\\\System32\\\\OpenSSH\\\\;C:\\\\Program Files\\\\Git\\\\cmd;C:\\\\Program Files\\\\NVIDIA Corporation\\\\NVIDIA NvDLISR;C:\\\\phpstudy_pro\\\\Extensions\\\\php\\\\php7.3.4nts;C:\\\\Program Files;C:\\\\Program Files (x86)\\\\NetSarang\\\\Xshell 8\\\\;C:\\\\ProgramData\\\\ComposerSetup\\\\bin;D:\\\\softInstall\\\\mcpuvx;c:\\\\Program Files\\\\TraeInternational\\\\bin;C:\\\\Program Files\\\\platform-tools;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\pnpm;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps;C:\\\\Program Files\\\\Go\\\\bin;C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\\\\nvm;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Links;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\\\\Schniz.fnm_Microsoft.Winget.Source_8wekyb3d8bbwe;C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\\\\Composer\\\\vendor\\\\bin;C:\\\\Users\\\\volvo\\\\.dotnet\\\\tools;C:\\\\Program Files (x86)\\\\GnuWin32\\\\bin;C:\\\\Users\\\\volvo\\\\Desktop\\\\infoSetUp\\\\soft\\\\1011\\\\platformTool;C:\\\\devENV\\\\apache-maven-3.9.9-bin\\\\apache-maven-3.9.9\\\\bin;C:\\\\Users\\\\volvo\\\\.dotnet\\\\tools;C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\\\\npm;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\nvm;C:\\\\nvm4w\\\\nodejs;D:\\\\softpath\\\\adbtools\\\\1011\\\\platformTool;C:\\\\Users\\\\volvo\\\\Desktop\\\\beetercall\\\\v1\\\\infoSetUp\\\\adb\\\\1011\\\\platformTool;D:\\\\softInstall\\\\networkCatch\\\\Fiddler\",\"PROCESSOR_ARCHITECTURE\":\"AMD64\",\"SYSTEMDRIVE\":\"C:\",\"SYSTEMROOT\":\"C:\\\\WINDOWS\",\"TEMP\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Temp\",\"USERNAME\":\"volvo\",\"USERPROFILE\":\"C:\\\\Users\\\\volvo\",\"PROGRAMFILES\":\"C:\\\\Program Files\"}","transportType":"stdio"}
STDIO transport: command=C:\Users\volvo\Downloads\venv\Scripts\python.exe, args=hardware_info_server.py
Created client transport
Created server transport
Received POST message for sessionId 55ac8b56-f912-4243-81d6-ae2c56e5a92d
New STDIO connection request
Query parameters: {"command":"python","args":"hardware_info_server.py","env":"{\"APPDATA\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\",\"HOMEDRIVE\":\"C:\",\"HOMEPATH\":\"\\\\Users\\\\volvo\",\"LOCALAPPDATA\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Local\",\"PATH\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\npm-cache\\\\_npx\\\\5a9d879542beca3a\\\\node_modules\\\\.bin;C:\\\\Users\\\\volvo\\\\Downloads\\\\node_modules\\\\.bin;C:\\\\Users\\\\volvo\\\\node_modules\\\\.bin;C:\\\\Users\\\\node_modules\\\\.bin;C:\\\\node_modules\\\\.bin;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\nvm\\\\v22.12.0\\\\node_modules\\\\npm\\\\node_modules\\\\@npmcli\\\\run-script\\\\lib\\\\node-gyp-bin;C:\\\\Users\\\\volvo\\\\Downloads\\\\venv\\\\Scripts;D:\\\\go\\\\bin;C:\\\\Python313\\\\Scripts\\\\;C:\\\\Python313\\\\;C:\\\\Program Files\\\\Eclipse Adoptium\\\\jdk-8.0.442.6-hotspot\\\\bin;C:\\\\Program Files\\\\Python310\\\\Scripts\\\\;C:\\\\Program Files\\\\Python310\\\\;C:\\\\Program Files (x86)\\\\Intel\\\\iCLS Client\\\\;C:\\\\Program Files\\\\Intel\\\\iCLS Client\\\\;C:\\\\Windows\\\\system32;C:\\\\Windows;C:\\\\Windows\\\\System32\\\\Wbem;C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\Program Files (x86)\\\\Intel\\\\Intel(R) Management Engine Components\\\\DAL;C:\\\\Program Files\\\\Intel\\\\Intel(R) Management Engine Components\\\\DAL;C:\\\\Program Files (x86)\\\\Intel\\\\Intel(R) Management Engine Components\\\\IPT;C:\\\\Program Files\\\\Intel\\\\Intel(R) Management Engine Components\\\\IPT;C:\\\\Program Files (x86)\\\\NVIDIA Corporation\\\\PhysX\\\\Common;C:\\\\Program Files\\\\Intel\\\\WiFi\\\\bin\\\\;C:\\\\Program Files\\\\Common Files\\\\Intel\\\\WirelessCommon\\\\;C:\\\\WINDOWS\\\\system32;C:\\\\WINDOWS;C:\\\\WINDOWS\\\\System32\\\\Wbem;C:\\\\WINDOWS\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\WINDOWS\\\\System32\\\\OpenSSH\\\\;C:\\\\Program Files\\\\Git\\\\cmd;C:\\\\Program Files\\\\NVIDIA Corporation\\\\NVIDIA NvDLISR;C:\\\\phpstudy_pro\\\\Extensions\\\\php\\\\php7.3.4nts;C:\\\\Program Files;C:\\\\Program Files (x86)\\\\NetSarang\\\\Xshell 8\\\\;C:\\\\ProgramData\\\\ComposerSetup\\\\bin;D:\\\\softInstall\\\\mcpuvx;c:\\\\Program Files\\\\TraeInternational\\\\bin;C:\\\\Program Files\\\\platform-tools;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\pnpm;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps;C:\\\\Program Files\\\\Go\\\\bin;C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\\\\nvm;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Links;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Microsoft\\\\WinGet\\\\Packages\\\\Schniz.fnm_Microsoft.Winget.Source_8wekyb3d8bbwe;C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\\\\Composer\\\\vendor\\\\bin;C:\\\\Users\\\\volvo\\\\.dotnet\\\\tools;C:\\\\Program Files (x86)\\\\GnuWin32\\\\bin;C:\\\\Users\\\\volvo\\\\Desktop\\\\infoSetUp\\\\soft\\\\1011\\\\platformTool;C:\\\\devENV\\\\apache-maven-3.9.9-bin\\\\apache-maven-3.9.9\\\\bin;C:\\\\Users\\\\volvo\\\\.dotnet\\\\tools;C:\\\\Users\\\\volvo\\\\AppData\\\\Roaming\\\\npm;C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\nvm;C:\\\\nvm4w\\\\nodejs;D:\\\\softpath\\\\adbtools\\\\1011\\\\platformTool;C:\\\\Users\\\\volvo\\\\Desktop\\\\beetercall\\\\v1\\\\infoSetUp\\\\adb\\\\1011\\\\platformTool;D:\\\\softInstall\\\\networkCatch\\\\Fiddler\",\"PROCESSOR_ARCHITECTURE\":\"AMD64\",\"SYSTEMDRIVE\":\"C:\",\"SYSTEMROOT\":\"C:\\\\WINDOWS\",\"TEMP\":\"C:\\\\Users\\\\volvo\\\\AppData\\\\Local\\\\Temp\",\"USERNAME\":\"volvo\",\"USERPROFILE\":\"C:\\\\Users\\\\volvo\",\"PROGRAMFILES\":\"C:\\\\Program Files\"}","transportType":"stdio"}
STDIO transport: command=C:\Users\volvo\Downloads\venv\Scripts\python.exe, args=hardware_info_server.py
Created client transport
Created server transport
Received POST message for sessionId 6e8c342f-e65d-4c83-bf7f-e1da6c8afc76
Received POST message for sessionId 55ac8b56-f912-4243-81d6-ae2c56e5a92d
Received POST message for sessionId 6e8c342f-e65d-4c83-bf7f-e1da6c8afc76
Received POST message for sessionId 6e8c342f-e65d-4c83-bf7f-e1da6c8afc76
Received POST message for sessionId 6e8c342f-e65d-4c83-bf7f-e1da6c8afc76
Received POST message for sessionId 6e8c342f-e65d-4c83-bf7f-e1da6c8afc76
Starting MCP inspector...
⚙️ Proxy server listening on localhost:6277
🔑 Session token: 72a7e06967c2e25056a4e58a3743d6eee509eacbbb6754744a74142f999c0d90
Use this token to authenticate requests or set DANGEROUSLY_OMIT_AUTH=true to disable auth
🚀 MCP Inspector is up and running at:
http://localhost:6274/?MCP_PROXY_AUTH_TOKEN=72a7e06967c2e25056a4e58a3743d6eee509eacbbb6754744a74142f999c0d90
🌐 Opening browser...本地会有一个mcp inspector

相关文档
相关配置图片
配置好claude的config.json后就可以看到这个mcp

然后就可以让agent调用ai,让ai发命令去读取基于mcp 实现的tool,需要授权

可以看到调用成功了
