一个简单的mcp屏幕识别
这个项目是一个使用 FastMCP 框架实现的屏幕截图工具,它能够捕获屏幕内容,并通过 Ollama API 或者是阿里云的 Dashscope 发送给视觉模型进行分析。 - **屏幕截图**:使用 `ImageGrab` 捕获整个屏幕,并调整图像大小 python from PIL import ImageGrab screenshot = ImageGrab.grab() resized_image = screenshot.resize((800, 600)) - **Base64 编码**:将截图转换为 Base64 编码的 data URL python import base64 from io import BytesIO buffered = BytesIO() resized_image.save(buffered, format="PNG") img_str = base64.b64encode(buffered.getvalue()).decode("utf-8") data_url = f"data:image/png;base64,{img_str}" - **Ollama API 调用**:将 Base64 编码的图像发送给 Ollama API python import requests url = "https://api.ollama.com/analyze" headers = { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_KEY" } payload = { "image": data_url } response = requests.post(url, headers=headers, json=payload) print(response.json())
MCP 服务配置
复制以下 JSON 到 OPClaw 或其他 MCP 客户端的配置文件中即可使用
{
"mcpServers": {
"会生成一个去cherry studio添加新服务器会自动生成": {
"baseUrl": "http://127.0.0.1:8000/sse",
"description": "",
"isActive": true,
"name": "MCP 服务器",
"type": "sse"
}
}
}
服务介绍
一个简单的捕获屏幕的mcp🦊
这个项目是一个使用 FastMCP 框架实现的屏幕截图工具,它能够捕获屏幕内容,并通过 Ollama API 或者是阿里云的 Dashscope 发送给视觉模型进行分析。
功能描述
- 屏幕截图:使用
ImageGrab捕获整个屏幕,并调整图像大小 - Base64 编码:将截图转换为 Base64 编码的 data URL
- Ollama API 调用:将 Base64 编码的图像发送给 Ollama API 进行分析,以识别图像内容
- 结果返回:将 Ollama API 返回的结果返回给用户
注意事项🚨
- 请确保 Ollama API 已经运行,或者你已正确配置了 Dashscope API 的地址和模型名称
- 本示例使用了
qwen2.5vl:7b作为视觉模型,你可以根据需要替换为其他模型 - 请根据你的需求调整图像的缩放倍数(4050跑视觉模型什么的还是太勉强了😭……建议真的缩放倍率开高一点)
没打包 pypi 下面是原代码
使用 dashscope
python
from mcp.server import FastMCP
import os
import base64
from openai import OpenAI
from PIL import ImageGrab
mcp = FastMCP('DEMO')
@mcp.tool()
def get_screen() -> str:
"""获取屏幕上的内容(无需传入信息)"""
# 捕获整个屏幕
img = ImageGrab.grab()
# 这里写缩放倍数
scale_factor = 0.5
# 计算新的尺寸
new_width = int(img.width * scale_factor)
new_height = int(img.height * scale_factor)
# 调整图像大小
img = img.resize((new_width, new_height))
# 保存截图
img.save('screenshot.jpg')
print('已截屏!')
# 将本地图片转换为 base64 编码的 data URL
def image_to_data_url(file_path):
with open(file_path, "rb") as image_file:
encoded_str = base64.b64encode(image_file.read()).decode("utf-8")
mime_type = "image/jpeg" # 根据你的图片类型修改,如 image/png
return f"data:{mime_type};base64,{encoded_str}"
# 初始化客户端
client = OpenAI(
api_key='YOUR_API_KEY', # 请先设置环境变量
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
try:
# 本地图片路径
local_image_path = "screenshot.jpg" # 替换为你的图片路径
# 转换为 data URL
image_data_url = image_to_data_url(local_image_path)
# 调用模型
completion = client.chat.completions.create(
model="qwen-vl-plus", # 可替换为 qwen-vl-max 等
messages=[
{
"role": "user",
"content": [
{"type": "image_url", "image_url": {"url": image_data_url}},
{"type": "text", "text": "这是什么?(简单回答一下)"},
],
}
],
)
# 输出模型的回答
# print(completion.choices[0].message.content)
return completion.choices[0].message.content
except Exception as e:
print(f"调用失败: {e}")
if name == 'main':
mcp.run(transport="sse") # 可以配置为stdio或者sse
使用 Ollama
python
from mcp.server import FastMCP
import os
import base64
import requests
from PIL import ImageGrab
mcp = FastMCP('DEMO')
@mcp.tool()
def get_screen() -> str:
"""获取屏幕上的内容并使用视觉模型识别"""
# 捕获整个屏幕
img = ImageGrab.grab()
# 这里写缩放倍数
scale_factor = 0.5
# 计算新的尺寸
new_width = int(img.width * scale_factor)
new_height = int(img.height * scale_factor)
# 调整图像大小
img = img.resize((new_width, new_height))
# 保存截图
img.save('screenshot.jpg')
print('已截屏!')
# 图像转 base64
def image_to_base64(file_path):
with open(file_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
image_base64 = image_to_base64("screenshot.jpg")
# 使用 Ollama
ollama_api_url = "http://localhost:11434/api/chat" # 你的api
headers = {
"Content-Type": "application/json"
}
# 芝士payload
payload = {
"model": "qwen2.5vl:7b", # 一定要是视觉模型啊!
"messages": [
{
"role": "user",
"content": "请描述这张图片的内容,或回答相关问题。",
"images": [image_base64]
}
],
"stream": False
}
try:
response = requests.post(ollama_api_url, json=payload, headers=headers)
response.raise_for_status()
result = response.json().get("message", {}).get("content", "")
return result
except Exception as e:
print(f"调用 Ollama 失败: {e}")
return f"识别失败: {str(e)}"
if name == 'main':
mcp.run(transport="sse") # 或者用stdio也行(装了uv前提下)