Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
185 lines (169 loc) · 5.54 KB
/
Copy pathserver.js
File metadata and controls
185 lines (169 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#!/usr/bin/env node
// Local MCP server that analyzes images through any OpenAI-compatible endpoint.
//
// Flow: the opencode-vision plugin saves a pasted image to a temp file and tells the
// model to call the `local_vision` tool with that path. This server reads the file,
// encodes it as a base64 data URL, and sends it to an OpenAI-compatible
// /chat/completions endpoint (e.g. an OmniRoute / LiteLLM gateway, or OpenAI directly)
// using a vision-capable model. The model's text description is returned to opencode.
//
// Configure via env: VISION_BASE_URL, VISION_API_KEY, VISION_MODEL, VISION_MAX_TOKENS.
// Tip: point VISION_MODEL at a gateway alias so the underlying model can be swapped
// centrally without touching this server.
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { readFile } from "node:fs/promises";
import { extname } from "node:path";
const BASE_URL = process.env.VISION_BASE_URL || "http://localhost:20128/v1";
const API_KEY = process.env.VISION_API_KEY || "";
const MODEL = process.env.VISION_MODEL || "gpt-4o";
const MAX_TOKENS = Number(process.env.VISION_MAX_TOKENS || 1024);
const EXT_TO_MIME = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".webp": "image/webp",
".gif": "image/gif",
};
function mimeForPath(p) {
return EXT_TO_MIME[extname(p).toLowerCase()] || "image/png";
}
async function analyzeImage(path, question) {
const buf = await readFile(path); // throws if missing -> surfaced as tool error
const dataUrl = `data:${mimeForPath(path)};base64,${buf.toString("base64")}`;
const body = {
model: MODEL,
max_tokens: MAX_TOKENS,
messages: [
{
role: "user",
content: [
{
type: "text",
text:
question && question.trim()
? question
: "Describe this image in detail. Transcribe any visible text verbatim.",
},
{ type: "image_url", image_url: { url: dataUrl } },
],
},
],
};
const headers = { "Content-Type": "application/json" };
if (API_KEY) headers["Authorization"] = `Bearer ${API_KEY}`;
const res = await fetch(`${BASE_URL}/chat/completions`, {
method: "POST",
headers,
body: JSON.stringify(body),
});
const text = await res.text();
if (!res.ok) {
throw new Error(`vision upstream HTTP ${res.status}: ${text.slice(0, 500)}`);
}
// Endpoint may answer as JSON or as SSE stream depending on OmniRoute settings.
let content = parseJsonContent(text);
if (content == null) content = parseSseContent(text);
if (content == null) {
throw new Error(`could not parse vision response: ${text.slice(0, 500)}`);
}
return content;
}
function parseJsonContent(text) {
try {
const j = JSON.parse(text);
const c = j?.choices?.[0]?.message?.content;
if (typeof c === "string") return c;
if (Array.isArray(c)) {
return c.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("");
}
return null;
} catch {
return null;
}
}
function parseSseContent(text) {
let out = "";
let sawData = false;
for (const line of text.split(/\r?\n/)) {
const t = line.trim();
if (!t.startsWith("data:")) continue;
const payload = t.slice(5).trim();
if (payload === "" || payload === "[DONE]") continue;
sawData = true;
try {
const j = JSON.parse(payload);
const delta = j?.choices?.[0]?.delta?.content;
if (typeof delta === "string") out += delta;
const msg = j?.choices?.[0]?.message?.content;
if (typeof msg === "string") out += msg;
} catch {
// ignore non-JSON data lines
}
}
return sawData ? out : null;
}
const server = new Server(
{ name: "local-vision-mcp", version: "1.0.0" },
{ capabilities: { tools: {} } },
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: "vision",
description:
"Analyze a local image file using a vision-capable model and return a text description. " +
"Use this whenever the user shares an image/screenshot. Pass the absolute file path.",
inputSchema: {
type: "object",
properties: {
path: {
type: "string",
description: "Absolute path to the image file on disk.",
},
question: {
type: "string",
description:
"Optional. What to look for or ask about the image. Defaults to a full description.",
},
},
required: ["path"],
},
},
],
}));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
if (req.params.name !== "vision") {
return {
isError: true,
content: [{ type: "text", text: `Unknown tool: ${req.params.name}` }],
};
}
const { path, question } = req.params.arguments ?? {};
if (!path || typeof path !== "string") {
return {
isError: true,
content: [{ type: "text", text: "Missing required 'path' argument." }],
};
}
try {
const description = await analyzeImage(path, question);
return { content: [{ type: "text", text: description }] };
} catch (err) {
return {
isError: true,
content: [
{
type: "text",
text: `Vision analysis failed: ${err instanceof Error ? err.message : String(err)}`,
},
],
};
}
});
const transport = new StdioServerTransport();
await server.connect(transport);